# eRPC documentation — llms-full.txt > Source: https://docs.erpc.cloud/ > Every docs page concatenated into a single machine-readable file. > For the navigable index, fetch /llms.txt instead. --- # eRPC vs dRPC NodeCore > Source: https://docs.erpc.cloud/compare/erpc-vs-drpc-nodecore > eRPC vs drpc nodecore feature by feature, with a source link in every cell, and where NodeCore is the better fit. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # eRPC vs dRPC NodeCore [NodeCore](https://github.com/drpcorg/nodecore) is dRPC's open-source RPC stack in Go. It covers 15+ chain families over JSON-RPC, REST and gRPC, and links to dRPC's hosted network. eRPC is an EVM and Solana JSON-RPC proxy built around failover, a finality-aware cache, and cost control. Every cell below links to the page or line that states it. Facts were checked on 2026-10-22. ## Feature table | | eRPC | dRPC NodeCore | |---|---|---| | Language, license | Go, Apache-2.0 ([LICENSE](https://github.com/erpc/erpc/blob/32a8a1e450c6ab5a78477859c85221b6a9058c72/LICENSE#L1)) | Go, MIT ([go.mod](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/go.mod#L3), [LICENSE](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/LICENSE#L1)) | | Latest release | 0.4.0, 2026-10-11 ([release](https://github.com/erpc/erpc/releases/tag/0.4.0)) | 1.17.1, 2026-10-22 ([release](https://github.com/drpcorg/nodecore/releases/tag/1.17.1)) | | Chains | EVM and Solana ([networks](/config/projects/networks.llms.txt)) | EVM, Solana, Bitcoin, Starknet, TON, Cosmos, Sui, Aptos and more ([README](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/README.md#L16)) | | Upstream protocols | JSON-RPC over HTTP and WebSocket, gRPC ([upstreams](/config/projects/upstreams.llms.txt)) | JSON-RPC, WebSocket, REST, Tendermint, gRPC ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L593-L640)) | | Config | YAML or TypeScript ([quick start](/)) | YAML, reload on SIGHUP or file change ([config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/01-config.md#L270-L290)) | | Upstream selection | Score from errors, latency, 429s, block lag; JS policy ([selection policies](/config/projects/selection-policies.llms.txt)) | Score from latency, error rate, lag; custom TypeScript scoring ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L378-L446)) | | Failover and retry | Yes, per method ([retry](/config/failsafe/retry.llms.txt)) | Yes, backoff and jitter ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L244-L295)) | | Hedged requests | Yes ([hedge](/config/failsafe/hedge.llms.txt)) | Yes ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L273-L295)) | | Circuit breaker | Yes ([circuit breaker](/config/failsafe/circuit-breaker.llms.txt)) | No named breaker; validators and method bans remove upstreams ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L778-L848)) | | Cross-checking answers | Consensus across any N upstreams ([consensus](/config/failsafe/consensus.llms.txt)) | Quorum over signed responses from dRPC providers ([quorum](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/10-quorum.md#L1-L49)) | | Integrity | Tip and range guards, opt-in schema checks ([integrity](/config/failsafe/integrity.llms.txt)) | Block numbers never go back; lag, chain-id, log-index validators ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L225-L242)) | | Cache | Memory, Redis, PostgreSQL, DynamoDB; finality-aware ([drivers](/config/database/drivers.llms.txt), [cache](/config/database/evm-json-rpc-cache.llms.txt)) | Memory, Redis, PostgreSQL; finalized-only policies ([cache](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/04-cache.md#L72-L158)) | | Rate limits | Per client, project, network, upstream ([rate limiters](/config/rate-limiters.llms.txt)) | Upstream side, with auto-tune ([rate limiting](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/06-rate-limiting.md#L1-L48)) | | Client auth | Secret, JWT, SIWE, IP, database ([auth](/config/auth.llms.txt)) | Token, JWT, API keys with IP, method and contract allowlists ([auth](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/03-auth.md#L66-L215)) | | `eth_getLogs` splitting | Yes ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)) | Not documented ([request_processor.go](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/internal/upstreams/flow/request_processor.go#L318-L331)) | | JSON-RPC batch | Yes ([batch](/operation/batch.llms.txt)) | Yes ([batch e2e test](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/test/e2e/http/batch_e2e_test.go#L15-L40)) | | Subscriptions | EVM `eth_subscribe` only; shared across clients ([websocket](/operation/websocket.llms.txt)) | EVM and other chain families, Solana included; shared across clients ([subscriptions](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/13-subscriptions.md#L1-L30)) | | Metrics, tracing | Prometheus, OpenTelemetry ([monitoring](/operation/monitoring.llms.txt), [tracing](/operation/tracing.llms.txt)) | Prometheus, Pyroscope ([metrics](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/08-prometheus-metrics.md), [server config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/02-server-config.md#L42)) | | Archive routing | Block availability per upstream ([upstreams](/config/projects/upstreams.llms.txt)) | Detects each upstream's lowest block and routes by height ([upstream config](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/05-upstream-config.md#L742-L760)) | | Deployment | Binaries, Docker, Kubernetes manifests, `npx start-erpc` ([docker](/deployment/docker.llms.txt), [kubernetes](/deployment/kubernetes.llms.txt)) | Binaries, Docker, Helm chart ([README](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/README.md#L125-L129), [chart](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/chart/nodecore/README.md#L10)) | | Hosted option | Managed instances ([cloud](/deployment/cloud.llms.txt)) | dRPC NodeCloud; keys can sync from it ([integration](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/09-integration.md#L12-L30)) | "Not documented" means the NodeCore docs do not describe it and a search of its source found no code for it. The [dRPC NodeCore page](https://drpc.org/docs/nodecore-open-source-rpc-stack) also lists a circuit breaker and OpenTelemetry traces. The open-source repo at the commit above does not document them, so the table does not count them. ## Where NodeCore is stronger - **Chain coverage.** 15+ chain families, with REST, Tendermint and gRPC upstreams ([README](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/README.md#L16)). eRPC serves EVM and Solana only. - **Subscriptions beyond EVM.** Solana and other chain families, and EVM streams built from all upstreams together ([subscriptions](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/13-subscriptions.md#L1-L30)). eRPC serves only EVM `eth_subscribe`. - **Signed-response quorum** with dRPC providers ([quorum](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/10-quorum.md#L32-L38)). - **Contract allowlists per API key** for `eth_call` and `eth_getLogs` ([auth](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/docs/nodecore/03-auth.md#L172-L207)). - **Official Helm chart** ([chart](https://github.com/drpcorg/nodecore/blob/8d8d79af258b5f7897ec77709eb495c29e744973/chart/nodecore/README.md#L10)). eRPC ships raw manifests ([kubernetes](/deployment/kubernetes.llms.txt)). ## Where eRPC is stronger - Consensus across any upstreams, not only signed ones ([consensus](/config/failsafe/consensus.llms.txt)). - Circuit breaker and OpenTelemetry tracing in the open-source code ([circuit breaker](/config/failsafe/circuit-breaker.llms.txt), [tracing](/operation/tracing.llms.txt)). - `eth_getLogs` range splitting ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)). - Rate limits on clients, projects and networks, not only upstreams ([rate limiters](/config/rate-limiters.llms.txt)). - DynamoDB cache driver and finality-aware cache buckets ([cache](/config/database/evm-json-rpc-cache.llms.txt)). - Config in TypeScript, with typed selection policies ([selection policies](/config/projects/selection-policies.llms.txt)). --- ### eRPC vs dRPC NodeCore — agent reference ### Sources and snapshot - eRPC: `erpc/erpc` at `32a8a1e450c6ab5a78477859c85221b6a9058c72`, docs at docs.erpc.cloud. - NodeCore: `drpcorg/nodecore` at `8d8d79af258b5f7897ec77709eb495c29e744973` (2026-10-22), docs in `docs/nodecore/`. - Checked 2026-10-22. NodeCore cuts releases often; re-check rows before you rely on them. Absence claims rest on its docs and a source search of `internal/`. ### Moving from NodeCore to eRPC | NodeCore concept | eRPC equivalent | |---|---| | `upstream-config.upstreams[]` | `projects[].upstreams[]` ([upstreams](/config/projects/upstreams.llms.txt)) | | `chain: ethereum` | `networks[].evm.chainId: 1` ([networks](/config/projects/networks.llms.txt)) | | `failsafe-config.retry` / `hedge` | `failsafe[].retry` / `failsafe[].hedge` ([retry](/config/failsafe/retry.llms.txt), [hedge](/config/failsafe/hedge.llms.txt)) | | TypeScript scoring function | selection policy ([selection policies](/config/projects/selection-policies.llms.txt)) | | cache policies | `database.evmJsonRpcCache.policies` ([cache](/config/database/evm-json-rpc-cache.llms.txt)) | ### Keep NodeCore when - You serve non-EVM, non-Solana chains. - You route to dRPC providers and want their signed-response quorum. ### Related pages - [Why eRPC?](/why.llms.txt) - [eRPC vs dshackle](/compare/erpc-vs-dshackle.llms.txt) - [eRPC vs web3-proxy](/compare/erpc-vs-web3-proxy.llms.txt) --- --- # eRPC vs dshackle > Source: https://docs.erpc.cloud/compare/erpc-vs-dshackle > eRPC vs dshackle (emeraldpay) feature by feature, with a source link in every cell, and where dshackle is the better fit. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # eRPC vs dshackle [dshackle](https://github.com/emeraldpay/dshackle) and eRPC both put one endpoint in front of many blockchain nodes. dshackle comes from wallet infrastructure: a gRPC API with streams, signed responses, and deep Bitcoin support. eRPC is an EVM and Solana JSON-RPC proxy built around failover, a finality-aware cache, and cost control. Every cell below links to the page or line that states it. Facts were checked on 2026-10-22. ## Feature table | | eRPC | dshackle | |---|---|---| | Language, license | Go, Apache-2.0 ([LICENSE](https://github.com/erpc/erpc/blob/32a8a1e450c6ab5a78477859c85221b6a9058c72/LICENSE#L1)) | Rust on `master`, Kotlin in v0.17.0; Apache-2.0 ([Cargo.toml](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/Cargo.toml#L1-L4), [LICENSE](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/LICENSE)) | | Latest release | 0.4.0, 2026-10-11 ([release](https://github.com/erpc/erpc/releases/tag/0.4.0)) | v0.17.0, 2026-04-01 ([release](https://github.com/emeraldpay/dshackle/releases/tag/v0.17.0)) | | Chains | EVM and Solana ([networks](/config/projects/networks.llms.txt)) | EVM and Bitcoin ([upstream config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/04-upstream-config.adoc#L13-L34)) | | Client APIs | JSON-RPC over HTTP and WebSocket ([websocket](/operation/websocket.llms.txt)) | JSON-RPC over HTTP and WebSocket, plus a gRPC API ([methods](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/07-methods.adoc#L1-L30)) | | Config | YAML or TypeScript ([quick start](/)) | YAML with `include` and `${ENV}` ([server config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/03-server-config.adoc#L1-L10)) | | Upstream selection | Score from errors, latency, 429s, block lag ([selection policies](/config/projects/selection-policies.llms.txt)) | Role tiers plus round-robin; lag and sync filters ([upstream config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/04-upstream-config.adoc#L154-L177)) | | Failover and retry | Yes, per method ([retry](/config/failsafe/retry.llms.txt)) | Primary, secondary, fallback with growing delay ([upstream config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/04-upstream-config.adoc#L167-L177)) | | Hedged requests | Yes ([hedge](/config/failsafe/hedge.llms.txt)) | Not documented ([source tree](https://github.com/emeraldpay/dshackle/tree/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src)) | | Circuit breaker | Yes ([circuit breaker](/config/failsafe/circuit-breaker.llms.txt)) | Pauses upstreams that return 429 or overload ([pause.rs](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src/upstream/pause.rs#L15-L59)) | | Cross-checking answers | Consensus across N upstreams with a threshold ([consensus](/config/failsafe/consensus.llms.txt)) | Per-method quorum: not lagging, non-empty, max nonce, broadcast ([ethereum.rs](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src/upstream/methods/ethereum.rs#L64-L90)) | | Signed responses | No | Yes, names the upstream that answered ([methods](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/07-methods.adoc#L94-L117)) | | Cache | Memory, Redis, PostgreSQL, DynamoDB; finality-aware ([drivers](/config/database/drivers.llms.txt), [cache](/config/database/evm-json-rpc-cache.llms.txt)) | Memory and Redis; blocks, txs, receipts by hash ([caching](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/10-caching.adoc#L1-L16)) | | Rate limits | Per client, project, network, upstream ([rate limiters](/config/rate-limiters.llms.txt)) | None for clients ([overload.rs](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src/upstream/overload.rs#L15-L35)) | | Client auth | Secret, JWT, SIWE, IP, database ([auth](/config/auth.llms.txt)) | TLS client certificates ([authentication](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/08-authentication.adoc#L68)) | | `eth_getLogs` splitting | Yes ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)) | Not documented; passed through ([ethereum.rs](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src/upstream/methods/ethereum.rs#L122)) | | JSON-RPC batch | Yes ([batch](/operation/batch.llms.txt)) | Yes ([reference](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/reference-configuration.adoc#L420-L424)) | | `eth_subscribe` | newHeads, logs, newPendingTransactions ([websocket](/operation/websocket.llms.txt)) | newHeads, logs, newPendingTransactions, syncing ([egress.rs](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/src/upstream/egress.rs#L42-L45)) | | Metrics, tracing | Prometheus, OpenTelemetry ([monitoring](/operation/monitoring.llms.txt), [tracing](/operation/tracing.llms.txt)) | Prometheus; JSON access logs, no OpenTelemetry ([monitoring](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/06-monitoring.adoc#L1-L14)) | | Multi-tenant | Projects, per-user budgets ([projects](/config/projects.llms.txt)) | Not documented ([reference](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/reference-configuration.adoc#L434-L454)) | | Archive routing | Block availability per upstream ([upstreams](/config/projects/upstreams.llms.txt)) | Labels such as `archive: true`, method on/off ([upstream config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/04-upstream-config.adoc#L264-L284)) | | Deployment | Binaries, Docker, Kubernetes manifests, `npx start-erpc` ([docker](/deployment/docker.llms.txt), [kubernetes](/deployment/kubernetes.llms.txt)) | Docker, release zip ([Dockerfile](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/Dockerfile)) | "Not documented" means the project's docs do not describe it and a search of its source found no code for it. ## Where dshackle is stronger - **gRPC API with streams.** Head, balance (ETH, ERC-20, BTC with xpub) and tx-status subscriptions ([methods](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/07-methods.adoc#L11-L30)). - **Signed responses.** A client can prove which upstream produced an answer ([methods](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/07-methods.adoc#L94-L117)). - **Bitcoin.** bitcoind, Esplora and ZeroMQ notifications ([reference](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/reference-configuration.adoc#L944-L992)). eRPC does not serve Bitcoin. - **Instance mesh.** dshackle instances link over mTLS gRPC across regions ([architecture](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/01-architecture-intro.adoc#L63-L72)). - **Fork-aware routing.** Upstreams on the losing fork still serve data below the fork point ([upstream config](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/docs/04-upstream-config.adoc#L119-L150)). ## Where eRPC is stronger - Hedging, circuit breaker and consensus as separate failsafe steps ([failsafe](/config/failsafe.llms.txt)). - Finality-aware cache on four storage drivers ([cache](/config/database/evm-json-rpc-cache.llms.txt)). - `eth_getLogs` range splitting ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)). - Client auth and rate limits for public or multi-team endpoints ([auth](/config/auth.llms.txt), [rate limiters](/config/rate-limiters.llms.txt)). - Solana support ([networks](/config/projects/networks.llms.txt)). ## Note on dshackle versions The latest dshackle release, v0.17.0, is Kotlin. Since April 2026 the `master` branch is a Rust rewrite, version `0.18.0-dev` ([Cargo.toml](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/Cargo.toml#L1-L4)). The dshackle README says `master` "should not be used in production" ([README](https://github.com/emeraldpay/dshackle/blob/896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78/README.adoc#L308)). dRPC keeps a separate Kotlin fork, [drpcorg/dshackle](https://github.com/drpcorg/dshackle), with more chains and JWT auth. This page compares `emeraldpay/dshackle`. --- ### eRPC vs dshackle — agent reference ### Sources and snapshot - eRPC: `erpc/erpc` at `32a8a1e450c6ab5a78477859c85221b6a9058c72`, docs at docs.erpc.cloud. - dshackle: `emeraldpay/dshackle` `master` at `896ab53b7c8806b5ee481a14aa1e1c04e7bc1a78` (2026-10-13), release `v0.17.0` at `f781e8edc4e35887f684209250412baf530417ae`. - Checked 2026-10-22. Absence claims ("Not documented") rest on the dshackle docs plus a source search of `master` `src/` and `v0.17.0` `src/main`. No maintainer statement confirms them. ### Moving from dshackle to eRPC | dshackle concept | eRPC equivalent | |---|---| | `cluster.upstreams[]` | `projects[].upstreams[]` ([upstreams](/config/projects/upstreams.llms.txt)) | | `blockchain` per upstream | `networks[].evm.chainId` ([networks](/config/projects/networks.llms.txt)) | | `role: primary/secondary/fallback` | selection policy ([selection policies](/config/projects/selection-policies.llms.txt)) | | `methods.enabled[].quorum` | `failsafe[].consensus` ([consensus](/config/failsafe/consensus.llms.txt)) | | `methods.enabled` / `methods.disabled` | `allowMethods` / `ignoreMethods` ([upstreams](/config/projects/upstreams.llms.txt)) | | Redis cache | `database.evmJsonRpcCache` with a Redis connector ([cache](/config/database/evm-json-rpc-cache.llms.txt)) | ### Keep dshackle when - Clients use its gRPC streams or signed responses. - You serve Bitcoin. ### Related pages - [Why eRPC?](/why.llms.txt) - [eRPC vs web3-proxy](/compare/erpc-vs-web3-proxy.llms.txt) - [eRPC vs dRPC NodeCore](/compare/erpc-vs-drpc-nodecore.llms.txt) --- --- # eRPC vs web3-proxy > Source: https://docs.erpc.cloud/compare/erpc-vs-web3-proxy > eRPC vs web3-proxy (llamanodes) feature by feature, with a source link in every cell, and where web3-proxy is the better fit. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # eRPC vs web3-proxy [web3-proxy](https://github.com/llamanodes/web3-proxy) is the Rust proxy that ran LlamaNodes' public RPC. It ships a full RPC-as-a-service layer: wallet login, keys, tiers and compute-unit billing. eRPC is an EVM and Solana JSON-RPC proxy built around failover, a finality-aware cache, and cost control. Every cell below links to the page or line that states it. Facts were checked on 2026-10-22. ## Feature table | | eRPC | web3-proxy | |---|---|---| | Language, license | Go, Apache-2.0 ([LICENSE](https://github.com/erpc/erpc/blob/32a8a1e450c6ab5a78477859c85221b6a9058c72/LICENSE#L1)) | Rust, GPL-3.0 ([LICENSE](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/LICENSE#L1-L2)) | | Latest release | 0.4.0, 2026-10-11 ([release](https://github.com/erpc/erpc/releases/tag/0.4.0)) | No GitHub releases; last tag v1.43.99, 2023-12-03 ([tags](https://github.com/llamanodes/web3-proxy/tags)) | | Last commit | 2026-10-22 ([commits](https://github.com/erpc/erpc/commits/main)) | 2023-12-05 ([commit](https://github.com/llamanodes/web3-proxy/commit/f4a71ee0b621c461828956436f6d55372228ec18)) | | Chains | EVM and Solana, many chains per process ([networks](/config/projects/networks.llms.txt)) | EVM, one `chain_id` per process ([example.toml](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/config/example.toml#L1-L2)) | | Config | YAML or TypeScript ([quick start](/)) | TOML ([example.toml](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/config/example.toml)) | | Upstream selection | Score from errors, latency, 429s, block lag ([selection policies](/config/projects/selection-policies.llms.txt)) | Synced head, latency tiers, peak-EWMA load ([one.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/one.rs#L270-L365)) | | Failover and retry | Yes, per method ([retry](/config/failsafe/retry.llms.txt)) | Next ranked upstream on error ([consensus.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/consensus.rs#L947-L1013)) | | Hedged requests | Yes ([hedge](/config/failsafe/hedge.llms.txt)) | No; "fastest" mode is `todo!()` ([many.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/many.rs#L583-L590)) | | Circuit breaker | Yes ([circuit breaker](/config/failsafe/circuit-breaker.llms.txt)) | Not found in source ([src](https://github.com/llamanodes/web3-proxy/tree/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src)) | | Cross-checking answers | Consensus across N upstreams ([consensus](/config/failsafe/consensus.llms.txt)) | Head-block agreement only; response quorum is `todo!()` ([many.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/many.rs#L588)) | | Cache | Memory, Redis, PostgreSQL, DynamoDB; finality-aware ([drivers](/config/database/drivers.llms.txt), [cache](/config/database/evm-json-rpc-cache.llms.txt)) | In-memory; keys include block hash ([app/mod.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/app/mod.rs#L411-L416), [block_number.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/block_number.rs#L353-L369)) | | Rate limits | Per client, project, network, upstream ([rate limiters](/config/rate-limiters.llms.txt)) | Per upstream soft/hard limits; per IP and per key tier ([config.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/config.rs#L398-L428), [authorization.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/frontend/authorization.rs#L680-L720)) | | Client auth | Secret, JWT, SIWE, IP, database ([auth](/config/auth.llms.txt)) | RPC keys, SIWE login, IP/origin/referer allowlists ([authentication.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/frontend/users/authentication.rs#L78-L130)) | | Billing | No; cost headers for an external meter ([directives](/operation/directives.llms.txt)) | Yes: compute units, balances, deposits, Stripe ([compute_units.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/compute_units.rs#L14-L80)) | | `eth_getLogs` splitting | Yes ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)) | No; ranges over 200,000 blocks rejected ([block_number.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/block_number.rs#L438-L452)) | | JSON-RPC batch | Yes ([batch](/operation/batch.llms.txt)) | Yes ([app/mod.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/app/mod.rs#L1011-L1017)) | | `eth_subscribe` | newHeads, logs, newPendingTransactions ([websocket](/operation/websocket.llms.txt)) | newHeads, newPendingTransactions ([ws.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/app/ws.rs#L41-L252)) | | Metrics, tracing | Prometheus, OpenTelemetry ([monitoring](/operation/monitoring.llms.txt), [tracing](/operation/tracing.llms.txt)) | Prometheus, InfluxDB stats, Sentry ([prometheus.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/prometheus.rs#L15-L44), [Cargo.toml](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/Cargo.toml#L76-L80)) | | Archive routing | Block availability per upstream ([upstreams](/config/projects/upstreams.llms.txt)) | Probes each upstream's history depth automatically ([one.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/one.rs#L368-L490)) | | Deployment | Binaries, Docker, Kubernetes manifests, `npx start-erpc` ([docker](/deployment/docker.llms.txt), [kubernetes](/deployment/kubernetes.llms.txt)) | Build with cargo or the Dockerfile ([Dockerfile](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/Dockerfile#L204-L216)) | "Not found in source" means a search of the web3-proxy source found no code for it. ## Where web3-proxy is stronger - **RPC-as-a-service built in.** Users, sub-users, tiers, compute-unit pricing, on-chain deposits and Stripe ([compute_units.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/compute_units.rs#L14-L80)). eRPC has no billing. - **Private transaction routing.** `eth_sendRawTransaction` goes to `private_rpcs` such as Flashbots ([app/mod.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/app/mod.rs#L1101-L1185)). - **ERC-4337 bundler routing** to a separate upstream pool ([app/mod.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/app/mod.rs#L1468-L1477)). - **Automatic archive-depth probing** per upstream, with no config ([one.rs](https://github.com/llamanodes/web3-proxy/blob/f4a71ee0b621c461828956436f6d55372228ec18/web3_proxy/src/rpcs/one.rs#L368-L450)). ## Where eRPC is stronger - Active releases; web3-proxy has had no commit since December 2023. - Hedging, circuit breaker and response consensus ([failsafe](/config/failsafe.llms.txt)). - Shared, finality-aware cache on Redis, PostgreSQL or DynamoDB ([cache](/config/database/evm-json-rpc-cache.llms.txt)). - `eth_getLogs` range splitting instead of a range cap ([getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)). - Many chains, EVM and Solana, in one process ([networks](/config/projects/networks.llms.txt)). --- ### eRPC vs web3-proxy — agent reference ### Sources and snapshot - eRPC: `erpc/erpc` at `32a8a1e450c6ab5a78477859c85221b6a9058c72`, docs at docs.erpc.cloud. - web3-proxy: `llamanodes/web3-proxy` `main` at `f4a71ee0b621c461828956436f6d55372228ec18` (2023-12-05). The repo is not archived. - Checked 2026-10-22. "Not found in source" and "No" for hedging, circuit breaker and OpenTelemetry rest on a source search and the `todo!()` branches cited. The code was not run. ### Moving from web3-proxy to eRPC | web3-proxy concept | eRPC equivalent | |---|---| | one process per `chain_id` | one process, many `networks[]` ([networks](/config/projects/networks.llms.txt)) | | `balanced_rpcs` | `projects[].upstreams[]` ([upstreams](/config/projects/upstreams.llms.txt)) | | `backup = true` upstream | fallback tier in a selection policy ([selection policies](/config/projects/selection-policies.llms.txt)) | | `soft_limit` / `hard_limit` | upstream rate-limit budget ([rate limiters](/config/rate-limiters.llms.txt)) | | RPC keys in the URL | `secret` or `database` auth ([auth](/config/auth.llms.txt)) | | in-memory response cache | `database.evmJsonRpcCache` ([cache](/config/database/evm-json-rpc-cache.llms.txt)) | ### Keep web3-proxy when - You need its built-in billing and user accounts and accept an unmaintained codebase. ### Related pages - [Why eRPC?](/why.llms.txt) - [eRPC vs dshackle](/compare/erpc-vs-dshackle.llms.txt) - [eRPC vs dRPC NodeCore](/compare/erpc-vs-drpc-nodecore.llms.txt) --- --- # Authentication > Source: https://docs.erpc.cloud/config/auth > Lock down every request with a token, JWT, wallet signature, or IP allowlist — and bind each identity to its own rate-limit budget. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Authentication Every request eRPC receives can be checked before it ever touches an upstream. Stack as many strategies as you need — static token, signed JWT, Ethereum wallet signature, or IP allowlist — and the first one that passes wins. Tie each identity directly to a rate-limit budget so power users and free-tier callers never share the same quota. ## Quick taste Illustrative, not a tuned production config — one secret token, one budget: **Config path:** `projects[].auth` **YAML — `erpc.yaml`:** ```yaml projects: - id: main auth: strategies: - type: secret # bind this identity to its own rate-limit budget rateLimitBudget: backend-tier secret: id: backend value: \${MY_SECRET_VALUE} ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", auth: { strategies: [{ type: "secret", // bind this identity to its own rate-limit budget rateLimitBudget: "backend-tier", secret: { id: "backend", value: process.env.MY_SECRET_VALUE, }, }], }, }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: lock down my project with a static token** ```text Add a secret-token auth strategy to my eRPC project so that only callers who supply the correct token in X-ERPC-Secret-Token (or ?secret=) can reach any upstream. Bind the token to an existing rate-limit budget so the backend tier gets its own quota. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/auth.llms.txt ``` **Prompt Example #2: set up JWT auth with per-user rate-limit tiers** ```text Configure eRPC to verify signed JWT bearer tokens (RS256) for my public-facing project. Different token tiers should get different rate-limit budgets — embed the budget ID in the token's rlm claim so a single strategy handles all users without separate config entries. Include key rotation via kid so I can add a new key without downtime. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/auth.llms.txt ``` **Prompt Example #3: migrate to database auth without a redeploy** ```text Replace my static secret strategy in my eRPC config with a database strategy backed by PostgreSQL so I can add and revoke API keys in the database without redeploying eRPC. Enable fail-open with an emergency rate-limit budget so the RPC endpoint stays reachable if the auth DB goes down. Reference: https://docs.erpc.cloud/config/auth.llms.txt ``` **Prompt Example #4: debug why callers are getting 401 or no-strategy-matched** ```text I'm seeing 401 responses and "no auth strategy matched" errors in my eRPC logs. Walk through the credential-extraction priority order and strategy matching logic to explain why my config in my eRPC config might be failing, and suggest fixes. Reference: https://docs.erpc.cloud/config/auth.llms.txt ``` **Prompt Example #5: add IP allowlist as a credential-less fallback** ```text My internal services call eRPC without any token. Add a network strategy that allowlists my private CIDR ranges and localhost so they get through, while still requiring a secret token for all other callers. Each internal IP should get its own User.Id in metrics (ipAsUser mode). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/auth.llms.txt ``` --- ### Authentication — full agent reference ### How it works At startup, three independent `AuthRegistry` instances can be created: one per project (consumer traffic at `projects[*].auth`), one for the admin API (`admin.auth`), and one for the healthcheck endpoint (`healthCheck.auth`). If a project has no auth config, its registry is nil and all requests are allowed. If `admin.auth` is nil, the admin endpoint hard-errors — configure `admin.auth` to protect it. For each HTTP request, eRPC extracts credential signals from query params and headers in a fixed priority order, then calls `AuthRegistry.Authenticate`. The registry iterates strategies in declaration order, skipping any whose type does not match the credential type and any filtered out by method rules. The first strategy that both matches and succeeds wins; its returned `User{Id, RateLimitBudget}` is attached to the request for downstream rate-limiting and observability. **HTTP credential extraction order (first match wins):** 1. `?token=` — deprecated alias for `?secret=` → `AuthTypeSecret` 2. `?secret=` → `AuthTypeSecret` 3. `X-ERPC-Secret-Token` header → `AuthTypeSecret` 4. `Authorization: Basic` (password part of base64 `user:pass`) → `AuthTypeSecret` 5. `Authorization: Bearer ` → `AuthTypeJwt` 6. `?jwt=` → `AuthTypeJwt` 7. `?signature=` + `?message=` → `AuthTypeSiwe` 8. `X-Siwe-Message` + `X-Siwe-Signature` headers → `AuthTypeSiwe` 9. No credential present → `AuthTypeNetwork` (fallback) gRPC metadata uses a parallel order without query-param equivalents: `x-erpc-secret-token`, then `authorization: Basic`, `authorization: Bearer`, then `x-siwe-message`+`x-siwe-signature`, then network fallback. gRPC has no `?token=` / `?secret=` / `?jwt=` equivalents — query params are not available in gRPC metadata. **Method filtering.** Every strategy accepts `ignoreMethods` and `allowMethods` wildcard lists. `ignoreMethods` is evaluated first; `allowMethods` overrides it. The canonical pattern for restricting a strategy to one method is `ignoreMethods: ["*"]` plus `allowMethods: ["eth_getLogs"]`. **Rate-limit budget cascade.** A `common.User{Id, RateLimitBudget}` is returned from each strategy. Budget priority: (1) per-user budget from the strategy result (database record field, JWT claim, or strategy-level `rateLimitBudget`); (2) strategy-level `AuthStrategyConfig.rateLimitBudget`; (3) no budget → all requests pass. In `acquireRateLimitPermit`, the user's budget (if non-empty) overrides the strategy-level budget. #### secret strategy The simplest backend-to-backend gate. The client sends the token as `?secret=VALUE` or the `X-ERPC-Secret-Token` header. `Authorization: Basic` is also accepted; only the password field is used — the username is silently discarded. Authenticate: exact equality match (`ap.Secret.Value != s.cfg.Value`). Returns `ErrAuthUnauthorized` on mismatch. No timing-safe compare — plain Go string inequality. For public internet deployments, prefer `database` or `jwt`. #### jwt strategy Verifies a signed JWT bearer token. Supports RSA, EC, and HMAC keys with optional `kid`-based rotation. Rate-limit budget tiers can be embedded in any JWT claim, enabling per-user rate limiting without separate strategy entries. Authenticate flow: `ParseUnverified` (kid extraction) → algorithm allowlist → key lookup by kid or type-compatibility → full `Parse` (signature + temporal claims) → issuer/audience/required claims → extract `sub` as `User.Id` → extract budget claim. **Critical footgun**: when `verificationKeys` is nil or empty, `s.keys` is empty, key lookup finds nothing, and every JWT is rejected with `"no suitable verification key found"`. An empty key map is deny-all, not allow-all. #### siwe strategy Verifies an EIP-4361 Sign-In-With-Ethereum message and signature. The recovered Ethereum address (lowercase) becomes `User.Id`. Requires an explicit `allowedDomains` list — an empty or absent list rejects all SIWE requests. Authenticate flow: parse EIP-4361 message → EIP-191 signature verification → domain allowlist → `ValidNow()` temporal check → return `User{Id: strings.ToLower(address)}`. Both raw and base64-encoded message forms are accepted. SIWE requires both `?signature=` AND `?message=` together — supplying only one causes silent fallthrough to network-strategy extraction. #### network strategy Authorizes requests by client IP address against an allowlist of exact IPs and CIDR ranges. This is the credential-less fallback — any request arriving without a recognizable token, JWT, or SIWE payload receives `AuthTypeNetwork` and is routed here if configured. Authenticate: reads `req.ClientIP()` (proxy-resolved by HTTP ingress). Checks localhost → exact IP list → CIDR list. First match wins. `ipAsUser=false` (default): all IPs in a CIDR range share one identity (`cidr.String()`). `ipAsUser=true`: each IP gets its own identity (`clientIP.String()`). #### database strategy Looks up an API key against a connector-backed store (PostgreSQL, DynamoDB, Redis, memory, or gRPC). Includes an in-process Ristretto positive cache (default 1h TTL), a hardcoded 5-second negative cache for invalid/disabled keys, singleflight deduplication for concurrent misses, configurable retry/backoff, and a connector-down circuit-breaker with optional fail-open. Authenticate fast paths (in evaluation order): 1. Positive Ristretto cache hit → return cached `User` immediately. 2. Negative Ristretto cache hit → return `ErrAuthUnauthorized` immediately. 3. Connector-down fast path (`tryFastFailOpen`) → return emergency user if fail-open enabled. 4. Singleflight deduplicated DB lookup → parse JSON → cache or negative-cache. **DB record format:** ```json { "userId": "string (required)", "enabled": true, "rateLimitBudget": "budget-id (optional)" } ``` `enabled: false` → `ErrAuthUnauthorized` + 5-second negative-cache entry. Missing `userId` → auth error. Missing `enabled` → treated as `true`. **Connector-down circuit-breaker** (added after 2026-05-13 production incident). The strategy tracks `connectorDown bool` and `connectorDownSince int64`. On transport/timeout/not-ready errors, `markConnectorDown()` sets the latch. While down, `tryFastFailOpen()` bypasses singleflight and the DB entirely — returning the emergency user (if `failOpen.enabled=true`) or rejecting immediately. One probe per second is elected via CAS to run the real DB path. A successful probe calls `markConnectorUp()`. ### Config schema **Auth attachment points** | YAML path | Type | Default | Notes | |---|---|---|---| | `projects[*].auth` | `*AuthConfig` | `nil` (allow-all) | Consumer auth per project. Nil = allow-all. [`common/config.go:L509`](https://github.com/erpc/erpc/blob/main/common/config.go#L509) | | `admin.auth` | `*AuthConfig` | `nil` | Admin endpoint auth. Nil = admin endpoint always returns error. [`common/config.go:L249`](https://github.com/erpc/erpc/blob/main/common/config.go#L249) | | `healthCheck.auth` | `*AuthConfig` | `nil` | Healthcheck auth. Nil = unguarded. Do NOT set `rateLimitBudget` on healthcheck strategies — healthcheck auth registry has no rate-limiter registry and will panic. [`erpc/http_server.go:L201-205`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L201-L205) | **`AuthConfig`** | Field | Type | Default | Notes | |---|---|---|---| | `auth.strategies` | `[]*AuthStrategyConfig` | `nil` (allow-all) | Ordered list. First strategy that matches credential type + method filter and authenticates successfully wins. [`common/config.go:L2444`](https://github.com/erpc/erpc/blob/main/common/config.go#L2444) | **`AuthStrategyConfig` — common fields** | Field | Type | Default | Notes | |---|---|---|---| | `strategies[*].type` | `string` | Inferred from sub-config block | `"secret"`, `"jwt"`, `"siwe"`, `"network"`, `"database"`. Block presence force-overwrites `type` for secret/database/jwt/siwe. For network, only `type: "network"` triggers auto-creation; the network block does not overwrite type. [`common/defaults.go:L2636-2666`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2636-L2666) | | `strategies[*].ignoreMethods` | `[]string` | `nil` | Wildcard patterns (supports `*`, `\|`, `&`, `!`). Applied before `allowMethods`. [`auth/authorizer.go:L86-98`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L86-L98) | | `strategies[*].allowMethods` | `[]string` | `nil` | Overrides `ignoreMethods`; any matching allow re-enables the strategy for that method. [`auth/authorizer.go:L100-113`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L100-L113) | | `strategies[*].rateLimitBudget` | `string` | `""` | Strategy-level budget ID. Overridden by per-user budget when non-empty. [`auth/authorizer.go:L119-127`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L119-L127) | **`secret` strategy — `SecretStrategyConfig`** YAML prefix: `auth.strategies[*].secret` | Field | Type | Default | Notes | |---|---|---|---| | `secret.id` | `string` | `""` | Returned as `User.Id` on success. May be empty. [`common/config.go:L2461`](https://github.com/erpc/erpc/blob/main/common/config.go#L2461) | | `secret.value` | `string` | required | Exact token to match. Plain string equality (not timing-safe). Redacted in JSON/YAML marshal. [`auth/strategy_secret.go:L24`](https://github.com/erpc/erpc/blob/main/auth/strategy_secret.go#L24) | | `secret.rateLimitBudget` | `string` | `""` | Attached to returned `User.RateLimitBudget` if non-empty. [`auth/strategy_secret.go:L29-31`](https://github.com/erpc/erpc/blob/main/auth/strategy_secret.go#L29-L31) | Supports: `AuthTypeSecret` only. `SetDefaults`: no-op. **`jwt` strategy — `JwtStrategyConfig`** YAML prefix: `auth.strategies[*].jwt` | Field | Type | Default | Notes | |---|---|---|---| | `jwt.verificationKeys` | `map[string]string` | `nil` | Map of `kid → keyData`. Value is PEM string, `"file:///path"`, or bare HMAC secret bytes. Empty map = ALL JWTs rejected (deny-all, not allow-all). [`auth/jwks.go`](https://github.com/erpc/erpc/blob/main/auth/jwks.go) | | `jwt.verificationJwksUrl` | `string` | `""` | Absolute HTTP(S) URL returning a standard JWKS document (`{"keys":[...]}`). Fetched at startup and refreshed in the background. Static `verificationKeys` override JWKS entries with the same `kid`. Non-HTTP(S) or host-less values fail startup validation. [`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go) | | `jwt.verificationJwksRefreshInterval` | `Duration` | `1h` when JWKS URL set | Background JWKS refresh interval. [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) | | `jwt.verificationJwksTlsInsecureSkipVerify` | `bool` | `false` | Skip TLS certificate verification when fetching the JWKS URL. **Do not enable in production** — intended for local development with self-signed certificates only. [`auth/jwks.go`](https://github.com/erpc/erpc/blob/main/auth/jwks.go) | | `jwt.allowedAlgorithms` | `[]string` | `nil` (any algorithm) | e.g. `["RS256","ES256"]`. Prevents algorithm-confusion attacks. [`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go) | | `jwt.allowedIssuers` | `[]string` | `nil` (any issuer) | Exact match against `iss` claim. Non-empty list + missing `iss` → error. [`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go) | | `jwt.allowedAudiences` | `[]string` | `nil` (any audience) | Exact match against `aud` claim as scalar string. Array-form `aud` JWT claim always fails the cast. [`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go) | | `jwt.requiredClaims` | `[]string` | `nil` | Claim names that must be present (any value). [`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go) | | `jwt.claimMatchers` | `map[string][]string` | `nil` | Map of `claimName → allowedValues`. Every key is an AND condition; within each key's value list any match passes (OR). Claim value may be a string, string array, or SCIM-style `[{"value":"..."}]`. Missing or empty claim → error. Omitting `claimMatchers` skips the check (backward-compatible). [`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go) | | `jwt.rateLimitBudgetClaimName` | `string` | `"rlm"` (set by SetDefaults) | JWT claim name from which `User.RateLimitBudget` is extracted. Missing claim → empty budget (no rate-limit). Non-string value → silent no-op. To suppress, use a claim name never present in tokens. [`common/defaults.go:L2749-2751`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2749-L2751) | Supports: `AuthTypeJwt` only. `SetDefaults`: sets `rateLimitBudgetClaimName = "rlm"` if empty. **`siwe` strategy — `SiweStrategyConfig`** YAML prefix: `auth.strategies[*].siwe` | Field | Type | Default | Notes | |---|---|---|---| | `siwe.allowedDomains` | `[]string` | `nil` (deny-all) | Exact match against EIP-4361 `domain` field. Empty list = all SIWE rejected. Must supply at least one domain. [`auth/strategy_siwe.go:L59-67`](https://github.com/erpc/erpc/blob/main/auth/strategy_siwe.go#L59-L67) | | `siwe.rateLimitBudget` | `string` | `""` | Attached to `User.RateLimitBudget` if non-empty. [`auth/strategy_siwe.go:L53-55`](https://github.com/erpc/erpc/blob/main/auth/strategy_siwe.go#L53-L55) | Supports: `AuthTypeSiwe` only. `SetDefaults`: no-op. **`network` strategy — `NetworkStrategyConfig`** YAML prefix: `auth.strategies[*].network` | Field | Type | Default | Notes | |---|---|---|---| | `network.allowedIPs` | `[]string` | `nil` | Exact IPv4/IPv6 addresses. Invalid IP → startup error. [`auth/strategy_network.go:L26-33`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L26-L33) | | `network.allowedCIDRs` | `[]string` | `nil` | CIDR ranges. Invalid CIDR → startup error. [`auth/strategy_network.go:L35-44`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L35-L44) | | `network.allowLocalhost` | `bool` | `false` | When true, any loopback address (`127.0.0.1`, `::1`) is allowed unconditionally before IP/CIDR checks. `User.Id = clientIP.String()`. [`auth/strategy_network.go:L63-71`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L63-L71) | | `network.trustedProxies` | `[]string` | `nil` | **NO-OP**. Never read by NetworkStrategy. Use `server.trustedIPForwarders` / `server.trustedIPHeaders` for X-Forwarded-For unwrapping. [`auth/strategy_network.go:L47-49`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L47-L49) | | `network.rateLimitBudget` | `string` | `""` | Attached to `User.RateLimitBudget` for all matching IPs. [`auth/strategy_network.go:L65-68`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L65-L68) | | `network.ipAsUser` | `bool` | `false` | For CIDR matches: false → `User.Id = cidr.String()` (all IPs in range share one identity); true → `User.Id = clientIP.String()` (per-IP identity). Localhost and exact-IP matches always use `clientIP.String()`. [`auth/strategy_network.go:L63-93`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L63-L93) | Supports: `AuthTypeNetwork` only (credential-less fallback). `SetDefaults`: no-op. **`database` strategy — `DatabaseStrategyConfig`** YAML prefix: `auth.strategies[*].database` | Field | Type | Default | Notes | |---|---|---|---| | `database.connector` | `*ConnectorConfig` | auto-created | Drivers: `postgresql`, `dynamodb`, `redis`, `memory`, `grpc`. Connector id defaults to `"auth-"`. [`common/defaults.go:L2676-2678`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2676-L2678) | | `database.maxWait` | `Duration` | `1s` | Per-request context timeout for the full DB lookup (singleflight + retries). [`common/defaults.go:L2718-2720`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2718-L2720) | | `database.cache.ttl` | `*time.Duration` | `1h` | Positive-cache TTL in Ristretto. [`common/defaults.go:L2691-2694`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2691-L2694) | | `database.cache.maxSize` | `*int64` | `10000` | Max positive-cache entries. [`common/defaults.go:L2696-2699`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2696-L2699) | | `database.cache.maxCost` | `*int64` | `1073741824` (1 GiB) | Ristretto MaxCost for positive cache. [`common/defaults.go:L2701-2704`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2701-L2704) | | `database.cache.numCounters` | `*int64` | `100000` | Ristretto NumCounters (also reused for negative cache). [`common/defaults.go:L2706-2709`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2706-L2709) | | `database.retry.maxAttempts` | `int` | `3` | Max DB lookup attempts. [`common/defaults.go:L2726-2728`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2726-L2728) | | `database.retry.baseBackoff` | `Duration` | `100ms` | Exponential backoff base; each attempt uses `baseBackoff << (attempt-1)`. [`common/defaults.go:L2729-2731`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2729-L2731) | | `database.failOpen.enabled` | `bool` | `false` | When true, DB errors grant an emergency user instead of rejecting. The connector-down circuit-breaker fast path also respects this flag. [`auth/strategy_database.go:L519-530`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L519-L530) | | `database.failOpen.userId` | `string` | `"emergency-failopen"` | `User.Id` for all fail-open authenticated requests. Flows into Prometheus labels and log fields. [`common/defaults.go:L2738-2740`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2738-L2740) | | `database.failOpen.rateLimitBudget` | `string` | `""` | `User.RateLimitBudget` applied to fail-open traffic. [`auth/strategy_database.go:L526-528`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L526-L528) | Negative cache: hardcoded 5-second TTL, 1 MiB MaxCost. Not configurable. Disabled/invalid keys stay rejected up to 5 seconds after change. **`database` strategy `Supports`**: accepts both `AuthTypeSecret` (token delivered via header/query) and `AuthTypeDatabase`. The `AuthTypeDatabase` enum value is never set by any current HTTP or gRPC payload extractor — it is reserved for future or programmatic use. [`auth/strategy_database.go:L118-120`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L118-L120) **database connector error classification** — determines whether `connectorDown` latch is set ([`auth/strategy_database.go:L487-L517`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L487-L517)): | Error | Label | Sets connectorDown? | |---|---|---| | `data.ErrConnectorNotReady` | `db_not_ready` | yes | | `context.DeadlineExceeded`, substring `"deadline exceeded"` or `"timeout"` | `db_timeout` | yes | | substrings: `"connection refused"`, `"connection reset"`, `"broken pipe"`, `"no route to host"`, `"EOF"`, `"use of closed network connection"` | `db_connection` | yes | | `ErrRecordNotFound` | *(treated separately; not error-classified)* | no — marks connector UP | | everything else (parse errors, Postgres `53300` "too many connections", syntax errors) | `db_query_error` | no | **`getWithRetries` abort conditions** ([`auth/strategy_database.go:L367-L417`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L367-L417)): - `ErrRecordNotFound` → abort immediately (DB is healthy; no retry needed). - `data.ErrConnectorNotReady` → abort immediately (connector's own reconnect loop handles recovery). - Context done → abort immediately. - Any other error → retry with `baseBackoff << (attempt-1)` up to `maxAttempts`. **Connector failsafe wrapping.** Auth-scope connectors support the same `failsafeForGets` and `failsafeForSets` wrapping as cache-scope connectors (`ConnectorConfig.failsafeForGets[*]` and `failsafeForSets[*]`). Each entry is a `FailsafeConfig` with fields `matchMethod` (default `"*"`), `matchFinality`, `retry`, `circuitBreaker`, `timeout`, `hedge`, and `consensus`. [`common/config.go:L349-350`](https://github.com/erpc/erpc/blob/main/common/config.go#L349-L350) **PostgreSQL auth-scope defaults** (`connector.postgresql.*`): | Field | Auth-scope default | Notes | |---|---|---| | `table` | `"erpc_auth"` | Differs from cache (`"erpc_json_rpc_cache"`) and shared-state (`"erpc_shared_state"`) scopes. [`common/defaults.go:L1028-1029`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1028-L1029) | | `minConns` | `1` | Differs from cache scope (4). [`common/defaults.go:L1034-1036`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1034-L1036) | | `maxConns` | `4` | Differs from cache scope (32). [`common/defaults.go:L1041-1043`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1041-L1043) | | `initTimeout` | `5s` | [`common/defaults.go:L1048-1050`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1048-L1050) | | `getTimeout` | `1s` | [`common/defaults.go:L1051-1053`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1051-L1053) | | `setTimeout` | `2s` | [`common/defaults.go:L1054-1056`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1054-L1056) | **Memory connector** (`connector.memory.*`): | Field | Auth-scope default | Notes | |---|---|---| | `maxItems` | `100000` | Ristretto item count limit. [`common/defaults.go:L936-938`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L936-L938) | | `maxTotalSize` | `"1GB"` | Max total size of values. [`common/defaults.go:L939-941`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L939-L941) | | `emitMetrics` | `nil` (disabled) | When `true`, a background goroutine emits Ristretto metrics to Prometheus every 30 seconds. Must be explicitly set to `true` to enable. [`data/memory.go:L71`](https://github.com/erpc/erpc/blob/main/data/memory.go#L71) | **DynamoDB auth-scope defaults** (`connector.dynamodb.*`): | Field | Auth-scope default | Notes | |---|---|---| | `table` | `"erpc_auth"` | Differs from cache scope. [`common/defaults.go:L1068-1069`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1068-L1069) | | `region` | `""` | AWS region. Required unless resolved from environment/instance profile. [`common/config.go:L430`](https://github.com/erpc/erpc/blob/main/common/config.go#L430) | | `endpoint` | `""` | Custom endpoint URL (for local DynamoDB or LocalStack). [`common/config.go:L431`](https://github.com/erpc/erpc/blob/main/common/config.go#L431) | | `auth` | `nil` | AWS credential config; see `AwsAuthConfig` table below. [`common/config.go:L432`](https://github.com/erpc/erpc/blob/main/common/config.go#L432) | | `partitionKeyName` | `"groupKey"` | [`common/defaults.go:L1074-1076`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1074-L1076) | | `rangeKeyName` | `"requestKey"` | [`common/defaults.go:L1077-1079`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1077-L1079) | | `reverseIndexName` | `"idx_requestKey_groupKey"` | GSI name. [`common/defaults.go:L1080-1082`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1080-L1082) | | `ttlAttributeName` | `"ttl"` | [`common/defaults.go:L1083-1085`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1083-L1085) | | `initTimeout` | `5s` | SDK init timeout. [`common/defaults.go:L1086-1088`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1086-L1088) | | `getTimeout` | `1s` | Per-get operation timeout. [`common/defaults.go:L1089-1091`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1089-L1091) | | `setTimeout` | `2s` | Per-set operation timeout. [`common/defaults.go:L1092-1094`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1092-L1094) | | `maxRetries` | `0` | Max DynamoDB SDK retries. Zero means use SDK default (typically 3). [`common/config.go:L440`](https://github.com/erpc/erpc/blob/main/common/config.go#L440) | | `statePollInterval` | `5s` | Interval for polling DynamoDB connection state. [`common/defaults.go:L1095-1097`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1095-L1097) | | `lockRetryInterval` | `0` | **Footgun**: zero means busy-spin retries; set to e.g. `100ms` in production. [`common/config.go:L442`](https://github.com/erpc/erpc/blob/main/common/config.go#L442) | **`AwsAuthConfig`** (used by `connector.dynamodb.auth`): | Field | Default | Notes | |---|---|---| | `mode` | `""` (SDK default chain) | Valid values: `"file"` (reads credentials file), `"env"` (reads `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`), `"secret"` (uses `accessKeyID`/`secretAccessKey` fields directly). Empty = AWS SDK default chain (env → shared credentials file → EC2 instance profile). [`common/config.go:L479-485`](https://github.com/erpc/erpc/blob/main/common/config.go#L479-L485) | | `credentialsFile` | `""` | Path to AWS credentials file (used when `mode="file"`). | | `profile` | `""` | AWS named profile. Only meaningful when `mode="file"` — passed to `credentials.NewSharedCredentials`. Ignored for `mode="env"`, `mode="secret"`, and the SDK default chain. [`data/dynamodb.go:L177-187`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L177-L187) | | `accessKeyID` | `""` | AWS access key ID (used when `mode="secret"`). | | `secretAccessKey` | `""` | AWS secret access key (used when `mode="secret"`). Redacted in JSON marshal. [`common/config.go:L487-495`](https://github.com/erpc/erpc/blob/main/common/config.go#L487-L495) | **Redis auth-scope defaults** (`connector.redis.*`): | Field | Auth-scope default | Notes | |---|---|---| | `uri` | `""` | Full Redis URI (e.g., `redis://user:pass@host:6379/0`). Mutually exclusive with `addr` — providing both causes a startup error. When set, `addr`/`username`/`password`/`db` are ignored entirely. [`common/defaults.go:L946-950`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L946-L950) | | `addr` | `""` | Redis `host:port`. Folded into `uri` and cleared by `SetDefaults`. Port defaults to `6379` when missing. After folding, `addr` is set to `""`. [`common/defaults.go:L978-1015`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L978-L1015) | | `username` | `""` | Redis username. Folded into `uri` and cleared (same as `addr`). `json:"-"` does NOT apply to username; only password is marshal-suppressed. | | `password` | `""` | Redis password. Folded into `uri` and cleared. Tagged `json:"-"` — never marshalled to JSON output. [`common/config.go:L386`](https://github.com/erpc/erpc/blob/main/common/config.go#L386) | | `db` | `0` | Redis database index. Folded into `uri` path and cleared. Always appended as `"/"` even for index 0. | | `connPoolSize` | `8` | Connection pool size. [`common/defaults.go:L955-957`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L955-L957) | | `initTimeout` | `5s` | [`common/defaults.go:L958-960`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L958-L960) | | `getTimeout` | `1s` | [`common/defaults.go:L961-963`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L961-L963) | | `setTimeout` | `3s` | [`common/defaults.go:L964-966`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L964-L966) | | `lockRetryInterval` | `500ms` | [`common/defaults.go:L967-969`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L967-L969) | | `tls` | `nil` | Optional TLS config with sub-fields `enabled` (bool), `certFile`, `keyFile`, `caFile`, `insecureSkipVerify`. When `tls.enabled=true` and `addr` is set, `SetDefaults` sets the URI scheme to `rediss://`. When `uri` is provided with `rediss://` scheme, `tls.*` fields are merged onto the baseline TLS config. [`data/redis.go:L149-179`](https://github.com/erpc/erpc/blob/main/data/redis.go#L149-L179) | **gRPC connector** (`connector.grpc.*`): | Field | Auth-scope default | Notes | |---|---|---| | `servers` | `nil` | Explicit server addresses. [`common/config.go:L356`](https://github.com/erpc/erpc/blob/main/common/config.go#L356) | | `bootstrap` | `""` | xDS bootstrap for server discovery. Appended to `servers`. [`data/grpc.go:L83-98`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L83-L98) | | `headers` | `nil` | Static headers on all outbound gRPC requests. | | `getTimeout` | `100ms` | Much tighter than other drivers. [`common/defaults.go:L927-929`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L927-L929) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Production database auth with fail-open and extended cache TTL.** The customer-facing edge fleet uses PostgreSQL-backed dynamic API keys. The cache TTL was raised from 5s to 1m after a 2026-05-13 incident where transient pgbouncer disruption caused a reconnect storm across all 32 replicas simultaneously — lower query rate means transient errors are far less likely to cascade. Trade-off: revoked/disabled keys take up to 1m to stop working: **Config path:** `projects[].auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml - type: database database: connector: id: auth-postgresql driver: postgresql postgresql: connectionUri: \${DATABASE_URL} # table defaults to "erpc_auth" at auth scope (differs from cache scope) cache: # Raised from 5s to 1m to cut the Postgres query rate ~12× and prevent # connector reconnect storms under transient pgbouncer disruptions. # Trade-off: revoked keys stay valid for up to 1 minute. ttl: 1m failOpen: # Keep traffic flowing under an emergency budget if the auth DB goes down; # the connector-down circuit-breaker limits real DB probes to ~1/second. enabled: true userId: emergency-failopen # Cap emergency traffic so a DB outage can't become a free-for-all rateLimitBudget: emergency-tier ``` **TypeScript — `erpc.ts`:** ```typescript { type: "database", database: { connector: { id: "auth-postgresql", driver: "postgresql", postgresql: { connectionUri: process.env.DATABASE_URL, // table defaults to "erpc_auth" at auth scope (differs from cache scope) }, }, cache: { // Raised from 5s to 1m to cut Postgres query rate ~12× and prevent // connector reconnect storms under transient pgbouncer disruptions. // Trade-off: revoked keys stay valid for up to 1 minute. ttl: "1m", }, failOpen: { // Keep traffic flowing under an emergency budget if the auth DB goes down; // connector-down circuit-breaker limits real DB probes to ~1/second. enabled: true, userId: "emergency-failopen", // Cap emergency traffic so a DB outage can't become a free-for-all rateLimitBudget: "emergency-tier", }, }, } ``` **2. Admin endpoint secret.** All production deployments share a single secret strategy on the admin scope; the token is injected from an environment variable at deploy time. Note: `admin.auth` being nil hard-errors the endpoint with no useful error code — always configure it even in internal-only deployments: **Config path:** `admin.auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml # admin.auth — nil = admin always returns 500, not 401 admin: auth: strategies: - type: secret secret: # admin endpoints only need identity; no rate-limit budget required value: \${ADMIN_SECRET_TOKEN} ``` **TypeScript — `erpc.ts`:** ```typescript // admin.auth — nil = admin always returns 500, not 401 admin: { auth: { strategies: [{ type: "secret", secret: { // admin endpoints only need identity; no rate-limit budget required value: process.env.ADMIN_SECRET_TOKEN, }, }], }, }, ``` **3. Multi-secret staging setup with per-identity budgets.** The staging environment uses multiple named secrets bound to the same rate-limit budget — useful for smoke-testing different client identities without a database. Each `id` surfaces separately in Prometheus labels so you can see per-client RPS in dashboards: **Config path:** `projects[].auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml - type: secret secret: id: client-a value: \${CLIENT_A_TOKEN} # each secret gets its own budget so one client can't starve others rateLimitBudget: edge-tier-60krpm-total-unlimited-per-ip - type: secret secret: id: client-b value: \${CLIENT_B_TOKEN} rateLimitBudget: edge-tier-60krpm-total-unlimited-per-ip ``` **TypeScript — `erpc.ts`:** ```typescript { type: "secret", secret: { id: "client-a", value: process.env.CLIENT_A_TOKEN, // each secret gets its own budget so one client can't starve others rateLimitBudget: "edge-tier-60krpm-total-unlimited-per-ip", }, }, { type: "secret", secret: { id: "client-b", value: process.env.CLIENT_B_TOKEN, rateLimitBudget: "edge-tier-60krpm-total-unlimited-per-ip", }, }, ``` **4. Network strategy as credential-less fallback for internal services.** The staging deployment allows all internal traffic via CIDR while still accepting named secrets for external test callers. The `network` strategy must come first — it matches any request with no credential, so placing it later would shadow secrets on credential-less paths: **Config path:** `projects[].auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml # Place network strategy FIRST — it is the credential-less fallback; # any request without a token, JWT, or SIWE payload lands here. - type: network network: allowedCIDRs: ["10.0.0.0/8", "172.16.0.0/12"] allowLocalhost: true # ipAsUser: true gives each IP its own User.Id in Prometheus labels ipAsUser: true rateLimitBudget: internal-tier # External callers still use named secrets - type: secret secret: id: external-service value: \${EXTERNAL_SECRET_TOKEN} rateLimitBudget: external-tier ``` **TypeScript — `erpc.ts`:** ```typescript // Place network strategy FIRST — it is the credential-less fallback; // any request without a token, JWT, or SIWE payload lands here. { type: "network", network: { allowedCIDRs: ["10.0.0.0/8", "172.16.0.0/12"], allowLocalhost: true, // ipAsUser: true gives each IP its own User.Id in Prometheus labels ipAsUser: true, rateLimitBudget: "internal-tier", }, }, { type: "secret", secret: { id: "external-service", value: process.env.EXTERNAL_SECRET_TOKEN, rateLimitBudget: "external-tier", }, }, ``` **5. JWT with per-user rate-limit tiers and key rotation.** Embed the budget ID in the token's `rlm` claim so a single strategy entry handles thousands of users. Rotate signing keys by adding a new `kid` entry — old tokens continue to verify against the old key until they naturally expire. Always set `allowedAlgorithms` to prevent algorithm-confusion attacks: **Config path:** `projects[].auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml - type: jwt jwt: verificationKeys: # Add a new kid here when rotating; keep the old entry until tokens expire rsa-2024: "file:///etc/erpc/public-2024.pem" rsa-2025: "file:///etc/erpc/public-2025.pem" # ALWAYS restrict algorithms — omitting this allows algorithm-confusion attacks allowedAlgorithms: ["RS256"] allowedIssuers: ["https://auth.myapp.com"] allowedAudiences: ["https://rpc.myapp.com"] # Extract User.RateLimitBudget from this JWT claim; missing claim = no budget rateLimitBudgetClaimName: rlm ``` **TypeScript — `erpc.ts`:** ```typescript { type: "jwt", jwt: { verificationKeys: { // Add a new kid here when rotating; keep the old entry until tokens expire "rsa-2024": "file:///etc/erpc/public-2024.pem", "rsa-2025": "file:///etc/erpc/public-2025.pem", }, // ALWAYS restrict algorithms — omitting allows algorithm-confusion attacks allowedAlgorithms: ["RS256"], allowedIssuers: ["https://auth.myapp.com"], allowedAudiences: ["https://rpc.myapp.com"], // Extract User.RateLimitBudget from this JWT claim; missing claim = no budget rateLimitBudgetClaimName: "rlm", }, } ``` ### Request/response behavior - A successful auth attaches `User{Id, RateLimitBudget}` to the request; `User.Id` flows into log context and Prometheus labels on every downstream metric. [[`auth/registry.go:L74-76`](https://github.com/erpc/erpc/blob/main/auth/registry.go#L74-L76)] - `ErrAuthUnauthorized` → HTTP 401. Carries `{strategy}` in `Details`; JWT parse denials also set `{reason}` (`token_expired` / `invalid_signature`) via `AuthUnauthorizedReason`, and `Message` is derived from that reason. [[`common/errors.go:L548-615`](https://github.com/erpc/erpc/blob/main/common/errors.go#L548-L615)] - `ErrAuthRateLimitRuleExceeded` → HTTP 429. Carries `{projectId, strategy, budget, rule, userId, clientIp}` in `Details`. The `rule` value is formatted as `"method:"`. [[`common/errors.go:L545-568`](https://github.com/erpc/erpc/blob/main/common/errors.go#L545-L568)] - If no strategy's `Supports` returns true (e.g., a JWT token arrives but only `network` is configured), the response is `"no auth strategy matched"` — not a per-strategy auth failure. [[`auth/registry.go:L46-96`](https://github.com/erpc/erpc/blob/main/auth/registry.go#L46-L96)] - For admin scope, when `adminCfg != nil` but `adminAuthRegistry == nil`, `AdminAuthenticate` returns a plain `fmt.Errorf` with no typed error code → HTTP 200 (not 401/500). When `adminCfg` is nil, the path returns `ErrAuthUnauthorized` → HTTP 401. [[`erpc/admin.go:L26-30`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L26-L30)] - `erpc_rate_limits_total` fires for auth-level budget exhaustion with `origin="auth"` and `auth=":"` (e.g. `"secret:0"`, `"database:1"`). [[`auth/authorizer.go:L137`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L137)] - `ErrAuthRateLimitRuleExceeded` is auth-scope only — it fires when the auth-strategy-level rate-limit budget is exceeded. It does NOT fire for upstream/network rate-limit budgets (those produce `ErrProjectRateLimitRuleExceeded` or `ErrNetworkRateLimitRuleExceeded`). Retryability: `U:no` (upstreams will not retry), `N:yes` (network propagates 429 to caller). [[`common/errors.go:L545-568`](https://github.com/erpc/erpc/blob/main/common/errors.go#L545-L568)] - **gRPC required metadata**: `x-erpc-project` (required; missing → `codes.InvalidArgument "missing metadata"`), `x-erpc-chain-id` (required), `x-erpc-architecture` (optional, defaults to `"evm"`). [[`erpc/grpc_server.go:L138-145`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L138-L145)] ### Best practices - **Use `database` for user-facing APIs** — dynamic key management without redeploys, per-user rate-limit budgets via the DB record's `rateLimitBudget` field, and the built-in cache means sub-millisecond auth on cache hits. - **Always set `allowedAlgorithms` on `jwt`** — leaving it nil accepts any algorithm, opening the door to algorithm-confusion attacks (e.g., RS256 public key forged as HS256 secret). - **Always list at least one `allowedDomains` on `siwe`** — an empty or absent list silently rejects every SIWE request with no config-level indication. - **Never set `rateLimitBudget` on a `healthCheck.auth` strategy** — the healthcheck auth registry is created with a nil rate-limiter registry; reaching the budget-acquisition path causes a nil pointer panic. - **Enable `failOpen` with a capped emergency budget on `database`** — a DB outage should not make your RPC endpoint unreachable; the circuit-breaker bounds probe load to ~1 query/second per replica. - **DynamoDB `lockRetryInterval` defaults to `0`** — zero means busy-spin retries during lock contention; set to `100ms` or higher in production to avoid rapid API calls and unexpected cost. - **Use `secret` only for private, server-side callers** — the plain string comparison is not timing-safe; for browser-reachable endpoints, prefer `jwt` or `database`. ### Edge cases & gotchas 1. **No strategies = allow-all.** `AuthRegistry.Authenticate` returns `nil, nil` when the strategy list is empty. All requests pass. Auth is opt-in. 2. **network strategy is the credential-less fallback.** Requests without any recognizable credential get `AuthTypeNetwork`. If no network strategy is configured and only a `secret` strategy exists, credential-less requests get "no auth strategy matched", not "invalid secret". 3. **secret and database both consume `AuthTypeSecret`.** If both are configured, declaration order determines which runs first. To use only database, omit the secret strategy. 4. **JWT `allowedAudiences` only supports scalar `aud`.** The implementation casts `claims["aud"]` to `string`. Tokens with `"aud": ["a","b"]` (array form) always fail the cast and are rejected even if a matching audience is in the array. 5. **SIWE `allowedDomains` nil/empty = deny-all.** Visual appearance of `siwe: {}` gives no indication it is a blanket deny. 6. **`network.trustedProxies` is an intentional no-op.** Configure `server.trustedIPForwarders` / `server.trustedIPHeaders` instead. 7. **Healthcheck auth cannot use `rateLimitBudget`.** The healthcheck auth registry is created with `rateLimitersRegistry = nil`. Setting a budget on a healthcheck strategy reaches a nil pointer dereference at `acquireRateLimitPermit`. 8. **secret uses non-constant-time comparison.** Plain `!=` is timing-side-channel vulnerable for public internet exposures. 9. **Database negative cache TTL is hardcoded at 5 seconds.** Not configurable. Re-enabled keys are rejected for up to 5 seconds. 10. **Connector-down probe is per-process.** One probe/second per replica, no cross-replica coordination. 11. **type inference conflict.** Setting multiple sub-config blocks (e.g. both `secret:` and `jwt:`) in one strategy entry causes the last-evaluated block to silently overwrite `type`. Evaluation order: `secret → database → jwt → siwe`. Never set multiple sub-config blocks in one strategy entry. 12. **`Authorization: Basic` username is silently discarded.** Only the password field is used as the secret value. `alice:mysecret` and `bob:mysecret` are treated identically. 13. **JWT requires keys.** Configure `verificationKeys` and/or `verificationJwksUrl`. With neither, startup validation fails. An empty resolved key map rejects every JWT (deny-all, not allow-all). 14. **SIWE requires both signature and message together.** Missing either one causes silent fallthrough to network-strategy payload extraction. 15. **`?token=` query param is deprecated.** Alias for `?secret=`. Continues to work but may be removed; use `?secret=` or `X-ERPC-Secret-Token` header in new implementations. 16. **Redis `addr`/`username`/`password`/`db` are cleared after `SetDefaults`.** After initialization only `uri` is set. Config exports show only the URI (with credentials URL-encoded in it). 17. **DynamoDB `lockRetryInterval` defaults to `0`.** Zero = busy-spin during lock contention. Set to a non-zero value (e.g. `100ms`) in production. 18. **database.cache, database.retry, and database.failOpen are always auto-created.** Caching is always on with 1h TTL unless `ttl` is explicitly changed. There is no config to disable caching by omitting the block. 19. **`type: "network"` auto-creates the `network {}` sub-struct; the converse is asymmetric.** Adding a `network:` block does NOT overwrite `type` — unlike `secret`/`database`/`jwt`/`siwe` which force-overwrite `type` when their sub-block is present. 20. **When `admin.auth` is nil the admin endpoint hard-errors with HTTP 500.** `AdminAuthenticate` returns a plain `fmt.Errorf` (no typed error code) → HTTP 200 wire, not 401. Configure `admin.auth` to protect it properly. 21. **`database` strategy also accepts `AuthTypeDatabase` in `Supports`.** The enum value `AuthTypeDatabase` exists but is never produced by any current HTTP or gRPC payload extractor. It is reserved for future or programmatic injection. In practice, database auth is triggered via `AuthTypeSecret` credentials (header/query token). [[`auth/strategy_database.go:L118-120`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L118-L120)] 22. **Singleflight scope is per API key.** The singleflight group inside `DatabaseStrategy` uses the raw API key string as the deduplication key. Concurrent requests with the same API key during a cache miss are coalesced into a single DB lookup. Requests with different API keys run in parallel. [[`auth/strategy_database.go:L173-178`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L173-L178)] 23. **`AuthConfig` is shared across all three scopes.** The same `AuthConfig` type is used for `projects[*].auth`, `admin.auth`, and `healthCheck.auth`. All five strategy types can be configured in any scope. The only scope-specific hazard is `healthCheck.auth` — the healthcheck auth registry is created with a nil `rateLimitersRegistry`, so setting `rateLimitBudget` on any healthcheck strategy causes a nil pointer panic. 24. **Redis `addr`/`username`/`password`/`db` are cleared after `SetDefaults`.** After initialization, only `uri` is set; all discrete fields are zeroed. Config exports show only the URI (with credentials URL-encoded in it). Because `password` has `json:"-"`, a JSON export shows the URI but not the password field. [[`common/defaults.go:L1012-1015`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1012-L1015)] 25. **Admin auth registry DOES support rate-limit budgets.** Unlike the healthcheck scope, the admin `AuthRegistry` is created with the same `rateLimitersRegistry` as projects. Rate-limit budgets on admin auth strategies are applied when configured. 26. **`verificationJwksUrl` must be absolute HTTP(S).** Non-empty values are parsed at startup; scheme must be `http` or `https` and a host is required. Scheme-less hosts, `file://`, and other schemes fail validation even when static `verificationKeys` are also set. [[`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go)] 27. **JWT `jwt.Parse` failures are classified into closed reasons.** Bad signatures → `invalid_signature`; expired → `token_expired`. If both bits are set, signature wins. Other `ValidationError` flags use `invalid_token` and keep jwt library text as the message. [[`auth/strategy_jwt.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go)] 28. **`erpc_auth_failed_total` increments when an `ErrAuthUnauthorized` is returned to the client** (`processErrorBody` / gRPC status mapping via `RecordAuthFailed`). Strategies stamp a closed `Details.reason` via `NewErrAuthUnauthorized`; intermediate strategy rejects on a request that later succeeds are not counted. When multiple strategies reject the same payload, the registry join keeps `strategy`/`reason` if every attempt agrees; if any attempt is `token_expired`, that wins (multi-JWT setups often pair matching-key expiry with other-key `invalid_signature`); other divergent attempts fall back to `n/a`/`unauthorized` while the joined message still lists each failure. `agent_name` is always `"unknown"`; `project`/`network` are `"n/a"` unless a resolved network is already on the request. [[`auth/auth_metrics.go`](https://github.com/erpc/erpc/blob/main/auth/auth_metrics.go), [`auth/registry.go`](https://github.com/erpc/erpc/blob/main/auth/registry.go)] ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_auth_failed_total` | counter | `project`, `network`, `strategy`, `reason`, `agent_name` | Client-facing `ErrAuthUnauthorized` counter via `RecordAuthFailed` ([`auth/auth_metrics.go`](https://github.com/erpc/erpc/blob/main/auth/auth_metrics.go)). Closed `reason` sets: **database** — `missing_secret`, `empty_secret`, `cached_unknown_api_key`, `db_not_ready`, `db_timeout`, `db_connection`, `db_query_error`, `invalid_api_key`, `disabled_key`, `db_record_parse_error`, `db_record_missing_user_id`; **jwt** — `parse_failed`, `unexpected_algorithm`, `no_verification_key`, `token_expired`, `invalid_signature`, `invalid_token`, `invalid_claims`, `claims_invalid`, `missing_sub`; **secret** — `invalid_secret`; **siwe** — `missing_payload`, `parse_failed`, `invalid_signature`, `domain_not_allowed`, `message_not_valid_now`; **network** — `missing_request`, `invalid_client_ip`, `ip_not_allowed`. Fallback reason `unauthorized`. `agent_name` always `unknown`. No `user` label. | | `erpc_rate_limits_total` | counter | `project`, `network`, `vendor`, `upstream`, `category`, `finality`, `user`, `agent_name`, `budget`, `scope`, `auth`, `origin` | When auth-level rate-limit budget is exhausted. `origin="auth"`, `auth=":"` (e.g. `"secret:0"`, `"database:1"`). | **Log messages (database strategy):** | Level | Message | Key fields | |---|---|---| | `warn` | `"database connector marked DOWN; subsequent requests will fast-path to fail-open until next probe succeeds"` | `connectorId` | | `warn` | `"database connector marked UP; resuming normal auth flow"` | `connectorId` | | `warn` | `"singleflight error; fail-open enabled, granting emergency user"` | `userId`, `err` | | `warn` | `"database authentication lookup failed; retrying"` | `driver`, `connectorId`, `attempt`, `backoff`, `err` | | `error` | `"database query failed during authentication"` | `apiKey`, `driver`, `connectorId`, `err` | | `error` | `"auth DB error; fail-open enabled, granting emergency user"` | `userId` | | `info` | `"initialized API key cache for database authentication strategy"` | `ttl`, `negTtl`, `maxSize`, `maxCost`, `numCounters` | | `debug` | `"API key found in cache"` / `"not found in cache"` | `apiKey` | | `debug` | `"API key found in negative cache"` | `apiKey` | | `debug` | `"cached API key data"` | `apiKey`, `ttl` | | `debug` | `"user authenticated successfully"` | `apiKey`, `userId`, `budget` | | `debug` | `"invalidated API key cache entry"` | `apiKey` | No dedicated auth trace spans — auth runs inline inside the HTTP handler goroutine within the OTel request span. ### Source code entry points - [`auth/registry.go:L46-L96`](https://github.com/erpc/erpc/blob/main/auth/registry.go#L46-L96) — `AuthRegistry.Authenticate`: first-win loop, error accumulation - [`auth/authorizer.go:L83-L157`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L83-L157) — `shouldApplyToMethod`, `acquireRateLimitPermit`, budget cascade - [`auth/http.go:L13-L88`](https://github.com/erpc/erpc/blob/main/auth/http.go#L13-L88) — `NewPayloadFromHttp`: credential extraction priority order - [`auth/strategy_database.go:L271-L357`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L271-L357) — connector-down circuit-breaker, probe election, fail-open - [`auth/strategy_jwt.go:L100-L116`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go#L100-L116) — JWT key selection (kid lookup + type-compatibility scan) - [`auth/strategy_siwe.go:L22-L67`](https://github.com/erpc/erpc/blob/main/auth/strategy_siwe.go#L22-L67) — SIWE signature verification + domain allowlist - [`auth/strategy_network.go:L47-L93`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L47-L93) — NetworkStrategy: localhost/IP/CIDR checks, `ipAsUser` mode - [`common/config.go:L2433-L2534`](https://github.com/erpc/erpc/blob/main/common/config.go#L2433-L2534) — all auth config type declarations - [`common/defaults.go:L2611-L2761`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2611-L2761) — SetDefaults for all auth types - [`auth/strategy_database_test.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_database_test.go) — circuit-breaker, probe election, fail-open, `classifyDbError` label tests ### Related pages - [Rate limiters](/config/rate-limiters.llms.txt) — define the budgets that auth strategies assign to each identity. - [Projects](/config/projects.llms.txt) — auth lives at `projects[*].auth`; project-level config context. - [Use cases: Multi-tenant RPC](/use-cases/multi-tenant-rpc.llms.txt) — end-to-end example combining auth + rate limiters. --- --- # Storage drivers > Source: https://docs.erpc.cloud/config/database/drivers > Five interchangeable cache back-ends — memory, Redis, PostgreSQL, DynamoDB, and a read-only gRPC BDS connector — all behind one uniform interface, with optional per-operation failsafe policies that keep transient storage hiccups invisible to your upstreams. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Storage drivers Pick the back-end that fits your deployment — in-process LRU for a single node, Redis for multi-instance scale, PostgreSQL or DynamoDB for managed persistence, or a read-only gRPC BDS layer for historical chain data. Swap drivers by changing one line. Wrap any connector with retry, circuit-breaker, hedge, or timeout policies so a slow cache never slows down your upstream calls. Connectors are architecture-neutral. The examples on this page use `database.evmJsonRpcCache.connectors[]`; the identical connector schema lives under `database.svmJsonRpcCache.connectors[]` for SVM networks, and both caches can reference the same physical backend — partition keys are prefixed with the network id (`evm:1`, `svm:mainnet-beta`), so the keyspaces are disjoint. See [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt). ## Quick taste Illustrative, not a tuned production config — add a Redis connector: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: my-redis # swap one line to change back-end: memory | redis | postgresql | dynamodb | grpc driver: redis redis: uri: redis://localhost:6379/0 connPoolSize: 8 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "my-redis", // swap one line to change back-end: memory | redis | postgresql | dynamodb | grpc driver: "redis", redis: { uri: "redis://localhost:6379/0", connPoolSize: 8 }, }], }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add a Redis cache for multi-instance deployments** ```text I'm running eRPC on multiple pods and need a shared Redis cache so all instances share cached responses. Add a Redis connector with a sensible connection pool, per-operation timeouts, a circuit-breaker on Gets so a Redis outage doesn't stall upstream fan-out, and a retry on Sets. Work with my existing eRPC config. Read the reference first: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` **Prompt Example #2: layer a read-only gRPC BDS connector for historical data** ```text I want to add a read-only gRPC BDS connector for historical EVM chain data in front of my existing Redis connector — so finalized block responses are served from the BDS layer and only cache misses go to live upstreams. Add failsafe policies (hedge + timeout + retry) on Gets so a slow gRPC call doesn't block requests. My Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` **Prompt Example #3: tune memory connector sizing for my workload** ```text My eRPC instance uses the in-process memory connector. I'm seeing high eviction rates in Grafana and want to resize maxItems and maxTotalSize correctly for 8 GB of RAM and a workload of ~2 million cached EVM responses. Also enable emitMetrics so I can track ristretto cost going forward. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` **Prompt Example #4: debug DynamoDB lock contention causing high request volume** ```text My eRPC DynamoDB connector is causing a spike of DynamoDB requests under load — I think the lockRetryInterval is zero and the retry loop is spinning. Audit my my eRPC config DynamoDB connector config, fix the lock retry interval, and explain the other DynamoDB footguns I should watch for (TTL lag, accessKeyID casing, etc.). Reference: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` **Prompt Example #5: migrate from memory to PostgreSQL without downtime** ```text I currently have a single in-process memory connector in my eRPC config and want to migrate to PostgreSQL for persistence. Show me the full connector config with correct timeout values (not from the URI), connection pool sizing, and a pg_cron cleanup setup. Explain what changes and what behavior to expect. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` **Prompt Example #6: use AWS IAM Auth with ElastiCache / RDS connectors** ```text I run eRPC on EKS with an IRSA role and want to use IAM Auth instead of static passwords for my Redis (ElastiCache) and PostgreSQL (RDS) cache connectors. Configure connectors to use iamAuth, derive region/endpoint/dbUser where possible, omit the auth block so the instance role is used, and tell me the exact IAM policy actions and the rds_iam SQL grant I need. Explain the token-rotation behavior and the 12-hour ElastiCache disconnect handling. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/database/drivers.llms.txt ``` --- ### Storage drivers — full agent reference ### How it works `NewConnector` reads `cfg.Driver`, instantiates the matching back-end, then optionally wraps it in `FailsafeConnector` when `failsafeForGets` or `failsafeForSets` is non-empty. The `Connector` interface exposes `Get`, `Set`, `Delete`, `List`, `Lock`, `WatchCounterInt64`, and `PublishCounterInt64`. All five drivers implement every method — except `List` on memory (intentionally unimplemented) and all write methods on gRPC (read-only). Two index constants control lookup paths: `ConnectorMainIndex` (`"idx_main"`) for direct key lookups and `ConnectorReverseIndex` (`"idx_reverse"`) for wildcard range-key resolution. `Set` always writes the main index. Memory writes a reverse-index companion for any reverse-indexable key (two or more colons, any architecture prefix, including `svm:`) only when `WithReverseIndex` is on the ctx. Redis writes that companion only for `evm:`-prefixed keys, and only when the same ctx value is set. **Key encoding.** The composite storage key is `:`. For EVM cache entries the partition key typically starts with `evm:` (e.g., `evm:1:0x12345678`). Reverse index entries for memory and Redis use the key format `rvi##` where `wildcardPartitionKey` is `{networkId}:{suffix}:*` (`evm:1:*`, or `evm:1:systx:*` when `cacheKeySuffix` is set), supplied by the cache layer rather than inferred from the concrete partition key. PostgreSQL and DynamoDB store a dedicated reverse-index row or GSI entry instead. **Distributed counter payload.** `WatchCounterInt64` and `PublishCounterInt64` exchange a JSON-serialized `CounterInt64State` struct: `{"v": 42, "t": 1718000000000, "b": "pod-name"}` where `v` is the counter value, `t` is unix milliseconds (`t ≤ 0` means uninitialized), and `b` is the best-effort reporter identity (hostname/pod). — [data/connector.go:L34-L38](https://github.com/erpc/erpc/blob/main/data/connector.go#L34-L38) **Memory connector (ristretto).** The memory connector uses [dgraph-io/ristretto v2](https://github.com/dgraph-io/ristretto) as an in-process LRU with cost-based eviction. Ristretto is initialized with `NumCounters = 3 × maxItems`, `MaxCost = maxTotalSizeBytes`, and `BufferItems = 64`. Each entry costs `len(value) + 256` bytes against `maxTotalSize`. TTL is enforced by ristretto internally — no background cleanup goroutine. Reverse index entries are stored without TTL; after the main entry expires the stale pointer resolves to a miss. `List` is not implemented; ristretto has no iteration API. `Lock` uses a `sync.Map` of `*sync.Mutex` with `TryLock` plus a backoff loop (starts at 2ms, increments by 1ms per attempt, caps at 20ms). `WatchCounterInt64` and `PublishCounterInt64` are no-ops. **Redis connector.** Redis is the recommended connector for multi-instance deployments. It supports `List` (cursor-based `SCAN` — main index scans all keys with `*`; reverse index scans with `rvi#*` prefix, values fetched in pipeline), distributed locking via [go-redsync](https://github.com/go-redsync/redsync), and pub/sub through a self-healing `RedisPubSubManager` (channel name: `counter:`). Reverse index entries inherit the same TTL as the main entry. On reverse-index Get, the connector verifies the resolved key's TTL: `-2s` means the key does not exist → `ErrRecordNotFound`; `-1s` means persistent (accepted); positive value means it has an active TTL (accepted). Connection setup is non-blocking: `NewRedisConnector` enqueues a bootstrap task and returns immediately. Reconnection fires only on a narrow allowlist of critical failure strings (`"connection refused"`, `"broken pipe"`, `"invalid connection"`, `"connection reset by peer"`, `"no such host"`, `"network is unreachable"`, `"connection closed"`) to avoid spurious reconnects. When `rediss://` URI and `tls.enabled: true` are both configured, YAML cert/CA overrides merge onto the URI-derived TLS baseline and disable `InsecureSkipVerify`. A `rediss://`-only URI without a YAML `tls:` block produces `InsecureSkipVerify=true`. **PostgreSQL connector.** PostgreSQL stores cache entries with columns `(partition_key, range_key, value BYTEA, expires_at TIMESTAMPTZ)`. Schema migration (including a `TEXT -> BYTEA` column migration), indexes, and an optional `pg_cron` cleanup job run once per process lifetime — reconnects do not re-run them. Connection pool settings are hardcoded at `MaxConnLifetime = 5h` and `MaxConnIdleTime = 30m`. The old pool is closed only after the lock is released during reconnect, preventing hot-path serialization. Wildcard Get escapes `\`, `%`, and `_`, then translates `*` to `%`, and matches with `LIKE ... ESCAPE E'\\'`. For `ConnectorReverseIndex` the query is `WHERE range_key = $1 AND partition_key LIKE $2`; for main index: `WHERE partition_key = $1 AND range_key LIKE $2`, returning the first row ordered by `partition_key DESC`. The escape keeps a `cacheKeySuffix` such as `foo_bar` from matching `foo-bar` (`_` is a single-character wildcard in LIKE). Distributed locking uses `pg_try_advisory_xact_lock(hash64(key))` (FNV-64a hashes the key to an int64 lock ID), which is non-blocking: if the lock is held the call returns immediately with an error. TTL enforcement is exact via server-side `expires_at` filtering; pg_cron or a local ticker deletes expired rows every 5 minutes. `WatchCounterInt64` uses PostgreSQL `LISTEN/NOTIFY` (pub/sub), falling back to 30-second polling if `LISTEN` is unavailable. Channel names are sanitized to valid PostgreSQL identifier characters (max 63 bytes). **DynamoDB connector.** DynamoDB uses separate read (2048 max idle connections) and write (256 max idle connections) HTTP/2 clients. The table is created with `PAY_PER_REQUEST` billing if absent. TTL is stored as a numeric unix epoch attribute; AWS native TTL expiry is eventually consistent and can lag up to ~48 hours. The connector guards with a client-side epoch comparison on every `Get`, returning `ErrRecordExpired` for items past TTL. For reverse-index Query, up to 10 items are fetched with a server-side `FilterExpression` and the first non-expired item is chosen client-side. Both `B` (binary) and `S` (string) value attribute types are read for backward compatibility — legacy string values are returned as `[]byte`. `WatchCounterInt64` uses periodic polling (5s default) — DynamoDB has no native pub/sub. `PublishCounterInt64` is a no-op; callers rely on polling to pick up state changes. **gRPC connector (read-only).** The gRPC connector is a read-through layer backed by BDS (Blockchain Data Standards) gRPC servers that hold historical EVM chain data. It supports no writes, and eRPC never selects it for writes: its policies match only for reads, whatever `appliesTo` says. Configure it alongside a write-capable connector in a multi-connector cache policy. Goldsky hosts one for 22 chains: see [Goldsky cache (gRPC)](/config/database/goldsky-cache.llms.txt). Server discovery supports both a static `servers` list and a `bootstrap` HTTP URL. Only a specific allowlist of methods is forwarded to BDS: `eth_getBlockByNumber`, `eth_getBlockByHash`, `eth_getLogs`, `eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`, `eth_chainId`, and `eth_blockNumber`; unsupported methods return a fast miss (`(nil, nil)`) without an RPC call. Fast-miss rejection: if the request block number is below `earliestByNetwork[networkId]` (and that value is > 0), `ErrRecordNotFound` is returned immediately without an RPC. A background goroutine polls chain head every 60 seconds, implementing the `CacheHeadReporter` interface used by the real-time cache freshness gate. `eth_blockNumber` has no native BDS method; the connector intercepts it, calls `eth_getBlockByNumber("latest", false)` internally, and returns only the `number` field as a canonical hex string with leading zeros normalized via uint64 round-trip (zero block → `"0x0"`). On failure it returns `ErrRecordNotFound` so the request falls through to live upstreams. **FailsafeConnector.** Any connector can be wrapped by setting `failsafeForGets` and/or `failsafeForSets`. Each entry specifies a `matchMethod` pattern and optional `matchFinality` list, plus one or more of retry, circuit-breaker, hedge, and timeout policies. Executor selection (`pickCacheExecutor`) reads the method and finality from `ctx.Value(common.RequestContextKey)`; if no request is attached (background prefetch, tests), `method = ""` and `finality = 0`. The most-specific match wins: (method + finality) > (method only) > (finality only) > wildcard. A no-op executor is always appended so unmatched operations proceed unconditionally. `List`, `Lock`, `WatchCounterInt64`, and `PublishCounterInt64` bypass all failsafe policies. Retry fires only on transport errors — cache misses, expired records, and context cancellation are never retried. Transport errors recognized by `isTransportError` include net.Error timeouts, io.EOF/ErrUnexpectedEOF, syscall connection errors, gRPC status codes `Unavailable`/`DeadlineExceeded`/`Aborted`, Redis cluster transients (`CLUSTERDOWN`, `MASTERDOWN`, `TRYAGAIN`, `LOADING`), HTTP/2 GOAWAY, and `"use of closed network connection"`. Timeout and hedge accept both static durations and quantile-driven (`AdaptiveDuration`) values: a quantile resolves against the executor's own latency — a 1-minute sliding window (10 sub-buckets, rotated every ~6s) tracked per (connector × direction × method-pattern × finality), fed only by completed operations. Cold start (no samples yet) falls back to `base + min`; a timeout spec with unset `min` additionally gets the `min = base/2` (or `500ms` when `base == 0`) auto-floor at executor construction. **AWS IAM authentication (Redis & PostgreSQL).** Both the Redis (ElastiCache) and PostgreSQL (RDS) connectors can authenticate with short-lived AWS IAM tokens instead of static passwords. A shared `createAWSSession` helper resolves credentials from `iamAuth.auth` (same modes as `dynamodb.auth`) or, when omitted, the AWS SDK default chain (instance role → IRSA → env → shared file). For **ElastiCache**, eRPC presigns a SigV4 token (via `aws/signer/v4`, scheme stripped) and feeds it through go-redis's `CredentialsProviderContext`, which fires on every new physical connection; `ConnMaxLifetime` is pinned to 11h (±30m jitter) so each connection refreshes its token well before AWS's 12-hour forced disconnect — no background goroutines. For **RDS**, eRPC calls `rdsutils.BuildAuthToken` inside pgxpool's `BeforeConnect` hook, minting a fresh token per new pool connection; tokens are valid 15 minutes but only checked at connect time, and RDS has no 12-hour cap so the 5h `MaxConnLifetime` is unchanged. IAM auth is also available for `rateLimiters.store.redis`: set `iamAuth.enabled: true` on the `store.redis` block and eRPC builds a `radix/v3` pool whose `PoolConnFunc` mints a fresh SigV4 token on every new physical connection; `PoolMaxLifetime` is pinned to 11h so connections rotate before AWS's 12-hour forced disconnect (radix lacks a jitter knob — connections spread naturally across the pool's dial history). ### Config schema #### Top-level `ConnectorConfig` — [`common/config.go:L341-352`](https://github.com/erpc/erpc/blob/main/common/config.go#L341-L352) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `id` | string | `"-"` e.g. `"cache-memory"` — [`common/defaults.go:L847-848`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L847-L848) | Unique identifier; appears as the `connector` label on all metrics. | | `driver` | string | Inferred from whichever sub-config is present; explicit `driver` wins when both are set — [`common/defaults.go:L876-930`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L876-L930) | One of: `memory`, `redis`, `postgresql`, `dynamodb`, `grpc`. Unknown value → `ErrInvalidConnectorDriver` at startup. | | `failsafeForGets` | `[]*FailsafeConfig` | nil | Policies applied to `Get`. Evaluated by `pickCacheExecutor` in declaration order. | | `failsafeForSets` | `[]*FailsafeConfig` | nil | Policies applied to `Set` and `Delete`. | Each `FailsafeConfig` entry under `failsafeForGets` / `failsafeForSets`: | Field | Type | Default | Notes | |---|---|---|---| | `matchMethod` | string | `"*"` — [`common/defaults.go:L855-857`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L855-L857) | Glob pattern matched against the request method. `"*"` = all methods. | | `matchFinality` | `[]DataFinalityState` | nil (any) | Filter by finality; nil matches any finality. | | `retry.maxAttempts` | int | — | Retries only on `isTransportError`. | | `retry.delay` | Duration | — | Base delay between attempts. | | `retry.backoffMaxDelay` | Duration | — | Max delay with exponential backoff. | | `retry.backoffFactor` | float64 | — | Backoff multiplier per attempt. | | `circuitBreaker.*` | — | — | Standard breaker fields — see [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt). The executor’s own timeout expiry counts as a breaker failure (the timeout policy is the sole definition of "too slow"), so sustained timeouts open the breaker and cache reads fail fast until a half-open probe completes in time — [`data/cache_executor.go:L279-309`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L279-L309). `ErrRecordNotFound` and `ErrRecordExpired` count as `OutcomeIgnore`, not failures; ignored outcomes still release half-open trial permits. | | `timeout.duration` | `Duration \| AdaptiveDuration` | — | Per-operation timeout via `context.WithTimeoutCause`. Quantile mode resolves against the connector's own latency window; unset `min` gets the `base/2` (or `500ms`) auto-floor — [`data/cache_executor.go:L75-85`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L75-L85) | | `hedge.delay` | `Duration \| AdaptiveDuration` | — | Static delay, or quantile-driven: resolves against the connector's own 1-minute latency window; cold start (no samples) falls back to `base + min` — [`data/cache_executor.go:L204-207`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L204-L207) | | `hedge.maxCount` | int | — | Max additional hedged copies. | | `consensus` | — | nil | **Rejected at construction** with `"consensus is not supported for connector-level failsafe"` — [`data/cache_executor.go:L59-63`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L59-L63) | #### Memory connector — [`common/config.go:L361-365`](https://github.com/erpc/erpc/blob/main/common/config.go#L361-L365), defaults [`common/defaults.go:L935-943`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L935-L943) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `memory.maxItems` | int | `100000` | Sets `NumCounters = 3 × maxItems` (ristretto frequency sketch). Must be > 0 or init fails. | | `memory.maxTotalSize` | string | `"1GB"` | Parsed by `go-humanize`; becomes ristretto `MaxCost` in bytes. Must be > 0. | | `memory.emitMetrics` | *bool | nil (disabled) | When `true`, background goroutine emits ristretto metrics every 30s — [`data/memory.go:L212-294`](https://github.com/erpc/erpc/blob/main/data/memory.go#L212-L294) | #### Redis connector — [`common/config.go:L383-395`](https://github.com/erpc/erpc/blob/main/common/config.go#L383-L395), defaults [`common/defaults.go:L946-1018`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L946-L1018) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `redis.uri` | string | — | Redis URI (`redis://` or `rediss://`). Mutually exclusive with `addr`. | | `redis.addr` | string | — | `host:port`; converted to URI at defaults time then cleared. | | `redis.username` | string | — | Folded into URI; cleared afterward. | | `redis.password` | string | — | Redacted in logs/JSON. Folded into URI; cleared afterward. | | `redis.db` | int | `0` | Database index appended as `/` in URI. | | `redis.tls.enabled` | bool | `false` | Uses `rediss://` scheme; merges with URI-inferred TLS if both present. | | `redis.tls.certFile` | string | — | Client certificate for mTLS. | | `redis.tls.keyFile` | string | — | Client private key for mTLS. | | `redis.tls.caFile` | string | — | Custom CA bundle for server cert verification. | | `redis.tls.insecureSkipVerify` | bool | `false` | Skip server certificate verification. | | `redis.connPoolSize` | int | `8` | go-redis connection pool size. | | `redis.initTimeout` | Duration | `5s` | Ping timeout per connection attempt. Falls back to `DialTimeout` from URI when zero. | | `redis.getTimeout` | Duration | `1s` | Per-Get deadline. Falls back to `ReadTimeout` from URI when zero. | | `redis.setTimeout` | Duration | `3s` | Per-Set/Delete deadline. Falls back to `WriteTimeout` from URI when zero. | | `redis.lockRetryInterval` | Duration | `500ms` | Sleep between redsync mutex acquisition retries. | | `redis.iamAuth.enabled` | bool | `false` | Enables AWS ElastiCache IAM auth. SetDefaults auto-enables TLS (promotes `addr` to `rediss://`); the connector sets `ConnMaxLifetime=11h` (±30m jitter) so connections rotate before AWS's 12h forced disconnect. Mutually exclusive with a static password — rejected at startup. — [`data/redis_iam_auth.go:L22-24`](https://github.com/erpc/erpc/blob/main/data/redis_iam_auth.go#L22-L24), wiring [`data/redis.go:L187-201`](https://github.com/erpc/erpc/blob/main/data/redis.go#L187-L201) | | `redis.iamAuth.cacheName` | string | — | ElastiCache replication-group ID. Required when enabled. Lowercased automatically (AWS lowercases cache names at creation). | | `redis.iamAuth.userID` | string | — | ElastiCache user. Required when enabled. The user **name and user ID must be identical** — supply that single value. | | `redis.iamAuth.region` | string | derived | AWS region; derived from `AWS_REGION` / instance metadata when omitted. | | `redis.iamAuth.auth.*` | `*AwsAuthConfig` | nil (default chain) | Optional AWS credential source for signing the token (same fields/casing as `dynamodb.auth`). Omit to use the instance-role / IRSA default chain (recommended). — [`common/config.go:L518-529`](https://github.com/erpc/erpc/blob/main/common/config.go#L518-L529) | ElastiCache Serverless is **not** supported (it lacks `PSUBSCRIBE`, required by eRPC's shared-state connector). Requires Valkey ≥ 7.2 or Redis OSS ≥ 7.0 with IAM auth and in-transit TLS enabled on the cache. #### PostgreSQL connector — [`common/config.go:L445-453`](https://github.com/erpc/erpc/blob/main/common/config.go#L445-L453), defaults [`common/defaults.go:L1021-1058`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1021-L1058) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `postgresql.connectionUri` | string | — | pgx v5 connection string (required). Redacted in logs. Set the query mode with `default_query_exec_mode` (`cache_statement` default, `cache_describe`, `describe_exec`, `exec`, `simple_protocol`). Behind PgBouncer in transaction mode, set PgBouncer `max_prepared_statements` above 0 (PgBouncer 1.21+); with it at 0, every mode except `simple_protocol` can fail with `prepared statement ... already exists`. Counter watches use `LISTEN`, which PgBouncer transaction mode does not support. The pgx v4 keys `statement_cache_mode=prepare\|describe` and `prefer_simple_protocol=true` still work: eRPC maps them to `cache_statement`, `cache_describe` and `simple_protocol`, removes them before connecting, and logs one deprecation warning. An explicit `default_query_exec_mode` wins over them. `statement_cache_capacity=0` (or `description_cache_capacity=0` with `cache_describe`) selects `describe_exec`, the v4 "no cache" behavior. — [`data/postgresql.go:L293-356`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L293-L356) | | `postgresql.table` | string | `"erpc_json_rpc_cache"` (cache), `"erpc_shared_state"` (shared-state), `"erpc_auth"` (auth) | Table created on first connect. | | `postgresql.minConns` | int32 | `4` (non-auth), `1` (auth) | pgxpool `MinConns`. | | `postgresql.maxConns` | int32 | `32` (non-auth), `4` (auth) | pgxpool `MaxConns`. Pool lifecycle: `MaxConnLifetime=5h`, `MaxConnIdleTime=30m`; pgx v5 also pings a connection on acquire after it is idle for 1s. | | `postgresql.initTimeout` | Duration | `5s` | Context deadline for pool creation. **NOT read from URI** — always explicit. Connect fails fast: `minConns` connections (at least one, at most `maxConns`) must open within this deadline, else the attempt fails (bad password, unreachable host, unknown database) and the initializer retries in the background. — [`data/postgresql.go:L358-402`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L358-L402) | | `postgresql.getTimeout` | Duration | `1s` | Per-Get/List query deadline. Never falls back to URI values. | | `postgresql.setTimeout` | Duration | `2s` | Per-Set/Delete query deadline. Never falls back to URI values. | | `postgresql.iamAuth.enabled` | bool | `false` | Enables AWS RDS IAM auth. Mints a fresh SigV4 token per new pool connection via pgx `BeforeConnect`; SetDefaults appends `sslmode=require` automatically. `connectionUri` must carry no password. RDS has no 12h cap, so `MaxConnLifetime` (5h) is unchanged. — [`data/postgresql_iam_auth.go:L21-38`](https://github.com/erpc/erpc/blob/main/data/postgresql_iam_auth.go#L21-L38), wiring [`data/postgresql.go:L205-219`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L205-L219) | | `postgresql.iamAuth.region` | string | derived | AWS region; derived from `AWS_REGION` / instance metadata when omitted. | | `postgresql.iamAuth.endpoint` | string | derived from `connectionUri` | `host:port` used to sign the token. Must include a port. — [`common/defaults.go:L1071-1090`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1071-L1090) | | `postgresql.iamAuth.dbUser` | string | derived from `connectionUri` | DB user the token authenticates as (must be granted `rds_iam`). When both are set it must match the `connectionUri` user, else startup fails with a mismatch error. | | `postgresql.iamAuth.auth.*` | `*AwsAuthConfig` | nil (default chain) | Optional AWS credential source for signing. Omit to use the default chain. — [`common/config.go:L534-545`](https://github.com/erpc/erpc/blob/main/common/config.go#L534-L545) | #### DynamoDB connector — [`common/config.go:L428-443`](https://github.com/erpc/erpc/blob/main/common/config.go#L428-L443), defaults [`common/defaults.go:L1061-1099`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1061-L1099) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `dynamodb.table` | string | `"erpc_json_rpc_cache"` / `"erpc_shared_state"` / `"erpc_auth"` | Created with `PAY_PER_REQUEST` if absent. | | `dynamodb.region` | string | — | AWS region (required; fatal if empty). | | `dynamodb.endpoint` | string | — | Custom endpoint (e.g., DynamoDB Local). | | `dynamodb.auth.mode` | string | — | `"file"` / `"env"` / `"secret"`. Nil auth uses default credential chain. | | `dynamodb.auth.credentialsFile` | string | — | Path to AWS credentials file (mode=`file`). | | `dynamodb.auth.profile` | string | — | AWS profile name. | | `dynamodb.auth.accessKeyID` | string | — | **Case-sensitive**: struct tag is `yaml:"accessKeyID"` (capital `I` and `D`). Using `accessKeyId` (lowercase `d`) silently skips the field. — [`common/config.go:L483`](https://github.com/erpc/erpc/blob/main/common/config.go#L483) | | `dynamodb.auth.secretAccessKey` | string | — | Static secret key (mode=`secret`). | | `dynamodb.partitionKeyName` | string | `"groupKey"` | DynamoDB partition key attribute name. | | `dynamodb.rangeKeyName` | string | `"requestKey"` | DynamoDB sort key attribute name. | | `dynamodb.reverseIndexName` | string | `"idx_requestKey_groupKey"` | GSI name for reverse lookups. Added if absent. | | `dynamodb.ttlAttributeName` | string | `"ttl"` | Numeric attribute holding unix epoch seconds for TTL. | | `dynamodb.initTimeout` | Duration | `5s` | Session creation and table/index init timeout. | | `dynamodb.getTimeout` | Duration | `1s` | Per-Get deadline. | | `dynamodb.setTimeout` | Duration | `2s` | Per-Set/Delete/Lock deadline. | | `dynamodb.maxRetries` | int | `0` (SDK default) | AWS SDK retry count for transient errors. | | `dynamodb.statePollInterval` | Duration | `5s` | `WatchCounterInt64` polling interval. | | `dynamodb.lockRetryInterval` | Duration | **no default** (zero) | **Footgun**: zero duration → retry loop spins as fast as the API under lock contention. Always set to `100ms` in production. — [`data/dynamodb.go:L660-688`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L660-L688) | #### gRPC connector — [`common/config.go:L354-359`](https://github.com/erpc/erpc/blob/main/common/config.go#L354-L359), defaults [`common/defaults.go:L927-929`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L927-L929) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `grpc.bootstrap` | string | — | HTTP URL returning JSON array or newline-separated gRPC server URLs. Fetched once at startup; failure → connector init error. | | `grpc.servers` | []string | — | Explicit server list. Combined with bootstrap results when both present. | | `grpc.headers` | map[string]string | — | Headers sent on every gRPC call. | | `grpc.getTimeout` | Duration | `100ms` | Per-Get call timeout. Applied only when shorter than existing context deadline. | #### Timeout buffer constants — [`data/timeout_constants.go:L7-15`](https://github.com/erpc/erpc/blob/main/data/timeout_constants.go#L7-L15) | Constant | Value | Usage | |---|---|---| | `DefaultOperationBuffer` | `10s` | Time reserved after lock acquisition for in-lock operations. Used by Redis lock retry budget calculation. | | `PollOperationBuffer` | `15s` | Reserved in the state poller after lock acquisition. | | `MinPollTimeout` | `30s` | Minimum timeout for a complete poll cycle. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Split memory caches for unfinalized vs. finalized data.** Production deployments keep two separate in-process connectors — a large one for the high-volume unfinalized stream (recently mined blocks, txs still propagating) and a smaller one for immutable finalized data. This lets ristretto tune its frequency sketch and cost budget independently for each access pattern: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: memory-cache-unfinalized driver: memory memory: # high-traffic: recent blocks, pending txs, unconfirmed receipts maxItems: 2000000 # NumCounters = 3 × maxItems = 6 M — enough sketch space for 2 M hot keys maxTotalSize: "8GB" - id: memory-cache-finalized driver: memory memory: # lower traffic: immutable block/tx data older than ~128 blocks maxItems: 500000 maxTotalSize: "4GB" ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "memory-cache-unfinalized", driver: "memory", memory: { // high-traffic: recent blocks, pending txs, unconfirmed receipts maxItems: 2000000, // NumCounters = 3 × maxItems = 6 M — enough sketch space for 2 M hot keys maxTotalSize: "8GB", }, }, { id: "memory-cache-finalized", driver: "memory", memory: { // lower traffic: immutable block/tx data older than ~128 blocks maxItems: 500000, maxTotalSize: "4GB", }, }, ], }, } ``` **2. gRPC BDS connector with hedge + timeout failsafe.** The canonical production pattern: a gRPC historical-data reader as the first connector, wrapped with a 400ms timeout and a p95 quantile hedge so a slow BDS server fires a backup rather than stalling the request. The hedge delay tracks this connector's own recent latency (1-minute window per method/finality executor); before any samples exist it falls back to `base + min`: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: bds-cache driver: grpc grpc: # static server list — or use bootstrap: URL for dynamic discovery servers: - grpc://bds-reader.example.com:50051 # cap total gRPC call time; past this, go to live upstreams instead getTimeout: 400ms failsafeForGets: - matchMethod: "*" retry: maxAttempts: 2 # retry immediately — a slow BDS call beats a fast empty one delay: "0" timeout: # 400ms = the same as getTimeout; belt-and-suspenders at the # failsafe layer in case gRPC context propagation is delayed duration: 400ms hedge: delay: # p95 of this connector's own completed reads (1-minute window) quantile: 0.95 # floor; also cold-start fallback (no samples yet → base+min) min: 50ms max: 200ms maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "bds-cache", driver: "grpc", grpc: { // static server list — or use bootstrap URL for dynamic discovery servers: ["grpc://bds-reader.example.com:50051"], // cap total gRPC call time; past this, go to live upstreams instead getTimeout: "400ms", }, failsafeForGets: [{ matchMethod: "*", retry: { maxAttempts: 2, delay: "0" }, // 400ms = same as getTimeout; belt-and-suspenders at failsafe layer timeout: { duration: "400ms" }, // p95 of this connector's own reads (1m window); cold start → base+min hedge: { maxCount: 1, delay: { quantile: 0.95, min: "50ms", max: "200ms" } }, }], }], }, } ``` **3. gRPC connector with bearer-authenticated edge API and a Redis write layer.** The gRPC connector is read-only (eRPC skips writes to it); pair it with Redis for writes. For Goldsky's hosted cache, see [Goldsky cache (gRPC)](/config/database/goldsky-cache.llms.txt). Production configs using a public BDS edge gateway attach auth headers per-connector — secrets stay in environment variables, not in the config file. A gateway that serves many chains on one host mounts each chain under a URL path: list one URL per chain, and eRPC maps each to its network by calling `ChainId`: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: bds-edge driver: grpc grpc: # grpcs:// without a port dials 443; the path mounts every call servers: - grpcs://bds-edge-api.example.com/ethereum - grpcs://bds-edge-api.example.com/base getTimeout: 400ms headers: # bearer token loaded from env — never hardcode secrets in config authorization: "Bearer \${BDS_API_TOKEN}" failsafeForGets: - matchMethod: "*" retry: { maxAttempts: 2, delay: "0" } timeout: { duration: 400ms } hedge: { maxCount: 1, delay: 100ms } - id: redis-write driver: redis redis: uri: "\${REDIS_URL}" connPoolSize: 16 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "bds-edge", driver: "grpc", grpc: { servers: [ "grpcs://bds-edge-api.example.com/ethereum", "grpcs://bds-edge-api.example.com/base", ], getTimeout: "400ms", // bearer token loaded from env — never hardcode secrets in config headers: { authorization: "Bearer \${BDS_API_TOKEN}" }, }, failsafeForGets: [{ matchMethod: "*", retry: { maxAttempts: 2, delay: "0" }, timeout: { duration: "400ms" }, hedge: { maxCount: 1, delay: "100ms" }, }], }, { id: "redis-write", driver: "redis", redis: { uri: "\${REDIS_URL}", connPoolSize: 16 }, }, ], }, } ``` **4. Redis shared state for multi-pod deployments.** When multiple eRPC instances need to coordinate (shared scoring state, distributed locking), use Redis for `sharedState`. This is separate from the cache connector — a single Redis URI with no extra config needed: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: # must be unique across all eRPC clusters sharing this Redis clusterKey: my-erpc-prod connector: driver: redis redis: # credentials via env var — never inline in config uri: "\${SHARED_STATE_REDIS_URL}" ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { // must be unique across all eRPC clusters sharing this Redis clusterKey: "my-erpc-prod", connector: { driver: "redis", redis: { // credentials via env var — never inline in config uri: "\${SHARED_STATE_REDIS_URL}", }, }, }, } ``` **5. DynamoDB for serverless deployments.** Useful when you want fully managed persistence without operating Redis. Set `lockRetryInterval` explicitly — the default is zero and the retry loop spins as fast as the DynamoDB API under contention, which can exhaust provisioned throughput: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: ddb-cache driver: dynamodb dynamodb: region: us-east-1 table: erpc_json_rpc_cache # CRITICAL: no default — zero = spin loop under lock contention lockRetryInterval: 100ms getTimeout: 1s setTimeout: 2s auth: mode: env # or "file" / "secret" # YAML key is accessKeyID (capital I and D) — accessKeyId silently fails accessKeyID: "\${AWS_ACCESS_KEY_ID}" secretAccessKey: "\${AWS_SECRET_ACCESS_KEY}" ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "ddb-cache", driver: "dynamodb", dynamodb: { region: "us-east-1", table: "erpc_json_rpc_cache", // CRITICAL: no default — zero = spin loop under lock contention lockRetryInterval: "100ms", getTimeout: "1s", setTimeout: "2s", auth: { mode: "env", // YAML key is accessKeyID (capital I and D) — accessKeyId silently fails accessKeyID: "\${AWS_ACCESS_KEY_ID}", secretAccessKey: "\${AWS_SECRET_ACCESS_KEY}", }, }, }], }, } ``` **6. Passwordless AWS IAM auth (ElastiCache + RDS).** Run on EC2/EKS with an instance role (or IRSA) and drop static passwords entirely. Omit `iamAuth.auth` so the AWS SDK default chain provides credentials; eRPC mints and rotates SigV4 tokens automatically. Note there is **no password** in either connection string, and `region`/`endpoint`/`dbUser` are derived when omitted: **Config path:** `database.evmJsonRpcCache.connectors[]` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: elasticache-iam driver: redis redis: # no password — IAM token is injected as AUTH on every new connection addr: my-cluster.abc123.ng.0001.use1.cache.amazonaws.com:6379 iamAuth: enabled: true cacheName: my-cluster # replication-group ID (auto-lowercased) userID: iam-user-01 # ElastiCache user name == user ID # region derived from AWS_REGION / instance metadata; auth omitted = instance role # TLS is auto-enabled (rediss://); add a tls block only for a custom CA - id: rds-iam driver: postgresql postgresql: # no password in the URI; sslmode=require is appended automatically connectionUri: postgres://erpc-user@mydb.abc123.us-east-1.rds.amazonaws.com:5432/erpc table: erpc_json_rpc_cache iamAuth: enabled: true # region, endpoint and dbUser are derived from connectionUri / metadata ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "elasticache-iam", driver: "redis", redis: { // no password — IAM token is injected as AUTH on every new connection addr: "my-cluster.abc123.ng.0001.use1.cache.amazonaws.com:6379", iamAuth: { enabled: true, cacheName: "my-cluster", // replication-group ID (auto-lowercased) userID: "iam-user-01", // ElastiCache user name == user ID // region derived; auth omitted = instance role / IRSA }, // TLS is auto-enabled (rediss://); add a tls block only for a custom CA }, }, { id: "rds-iam", driver: "postgresql", postgresql: { // no password in the URI; sslmode=require is appended automatically connectionUri: "postgres://erpc-user@mydb.abc123.us-east-1.rds.amazonaws.com:5432/erpc", table: "erpc_json_rpc_cache", iamAuth: { enabled: true, // region, endpoint and dbUser derived from connectionUri / metadata }, }, }, ], }, } ``` The RDS database user must exist and hold `rds_iam` before first connect: ```sql CREATE USER "erpc-user" WITH LOGIN; GRANT rds_iam TO "erpc-user"; -- eRPC creates the table and indexes on first connect; the user needs CREATE on -- the schema. PostgreSQL ≥15 no longer grants public-schema CREATE by default: GRANT ALL ON SCHEMA public TO "erpc-user"; ``` Minimal IAM policy for the instance role: ```json [ { "Effect": "Allow", "Action": "elasticache:Connect", "Resource": [ "arn:aws:elasticache:us-east-1:123456789012:replicationgroup:my-cluster", "arn:aws:elasticache:us-east-1:123456789012:user:iam-user-01" ] }, { "Effect": "Allow", "Action": "rds-db:connect", "Resource": "arn:aws:rds-db:us-east-1:123456789012:dbuser:db-XXXXXXXXXXXXXXXX/erpc-user" } ] ``` The RDS `db-XXXXXXXXXXXXXXXX` resource ID is the instance's resource ID (RDS console → instance details), not its name. ### Request/response behavior - `NewConnector` dispatches on `cfg.Driver`. Unknown driver → `ErrInvalidConnectorDriver` at startup; never returned during live request processing. [[`data/connector.go:L63-103`](https://github.com/erpc/erpc/blob/main/data/connector.go#L63-L103)] - `Set` always writes `ConnectorMainIndex`. Memory writes a reverse-index companion for any architecture-prefixed key (`evm:`, `svm:`, …) when `WithReverseIndex` is on the ctx. Redis writes that companion only for `evm:`-prefixed keys. Without the ctx value the `rvi#` entry is skipped. Memory reverse index entries carry no TTL; stale pointers after main entry expiry resolve to cache misses. [[`data/memory.go:L121-155`](https://github.com/erpc/erpc/blob/main/data/memory.go#L121-L155)] [[`data/redis.go:L359-362`](https://github.com/erpc/erpc/blob/main/data/redis.go#L359-L362)] - DynamoDB applies a client-side epoch check on every `Get` and returns `ErrRecordExpired` for items past TTL regardless of AWS purge lag. Callers must distinguish `ErrRecordExpired` from `ErrRecordNotFound`. [[`data/dynamodb.go:L547-556`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L547-L556)] - gRPC intercepts `eth_blockNumber` and translates it to `eth_getBlockByNumber("latest", false)`, returning only the `number` field as a canonical hex string. On failure returns `ErrRecordNotFound` (falls through to real upstreams). [[`data/grpc.go:L265-278`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L265-L278)] - `FailsafeConnector` bypasses failsafe policies for `List`, `Lock`, `WatchCounterInt64`, and `PublishCounterInt64`. Only `Get`, `Set`, and `Delete` get failsafe treatment. [[`data/failsafe.go:L308-322`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L308-L322)] - `FailsafeConnector` forwards `CacheLatestBlock` to the wrapped connector so the freshness gate works even when the gRPC connector is wrapped. [[`data/failsafe.go:L211-216`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L211-L216)] - `isTransportError` is the sole retryability gate: `ErrRecordNotFound`, `ErrRecordExpired`, `context.Canceled`, and `context.DeadlineExceeded` are not transport errors and are never retried. [[`data/failsafe.go:L25-92`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L25-L92)] - `pickCacheExecutor` four-tier priority: (method + finality) > (method only) > (finality only) > (wildcard). A no-op executor is always appended so unmatched operations proceed unconditionally. [[`data/failsafe.go:L159-201`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L159-L201)] ### Best practices - **Use Redis for multi-instance deployments** — memory is single-process only and `List` is unimplemented; any shared-state or admin endpoint that needs `List` silently breaks with memory. - **Set `dynamodb.lockRetryInterval: 100ms` explicitly in production.** DynamoDB has no default; zero means the retry loop spins as fast as the HTTP API responds under contention. Redis defaults to `500ms`. - **Set PostgreSQL timeouts explicitly; do not rely on the connection URI.** Unlike Redis, `initTimeout`, `getTimeout`, and `setTimeout` are always Go context deadlines and are never read from `connectionUri`. Setting `connect_timeout=5` in the DSN has no effect on these fields. - **Always supply a `caFile` or client cert when using `rediss://` in production.** A `rediss://`-only URI without a YAML `tls:` block produces `InsecureSkipVerify=true`. - **Never use `dynamodb.auth.accessKeyId` (lowercase `d`).** The struct tag is `yaml:"accessKeyID"` — a lowercase `d` silently skips the field and falls through to the default credential chain. - **Plan for a 60-second warm-up when using the gRPC connector with the freshness gate.** The block-head poller first fires at T+60s. During this window `CacheLatestBlock` returns `ok=false` and the freshness gate fails open — stale realtime responses may be served. - **Wrap the gRPC connector with a circuit-breaker** in `failsafeForGets` to avoid hammering a BDS server that is returning errors; without it, every cache request makes a gRPC call when the BDS layer is unhealthy. - **Prefer IAM auth over static passwords on AWS.** With `redis.iamAuth` / `postgresql.iamAuth` enabled and `iamAuth.auth` omitted, the instance role / IRSA chain provides credentials and eRPC rotates short-lived tokens automatically — no secrets in config, no rotation tooling. Keep host clocks NTP-synced; SigV4 tokens are time-bound (±5 minutes). ### Edge cases & gotchas 1. **Memory `List` is not implemented.** Returns an error with guidance to use Redis/PostgreSQL/DynamoDB. Any subsystem needing `List` (admin endpoints, shared-state enumeration) must not use the memory driver. [`data/memory.go:L316-L321`](https://github.com/erpc/erpc/blob/main/data/memory.go#L316-L321) 2. **Memory reverse index has no TTL.** Main entries expire; their reverse index pointers remain until cost-based eviction. Stale pointers resolve to misses — no incorrect data is served. Redis correctly propagates TTL to reverse index entries. [`data/memory.go:L128-L130`](https://github.com/erpc/erpc/blob/main/data/memory.go#L128-L130) 3. **Memory cost overhead is 256 bytes per entry.** Even a 1-byte value costs 257 bytes against `maxTotalSize`. Small-value workloads require a proportionally larger `maxTotalSize`. [`data/memory.go:L78-L80`](https://github.com/erpc/erpc/blob/main/data/memory.go#L78-L80) 4. **DynamoDB TTL lag (~48h).** AWS native TTL expiry is eventually consistent. The connector applies a client-side epoch check returning `ErrRecordExpired`, but callers must distinguish `ErrRecordExpired` from `ErrRecordNotFound` since the expired item still exists in DynamoDB. [`data/dynamodb.go:L547-L556`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L547-L556) 5. **DynamoDB `lockRetryInterval` has no default.** Zero duration → retry loop spins as fast as the DynamoDB API under contention. Set `dynamodb.lockRetryInterval: 100ms` in production. Contrast: Redis defaults to `500ms`. [`data/dynamodb.go:L660-L688`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L660-L688) 6. **PostgreSQL advisory lock is non-blocking.** `pg_try_advisory_xact_lock` returns immediately with `false` if locked. No built-in retry loop — callers must implement their own. [`data/postgresql.go:L558-L573`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L558-L573) 7. **PostgreSQL timeouts cannot be set via connection URI.** Unlike Redis, `initTimeout`, `getTimeout`, and `setTimeout` are always Go context deadlines. Setting `connect_timeout=5` in the DSN does NOT populate `initTimeout`. Configure all three explicitly in YAML. [`data/postgresql.go:L130-L134`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L130-L134) 8. **PostgreSQL `cron.schedule` is not idempotent.** `applySchema` is gated by a `schemaApplied` flag (set once per process lifetime) to prevent duplicate pg_cron jobs on reconnect. [`data/postgresql.go:L257-L268`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L257-L268) 9. **gRPC connector supports no writes, and eRPC skips them.** It implements `ReadOnlyConnector`, so a policy on it never matches for set (even with `appliesTo: both`) and no write is attempted, counted as an error or logged. A policy whose only connector is gRPC therefore caches nothing locally; use it as a read-through layer alongside a write-capable connector. [`data/grpc.go:L454-L478`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L454-L478) 10. **gRPC head poller first fires at T+60s.** Block-head gauges are zero for the first 60 seconds. During this window the freshness gate fails open — cached realtime responses may be served. [`data/grpc.go:L302-L313`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L302-L313) 11. **gRPC bootstrap fetch is not retried.** If `fetchGrpcServers` fails at startup, `NewGrpcConnector` returns an error. Individual per-server connection tasks ARE retried by the initializer. [`data/grpc.go:L88-L95`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L88-L95) 12. **gRPC freshness gate fails open for non-gRPC connectors.** Memory, Redis, PostgreSQL, and DynamoDB do not implement `CacheHeadReporter`. When `eth_blockNumber` or `eth_gasPrice` is fetched from one of these connectors, `shouldAcceptCachedResult` cannot determine response age and unconditionally accepts the cached result. [`architecture/evm/json_rpc_cache.go:L862-L920`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L862-L920) 13. **gRPC block-head poller: zero `latestTs` means "unknown", not genesis block.** When `eth_getBlockByNumber("latest")` returns a block with a zero or absent `timestamp` field, `CacheLatestBlock` returns `ok=false` and the freshness gate fails open. [`data/grpc.go:L349-L357`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L349-L357) 14. **Quantile timeout/hedge at connector scope resolve from the connector's own latency window.** Each (method, finality) executor owns a `QuantileTracker` — 1-minute sliding window, 10 sub-buckets rotated every ~6s — created only when a configured policy sets `quantile > 0` (static configs pay no tracking cost). Only completed operations feed it: successes, semantic misses, and the executor's own timeout expiry; transport errors and attempts canceled by the parent context stay out. Cold start falls back to `base + min`. [`data/cache_executor.go:L14-L20`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L14-L20), [`data/cache_executor.go:L266-L281`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L266-L281) 15. **Consensus rejected for connector-level failsafe.** `consensus` non-nil at construction → `ErrFailsafeConfiguration` at startup. [`data/cache_executor.go:L59-L63`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L59-L63) 16. **`dynamodb.auth.accessKeyID` is case-sensitive.** The struct tag is `yaml:"accessKeyID"` (capital `I` and `D`). Using `accessKeyId` (lowercase `d`) silently skips the field; AWS falls through to the default credential chain. [`common/config.go:L483`](https://github.com/erpc/erpc/blob/main/common/config.go#L483) 17. **Redis TLS merging with `rediss://` URIs.** When both a `rediss://` URI and `tls.enabled: true` are configured, YAML cert/CA overrides merge onto the URI-derived TLS baseline and disable `InsecureSkipVerify`. A `rediss://`-only URI without a YAML `tls:` block produces `InsecureSkipVerify=true`. Always supply a `caFile` or client cert when using `rediss://` in production. [`data/redis.go:L156-L180`](https://github.com/erpc/erpc/blob/main/data/redis.go#L156-L180) 18. **`FailsafeConnector` wrapping does not break `CacheHeadReporter`.** `FailsafeConnector` forwards `CacheLatestBlock` to the wrapped connector, so the freshness gate works correctly even when the gRPC connector has failsafe policies. [`data/failsafe.go:L211-L216`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L211-L216) 19. **gRPC freshness gate: response timestamp takes precedence over connector head.** `shouldAcceptCachedResult` first extracts a block timestamp from the cached response itself. Only if the response carries no timestamp does it fall back to `CacheLatestBlock`. For `eth_getBlockByNumber` (which returns a full block with a timestamp), the response timestamp is used regardless of the connector's polled head. [`architecture/evm/json_rpc_cache.go:L862-L920`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L862-L920) 20. **PostgreSQL pub/sub falls back to 30-second polling.** If `LISTEN/NOTIFY` is unavailable (e.g., connection pooler that strips it), `WatchCounterInt64` falls back to a 30-second polling interval. Channel names are sanitized to valid PostgreSQL identifier characters with a maximum of 63 bytes. [`data/postgresql.go:L1103-L1127`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L1103-L1127) 21. **DynamoDB backward compatibility: `S` and `B` attribute types both accepted.** When reading items, both binary (`B`) and legacy string (`S`) value attributes are handled. Legacy string values are returned as `[]byte`. If neither attribute is present, the item is skipped. [`data/dynamodb.go:L512-L566`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L512-L566) 22. **PostgreSQL pool lock timing.** During reconnect, `connectTask` holds the write lock only for the field swap (nanoseconds). Schema setup and pool creation happen outside the lock. The old pool is closed after releasing the lock to prevent blocking hot-path reads/writes during pool drain. [`data/postgresql.go:L176-L250`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L176-L250) 23. **IAM auth + static password is rejected at startup.** Redis rejects a password embedded in the URI when `iamAuth.enabled: true`; PostgreSQL rejects a password in `connectionUri`. Remove the password — the IAM token is injected at connect time. [`common/validation.go:L556-L630`](https://github.com/erpc/erpc/blob/main/common/validation.go#L556-L630) 24. **ElastiCache `userID` must equal the user name.** For IAM-enabled ElastiCache users the user name and user ID are identical by AWS requirement; supply that single value as `userID`. A mismatch authenticates as the wrong user or fails. `cacheName` is lowercased automatically (AWS lowercases at creation), but the ElastiCache user must still match `userID` exactly. [`common/defaults.go:L971-L982`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L971-L982) 25. **ElastiCache IAM connections are force-disconnected at 12h.** AWS drops IAM-authenticated connections after 12 hours. eRPC pins `ConnMaxLifetime=11h` (±30m jitter) so go-redis rotates connections — re-invoking `CredentialsProviderContext` for a fresh token — before the cliff. Do not override the pool lifetime when IAM auth is on. ElastiCache Serverless is unsupported (no `PSUBSCRIBE`). [`data/redis_iam_auth.go:L22-L24`](https://github.com/erpc/erpc/blob/main/data/redis_iam_auth.go#L22-L24) 26. **RDS `iamAuth.dbUser` must match the `connectionUri` user.** When both are set and differ, startup fails — pgx would otherwise sign the token for `dbUser` while connecting as the URI user, a silent auth mismatch. The user must hold `rds_iam` and SSL is mandatory (`sslmode=require` is appended automatically; an explicit weaker `sslmode` is rejected). [`common/validation.go:L556-L590`](https://github.com/erpc/erpc/blob/main/common/validation.go#L556-L590) 27. **SigV4 tokens are clock-sensitive.** ElastiCache presigned tokens and RDS auth tokens are time-bound (±5 minutes). Unsynced host clocks (no NTP) cause intermittent auth failures on new connections. [`data/redis_iam_auth.go:L1-L86`](https://github.com/erpc/erpc/blob/main/data/redis_iam_auth.go#L1-L86) ### Observability #### Prometheus metrics — [`telemetry/metrics.go:L73-107`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L73-L107), [`telemetry/metrics.go:L628-638`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L628-L638) | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_ristretto_cache_current_cost` | gauge | `connector` | Every 30s by memory connector when `emitMetrics=true`. Bytes currently used by ristretto. | | `erpc_ristretto_cache_sets_failed_total` | counter | `connector` | Every 30s; delta of `SetsDropped + SetsRejected` from ristretto stats. | | `erpc_cache_connector_earliest_block_number` | gauge | `connector`, `network` | Set every 60s when gRPC `fetchTaggedBlock("earliest")` succeeds. Drives fast-miss rejection. Not reset on transient poll failure. | | `erpc_cache_connector_latest_block_number` | gauge | `connector`, `network` | Set every 60s when gRPC `fetchTaggedBlock("latest")` succeeds. | | `erpc_cache_connector_finalized_block_number` | gauge | `connector`, `network` | Set every 60s when finalized block is fetchable. | | `erpc_cache_connector_earliest_block_timestamp_seconds` | gauge | `connector`, `network` | Unix timestamp (seconds) of the earliest known block. Set only when block timestamp > 0. | | `erpc_cache_connector_latest_block_timestamp_seconds` | gauge | `connector`, `network` | Unix timestamp of the latest block. Drives the freshness gate via `CacheLatestBlock`. Alert when this lags wall-clock by more than your expected block interval. Zero means unknown → freshness gate fails open. | | `erpc_cache_connector_finalized_block_timestamp_seconds` | gauge | `connector`, `network` | Unix timestamp of the finalized block. Set only when block timestamp > 0. | #### Trace spans | Span name | Connector | Notable attributes | |---|---|---| | `RedisConnector.Set` | Redis | `partition_key`, `range_key`, `value_size` | | `RedisConnector.Get` | Redis | `index`, `partition_key`, `range_key`, `value_size` | | `RedisConnector.Delete` | Redis | | | `RedisConnector.List` | Redis | `index`, `limit` | | `RedisConnector.Lock` | Redis | `lock_key`, `ttl_ms` | | `RedisConnector.Unlock` | Redis | `lock_key` | | `RedisConnector.PublishCounterInt64` | Redis | `key`, `value`, `updated_at`, `updated_by` | | `DynamoDBConnector.Set` | DynamoDB | | | `DynamoDBConnector.Get` | DynamoDB | | | `DynamoDBConnector.Delete` | DynamoDB | | | `DynamoDBConnector.List` | DynamoDB | | | `DynamoDBConnector.Lock` | DynamoDB | | | `DynamoDBConnector.Unlock` | DynamoDB | | | `DynamoDBConnector.getSimpleValue` | DynamoDB | Detail span | | `PostgreSQLConnector.Set` | PostgreSQL | | | `PostgreSQLConnector.Get` | PostgreSQL | | | `PostgreSQLConnector.Delete` | PostgreSQL | | | `PostgreSQLConnector.List` | PostgreSQL | | | `PostgreSQLConnector.Lock` | PostgreSQL | | | `PostgreSQLConnector.Unlock` | PostgreSQL | | | `PostgreSQLConnector.PublishCounterInt64` | PostgreSQL | | | `PostgreSQLConnector.getCurrentValue` | PostgreSQL | Detail span | | `PostgreSQLConnector.getWithWildcard` | PostgreSQL | Detail span | | `ConnectorFailsafe.Get` | FailsafeConnector | `connector.id`, `connector.partition_key`, `connector.range_key`, `failsafe.match_method`, `result.bytes` | | `ConnectorFailsafe.Set` | FailsafeConnector | `connector.id`, `connector.partition_key`, `connector.range_key`, `failsafe.match_method`, `value.bytes`, `ttl.ms` | | `ConnectorFailsafe.Delete` | FailsafeConnector | | #### Notable log messages | Message | Level | Driver | Meaning | |---|---|---|---| | `"redis is not connected (state: %s), errors: %v"` | Warn | Redis | Every Get/Set/Lock attempt while connector is not ready. | | `"detected critical connection failure, marking for reconnection"` | Warn | Redis | `markConnectionAsLostIfNecessary` fired; reconnect enqueued. | | `"successfully connected to Redis"` | Info | Redis | Ping succeeded after (re)connect. | | `"postgres connection lost; marking connector as failed for reinitialization"` | Warn | PostgreSQL | `handleConnectionFailure` triggered reconnect. | | `"successfully connected to postgres"` | Info | PostgreSQL | Pool swap complete. | | `"migrating value column from TEXT to BYTEA"` / `"successfully migrated value column to BYTEA"` | Info | PostgreSQL | One-time schema migration. | | `"successfully configured pg_cron cleanup job"` | Info | PostgreSQL | pg_cron extension detected and job installed. | | `"starting local expired items cleanup routine"` | Debug | PostgreSQL | pg_cron absent; local 5-minute ticker used instead. | | `"List operation on MemoryConnector is not efficiently supported"` | Warn | Memory | `List` called on memory connector (unimplemented). | | `"gRPC client initialized for network"` | Info | gRPC | Chain probe succeeded for a server. | | `"duplicate gRPC server for network detected; ignoring"` | Error | gRPC | Two servers returned the same `chainId`. | | `"Starting Ristretto metrics collection loop"` | Info | Memory | `emitMetrics=true`, background goroutine started. | ### Source code entry points - [`data/connector.go:L40-L103`](https://github.com/erpc/erpc/blob/main/data/connector.go#L40-L103) — `Connector` interface; `CacheHeadReporter`; `NewConnector` factory; `ConnectorMainIndex` / `ConnectorReverseIndex` constants - [`data/memory.go:L1-L321`](https://github.com/erpc/erpc/blob/main/data/memory.go#L1-L321) — ristretto-backed connector; TTL; reverse index; no-op pub/sub; TryLock; background metrics; unimplemented `List` - [`data/redis.go:L1-L784`](https://github.com/erpc/erpc/blob/main/data/redis.go#L1-L784) — Redis connector; URI construction; TLS merging; narrow reconnect detection; redsync locking; SCAN-based `List` - [`data/redis_pubsub_manager.go`](https://github.com/erpc/erpc/blob/main/data/redis_pubsub_manager.go) — self-healing pub/sub manager; transparent reconnection; copy-on-write subscriber management - [`data/timeout_constants.go`](https://github.com/erpc/erpc/blob/main/data/timeout_constants.go) — `DefaultOperationBuffer` (10s), `PollOperationBuffer` (15s), `MinPollTimeout` (30s) - [`data/postgresql.go:L1-L1270`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L1-L1270) — pgxpool connector; schema migration; pg_cron or local cleanup ticker; advisory locks; LISTEN/NOTIFY pub/sub; connection failure coalescing - [`data/dynamodb.go:L1-L983`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L1-L983) — DynamoDB connector; split read/write clients; GSI; native TTL + client-side expiry check; conditional-PutItem locking; polling `WatchCounterInt64` - [`data/grpc.go:L1-L478`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L1-L478) — Read-only gRPC BDS connector; bootstrap; chain probing; `eth_blockNumber` translation; fast-miss rejection; 60s head poller; `CacheLatestBlock` - [`data/failsafe.go:L25-L216`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L25-L216) — `FailsafeConnector`; `pickCacheExecutor` four-tier selection; `isTransportError`; `CacheHeadReporter` forwarding - [`data/cache_executor.go:L1-L310`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L1-L310) — `cacheExecutor` retry/hedge/breaker/timeout pipeline; per-executor latency window feeding quantile timeout/hedge; transport-error-only retry; own-timeouts-as-breaker-failures classification; consensus rejection - [`architecture/evm/json_rpc_cache.go:L834-L924`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L834-L924) — `shouldAcceptCachedResult`: freshness gate; response-timestamp path; `CacheHeadReporter` fallback; fail-open logic - [`common/defaults.go:L846-L1099`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L846-L1099) — `SetDefaults` for all connector configs; driver inference; default table names by scope; IAM auto-TLS (Redis) and `sslmode=require` + endpoint/dbUser derivation (PostgreSQL) - [`data/aws_auth.go:L1-L42`](https://github.com/erpc/erpc/blob/main/data/aws_auth.go#L1-L42) — shared `createAWSSession` helper; resolves `iamAuth.auth` modes or the AWS SDK default credential chain - [`data/redis_iam_auth.go:L1-L86`](https://github.com/erpc/erpc/blob/main/data/redis_iam_auth.go#L1-L86) — ElastiCache SigV4 presign; scheme stripping; `CredentialsProviderContext`; 11h connection-lifetime constants - [`data/postgresql_iam_auth.go:L1-L39`](https://github.com/erpc/erpc/blob/main/data/postgresql_iam_auth.go#L1-L39) — RDS `rdsutils.BuildAuthToken` minted inside the pgxpool `BeforeConnect` hook ### Related pages - [Cache policies](/config/database/cache-policies.llms.txt) — configure which methods get cached and with what TTL; connectors are selected here. - [Real-time cache](/config/database/realtime.llms.txt) — the freshness gate that uses gRPC connector's `CacheHeadReporter`. - [Retry](/config/failsafe/retry.llms.txt) — the same retry semantics available in `failsafeForGets` / `failsafeForSets`. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — breaker semantics for connector-level failsafe; cache misses count as ignored, not failures; the executor’s own timeout expiry counts as a failure, so sustained timeouts exclude the connector until a probe completes in time. - [Hedge](/config/failsafe/hedge.llms.txt) — static or quantile hedge at connector layer; quantile resolves from the connector's own latency window. --- --- # Cache policies > Source: https://docs.erpc.cloud/config/database/evm-json-rpc-cache > Stop paying for the same upstream call twice — eRPC caches every EVM JSON-RPC response by finality bucket, fans out reads in parallel, and rejects stale tip-of-chain data before it ever reaches your users. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Cache policies Every repeated upstream call costs money and latency. eRPC intercepts each EVM JSON-RPC request, matches it against your cache policies, and serves the stored response — no extra round-trip. Finalized data is cached forever; realtime data is age-gated against the actual block timestamp so stale chain-tip responses never escape. **What you get** - Parallel fan-out reads across multiple backends — fastest hit wins, peers cancel - Four finality buckets (`finalized`, `unfinalized`, `realtime`, `unknown`) each with independent TTLs - Transparent zstd compression on writes, automatic decompression on reads - Per-request bypass directive (`X-ERPC-Skip-Cache-Read`) for cache-busting without config changes ## Quick taste Illustrative, not a tuned production config — cache finalized data forever in memory: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 100000 } policies: - connector: mem network: "*" method: "*" # finalized blocks are reorg-immune — cache them forever finality: finalized # 0 = no expiry; safe because finalized data never changes ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "mem", driver: "memory", memory: { maxItems: 100000 } }], policies: [{ connector: "mem", network: "*", method: "*", // finalized blocks are reorg-immune — cache them forever finality: "finalized", // 0 = no expiry; safe because finalized data never changes ttl: 0, }], }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up caching from scratch** ```text I want to stop paying for repeated upstream calls by enabling eRPC's EVM JSON-RPC cache. Set up a four-bucket cache (finalized, unfinalized, realtime, unknown) with an in-memory connector so every finality class is covered. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/database/evm-json-rpc-cache.llms.txt ``` **Prompt Example #2: add a persistent Redis tier behind in-memory** ```text I already have an in-memory cache connector in my eRPC config but I want to add Redis as a warm durable fallback so cached data survives restarts. Wire both connectors to the same finalized and unfinalized policies so the memory connector wins fan-out races when hot. Reference: https://docs.erpc.cloud/config/database/evm-json-rpc-cache.llms.txt ``` **Prompt Example #3: debug realtime cache misses (eth_blockNumber always bypasses cache)** ```text My eRPC cache seems to have zero hits for eth_blockNumber and eth_call with "latest". Audit my cache policies in my eRPC config and explain why realtime methods are missing, then add the correct finality: realtime policy with an appropriate TTL. Reference: https://docs.erpc.cloud/config/database/evm-json-rpc-cache.llms.txt ``` **Prompt Example #4: limit cache to a specific method allowlist to avoid wasted connector RTTs** ```text I want to restrict my cache policies so only the methods my gRPC connector actually indexes are tried (eth_getBlockByNumber, eth_getBlockByHash, eth_getBlockReceipts, eth_getLogs, eth_getTransactionByHash, eth_getTransactionReceipt). Requests for other methods should skip the cache entirely. Update my eRPC config accordingly. Reference: https://docs.erpc.cloud/config/database/evm-json-rpc-cache.llms.txt ``` **Prompt Example #5: shadow-write to a new connector before enabling reads** ```text I want to migrate to a new PostgreSQL cache connector without risking stale reads. Set up a shadow-write policy (appliesTo: set) on the new connector while keeping reads on the existing one, so I can verify data populates correctly before cutting over. My config is in my eRPC config. Reference: https://docs.erpc.cloud/config/database/evm-json-rpc-cache.llms.txt ``` --- ### Cache policies — full agent reference ### How it works **Policy matching pipeline.** At startup eRPC builds an ordered slice of `CachePolicy` objects from `evmJsonRpcCache.policies`. Every request passes through `findGetPolicies` (reads) or `findSetPolicies` (writes). Both walk the slice and test each policy's `network`, `method`, `params`, and `finality` fields against the request. For reads, finality matching is asymmetric: a finalized request also matches unfinalized policies (a block finalized after write may be stored under the unfinalized policy); a realtime request matches only realtime policies; an unknown-finality request matches all policies. For writes, finality must match exactly. `findGetPolicies` deduplicates by connector so each connector is probed at most once per request. **Cache key derivation.** Every lookup computes a partition key `{networkId}:{blockRef}` (or `{networkId}:{cacheKeySuffix}:{blockRef}` when `networks[].cacheKeySuffix` is set) and a range key `{method}:{sha256(params)}`. `:` and `\` inside the block ref are backslash-escaped so an unsuffixed ref cannot collide with a suffixed key; refs without those bytes are unchanged. The block reference comes from `ExtractBlockReferenceFromRequest`, which inspects the per-method `reqRefs` path config. If the block reference resolves to `*` (a wildcard tag like `"latest"`), the connector is queried via a reverse index rather than the main index. If the block reference is empty — method not recognized or not cacheable — the whole cache lookup is skipped silently. **Get fan-out.** `Get` spawns one goroutine per matching policy. All goroutines race under a shared `fanCtx`; the first to find an acceptable non-empty hit calls `cancelFan()` so peers exit without posting to metrics. Results travel through a buffered channel sized to the number of goroutines so no goroutine ever blocks after `fanCtx` is done — a slow peer that refuses to honour cancellation never pins user-visible latency. A 30-second backstop context wraps the fan-out when the parent carries no deadline, protecting against FD leaks from misbehaving connectors. **Set fan-out.** `Set` fans out using `sync.WaitGroup` (fire-and-forget per policy). A hard 5-second write timeout is applied per connector, independent of any failsafe configuration. Responses with a JSON-RPC error field are never cached. Empty results for future blocks (beyond the network's confidence head) are never cached regardless of the `empty` policy setting. **Realtime freshness gate.** After a cache hit is retrieved for a realtime request, `shouldAcceptCachedResult` compares the block's unix timestamp (extracted from the response via `ExtractBlockTimestampFromResponse`) against the policy TTL. This is **block age, not cache-entry wall-clock age**: a response cached 5 minutes ago is accepted if its block was produced 3 seconds ago; a response cached 30 seconds ago is rejected if its block is 2 minutes old and TTL is 60 s. For responses with no block timestamp (`eth_blockNumber`, `eth_gasPrice`, `eth_getLogs`), the gate falls back to the connector's own latest-block timestamp via the `CacheHeadReporter` interface — currently implemented only by `GrpcConnector`, which polls every 60 seconds. If neither source is available the gate fails open (accepts the result). When age exceeds TTL the result is reclassified as `ttl_rejected` and the fan-out loop continues searching peer connectors. Non-realtime data (finalized, unfinalized, unknown) is never age-gated. **Finality buckets.** The zero value of the Go `DataFinalityState` enum is `finalized`, so omitting `finality` in YAML silently creates a finalized-only policy. | Finality | Meaning | Recommended TTL | |---|---|---| | `finalized` | Past chain's finalization horizon; reorg-immune | `0` (forever) | | `unfinalized` | Recent block, still reorgable | 5–15 s (≈ 2× block time) | | `realtime` | Updates every block (`eth_blockNumber`, `eth_gasPrice`, …) | 1–3 s | | `unknown` | Block reference indeterminate (tx-hash keyed) | `0` (key is immutable) | To cache all traffic types you need at least four policies — one per finality bucket — or the realtime/unfinalized traffic will always bypass the cache and hit upstreams. **Empty-result handling.** The `empty` field controls three modes: - `ignore` (default) — empty results are never cached on write; cached empty results are treated as misses on read. - `allow` — cache and serve empty results like any other result. - `only` — cache and serve only empty results; non-empty responses skip this policy. A result is "emptyish" if the raw JSON bytes are `null`, `""`, `"0x"`, `"0x0"`, `0`, `[]`, `{}`, or a hex string whose non-prefix digits are all zeros. **Skip-cache-read directive.** Callers can set the `X-ERPC-Skip-Cache-Read` HTTP header or `skip-cache-read` query parameter to bypass specific connectors. The value can be `"true"` (skip all connectors), `"false"` (normal), or a glob pattern matched against connector IDs. **Compression.** When `evmJsonRpcCache.compression.enabled = true` (the default — auto-created even when the `compression:` block is omitted), values are compressed with zstd before storage. Only values whose pre-compression size meets or exceeds `threshold` (default 1024 bytes) are compressed; smaller values are stored raw. If the compressed output is larger than the original it is also stored raw. Detection on read is by the zstd magic bytes `0x28 0xB5 0x2F 0xFD` — no explicit flag needed. **Connector failsafe wrapping.** When a connector config lists `failsafeForGets` or `failsafeForSets`, the raw connector is wrapped in a `FailsafeConnector`. Retry, hedge, timeout, and circuit-breaker are supported; hedge and timeout accept quantile-driven (adaptive) values, which resolve against the connector’s own 1-minute sliding latency window tracked per (method, finality) executor — configuring either in quantile mode creates that tracker, and cold start (no samples yet) falls back to `base + min`. The circuit breaker counts the executor’s own timeout expiry as a failure, so sustained timeouts exclude the connector (fail-fast to upstream fallthrough) until a half-open probe completes in time. Consensus is not supported at this scope. **gRPC connector (BDS read-through).** `GrpcConnector` is a read-only connector backed by BDS gRPC servers. It does not support `Set`, and its policies never match for writes, so `appliesTo: get` is optional. Supported methods: `eth_getBlockByNumber`, `eth_getBlockByHash`, `eth_getLogs`, `eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`, `eth_chainId`, `eth_blockNumber`. `eth_blockNumber` is derived by fetching the latest block internally — there is no native BDS gRPC call for it. The gRPC connector performs a fast-miss check: if the request block number is below the connector's earliest known block, it returns `ErrRecordNotFound` immediately without a network call. **CacheHash derivation (range key).** The range key `{method}:{sha256(params)}` is computed by `JsonRpcRequest.CacheHash` (`common/json_rpc.go:L1385-L1409`). It hashes params positionally using SHA-256 over a recursive type-aware `hashValue` function, producing a hex string prefixed with the method name. The hash is memoized on the request object — multiple policies referencing the same request compute it only once. **reqRefs and respRefs — block reference extraction.** These per-method config fields (`networks[*].methods.definitions..reqRefs` / `respRefs`) tell the block-reference extraction logic where in a JSON-RPC request or response to find a block number, tag, or hash. They determine whether a request is cacheable and what partition key to use. Built-in path variables in `common/defaults.go`: | Variable | Path | Used by | |---|---|---| | `FirstParam` | `[[0]]` | `eth_getBlockByNumber`, `eth_getBlockByHash`, … | | `SecondParam` | `[[1]]` | `eth_getStorageAt`, `eth_getCode`, … | | `ThirdParam` | `[[2]]` | `eth_getProof` | | `NumberOrHashParam` | `[["number"], ["hash"]]` | response object fields | | `BlockNumberOrBlockHashParam` | `[["blockNumber"], ["blockHash"]]` | receipt-like responses | | `ArbitraryBlock` | `[["*"]]` | `eth_getTransactionByHash`, `eth_getTransactionReceipt` — tx-hash methods | Path format: each selector is an `[]interface{}` where integers index JSON arrays and strings key into JSON objects. An empty path (`[]`) means the value at that position IS the scalar. A single-element path `["*"]` means "arbitrary block" — produces `blockRef = "*"` which routes to the reverse index. **reqRefs extraction algorithm** (`architecture/evm/block_ref.go:L277-L310`): 1. If `reqRefs` has exactly one path of length 1 and that element is `"*"`: return `blockRef="*"` immediately. 2. Otherwise for each path, parse the value as a block parameter (hex number, decimal, or named tag). 3. If multiple paths yield different block references (e.g. `eth_getLogs` with different `fromBlock`/`toBlock`): set `blockRef = "*"` (composite range). 4. Accumulate the highest block number seen across all paths. 5. If no path resolves: `blockRef = ""` → cache bypassed entirely, trace attribute `cache.skip_reason = "empty_block_ref"` set. **respRefs extraction algorithm** (`architecture/evm/block_ref.go:L343-L368`): Called only after a response exists. First non-`"*"` block ref wins; result supplements or overrides the request-derived ref for the cache key. Custom `reqRefs`/`respRefs` in user config **override built-in defaults entirely** — there is no merge. ### Config schema All fields are under `database.evmJsonRpcCache`. `Duration` values accept Go duration strings or bare integers (milliseconds). #### `database.evmJsonRpcCache` (root) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `database.evmJsonRpcCache` | `*CacheConfig` | `nil` | When `nil` (omitted): cache subsystem is entirely disabled — the `EvmJsonRpcCache` object is never created. `SetDefaults` on sub-fields is only called when this pointer is non-nil. The auto-generated project (`id: "main"`, created when no `projects:` block exists) has NO `evmJsonRpcCache` config. You must provide the key explicitly to enable caching. Source: [`common/defaults.go:L831-836`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L831-L836) | | `cachingStrategy` | `'defaultAllow' \| 'defaultIgnore'` | `defaultAllow` (omit → same) | Write-side admission default combined with the response `cacheable` mark (set by consensus via `cacheableResponses`). `defaultAllow`: write unless mark is `false`; unmarked (`nil`) still writes **except** on networks with a `customPolicy` selector — Forward skips Set when the mark is nil so no-consensus sibling routes cannot poison the selector-shared store. `defaultIgnore`: write only when mark is `true`. Cache stays consensus-ignorant — it never sees policy names. Source: [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go), [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go), [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) | For requests that keep a moving tag untranslated (`"latest"`, `"finalized"` — by default `eth_getBlockByNumber`), eRPC keys the cache entry by the concrete block number — the response's own number on write, the network's tracked tip on read. `"safe"` keeps its literal-tag key. That means a burst of concurrent tag queries landing on the same tip coalesces onto one cached entry, but once the tip advances the key changes and the next request forwards upstream. You don't have to worry about a `"latest"` query returning a block that's multiple tips stale just because the TTL hasn't expired. #### `evmJsonRpcCache.compression` Auto-created even when omitted: `CacheConfig.SetDefaults` always creates `&CompressionConfig{}` and calls its `SetDefaults()` when `c.Compression == nil`. The only way to opt out is `compression.enabled: false`. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `compression.enabled` | `*bool` | `true` — set by `SetDefaults` when nil | Enable zstd compression. Footgun: omitting the block silently enables compression. Source: [`common/defaults.go:L580-582`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L580-L582) | | `compression.algorithm` | string | `"zstd"` | Only `"zstd"` is implemented; reserved for future algorithms. Source: [`common/defaults.go:L585-587`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L585-L587) | | `compression.zstdLevel` | string | `"fastest"` | Valid: `"fastest"`, `"default"`, `"better"`, `"best"`. Unknown values fall back to `fastest` with a warning. Source: [`common/defaults.go:L590-592`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L590-L592) | | `compression.threshold` | int (bytes) | `1024` | Minimum pre-compression size to attempt compression. Footgun: the inline code default is 512 bytes but `SetDefaults` overrides to 1024; `SetDefaults` wins at runtime. Source: [`common/defaults.go:L597-599`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L597-L599) | #### `evmJsonRpcCache.connectors[*]` Connector `SetDefaults` is called with `scope = connectorScopeCache`, which sets cache-specific defaults. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `connectors[*].id` | string | `"cache-"` | Unique ID referenced by policies. Auto-set to `"cache-" + driver` when blank. Source: [`common/defaults.go:L847-849`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L847-L849) | | `connectors[*].driver` | string | required | One of `memory`, `redis`, `dynamodb`, `postgresql`, `grpc`. | | `connectors[*].memory.maxItems` | int | required | Max items in Ristretto in-process cache. | | `connectors[*].memory.maxTotalSize` | string | required | Max total memory, e.g. `"1GB"`. | | `connectors[*].memory.emitMetrics` | `*bool` | `nil` | Emit Ristretto cost/set-failure metrics when true. | | `connectors[*].redis.addr` | string | `""` | Redis `host:port`. Mutually exclusive with `uri`. | | `connectors[*].redis.uri` | string | `""` | Full Redis URI. Preferred over `addr`. | | `connectors[*].redis.password` | string | `""` | Redacted in JSON/YAML marshal. | | `connectors[*].redis.db` | int | `0` | Redis DB index. | | `connectors[*].redis.connPoolSize` | int | `0` (driver default) | Connection pool size. | | `connectors[*].redis.initTimeout` | Duration | driver default | Timeout for initial connection. | | `connectors[*].redis.getTimeout` | Duration | driver default | Per-GET timeout. | | `connectors[*].redis.setTimeout` | Duration | driver default | Per-SET timeout. | | `connectors[*].redis.lockRetryInterval` | Duration | driver default | Distributed lock retry interval. | | `connectors[*].redis.tls` | `*TLSConfig` | `nil` | Optional TLS for Redis. | | `connectors[*].dynamodb.table` | string | required | DynamoDB table name. | | `connectors[*].dynamodb.region` | string | required | AWS region. | | `connectors[*].dynamodb.partitionKeyName` | string | required | Partition key attribute name. | | `connectors[*].dynamodb.rangeKeyName` | string | required | Range key attribute name. | | `connectors[*].dynamodb.reverseIndexName` | string | required | GSI name for reverse index (wildcard block lookups). | | `connectors[*].dynamodb.ttlAttributeName` | string | required | DynamoDB TTL attribute name. | | `connectors[*].dynamodb.initTimeout` | Duration | driver default | Init timeout. | | `connectors[*].dynamodb.getTimeout` | Duration | driver default | Per-GET timeout. | | `connectors[*].dynamodb.setTimeout` | Duration | driver default | Per-SET timeout. | | `connectors[*].dynamodb.maxRetries` | int | `0` | AWS SDK max retries. | | `connectors[*].dynamodb.statePollInterval` | Duration | driver default | State poller interval. | | `connectors[*].dynamodb.lockRetryInterval` | Duration | driver default | Distributed lock retry interval. | | `connectors[*].postgresql.connectionUri` | string | required | PostgreSQL connection URI. Redacted in marshal. | | `connectors[*].postgresql.table` | string | `"erpc_json_rpc_cache"` (cache scope) | Auto-set to `"erpc_json_rpc_cache"` when scope=cache and value is blank. Source: [`common/defaults.go:L1027`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1027) | | `connectors[*].postgresql.minConns` | int32 | `4` (cache scope) | Min pool connections. Source: [`common/defaults.go:L1034-1040`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1034-L1040) | | `connectors[*].postgresql.maxConns` | int32 | `32` (cache scope) | Max pool connections. Source: [`common/defaults.go:L1041-1047`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1041-L1047) | | `connectors[*].grpc.bootstrap` | string | `""` | HTTP URL to fetch gRPC server list. | | `connectors[*].grpc.servers` | `[]string` | nil | Explicit gRPC server URLs. When both `bootstrap` and `servers` are provided, explicit list takes precedence and bootstrap is also resolved and appended. Source: [`data/grpc.go:L85-95`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L85-L95) | | `connectors[*].grpc.headers` | `map[string]string` | nil | Headers sent with every gRPC request. | | `connectors[*].grpc.getTimeout` | Duration | `100ms` | Per-call timeout. Applied when the existing context deadline is absent or farther in the future than `getTimeout`. Footgun: older docs incorrectly stated `0 (no override)`; the correct runtime default is 100ms. Source: [`common/defaults.go:L927-929`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L927-L929) | | `connectors[*].failsafeForGets` | `[]*FailsafeConfig` | nil | Per-connector failsafe for Get operations. Hedge and timeout accept quantile-driven values resolved from the connector's own latency window ([`data/cache_executor.go:L204-207`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L204-L207), [`data/cache_executor.go:L244-249`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L244-L249)). Consensus is not supported at this scope. Source: [`data/cache_executor.go:L59-63`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L59-L63) | | `connectors[*].failsafeForSets` | `[]*FailsafeConfig` | nil | Per-connector failsafe for Set operations. Same semantics as Gets. | #### `evmJsonRpcCache.policies[*]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `policies[*].connector` | string | required | ID matching a `connectors[*].id`. | | `policies[*].network` | string | `"*"` | Wildcard/glob network filter against `networkId`. Source: [`common/defaults.go:L608-610`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L608-L610) | | `policies[*].method` | string | `"*"` | Wildcard/glob method filter. Source: [`common/defaults.go:L605-607`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L605-L607) | | `policies[*].params` | `[]interface{}` | nil | Positional parameter pattern; nil matches any params. Each element: string (wildcard-matched), object (recursive key match), array (index match), or nil (match any/absent). Extra params beyond pattern length are ignored. | | `policies[*].finality` | `DataFinalityState` | `finalized` (zero value of iota) | One of `finalized`, `unfinalized`, `realtime`, `unknown`. **Footgun: omitting this field is byte-identical to `finality: finalized`.** Realtime methods will silently miss unless a separate `finality: realtime` policy exists. Source: [`common/data.go:L9-27`](https://github.com/erpc/erpc/blob/main/common/data.go#L9-L27) | | `policies[*].empty` | `CacheEmptyBehavior` | `ignore` (iota=0) | One of `ignore`, `allow`, `only`. | | `policies[*].appliesTo` | `CachePolicyAppliesTo` | `"both"` | One of `"both"`, `"get"`, `"set"`. Restricts whether the policy is evaluated for reads, writes, or both. Source: [`common/defaults.go:L611-613`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L611-L613) | | `policies[*].minItemSize` | `*string` | nil | ByteSize string (`"512B"`, `"1KB"`, `"2MB"`). Measured as **pre-compression length of the JSON-RPC `result` field bytes**. Responses smaller than this are silently skipped (no error, increments `erpc_cache_set_skipped_total`). Source: [`architecture/evm/json_rpc_cache.go:L1069-1072`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1069-L1072) | | `policies[*].maxItemSize` | `*string` | nil | ByteSize string. Same format and measurement as `minItemSize`. Responses whose result byte length exceeds this are silently skipped. Source: [`data/cache_policy.go:L152-160`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L152-L160) | | `policies[*].ttl` | Duration | `0` (unlimited) | Time-to-live stored with each key. When set on a `realtime` policy, also used as the freshness window in the age gate. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Two-tier memory connectors: fast unfinalized + large finalized pool.** Production fleets separate recent reorgable data from immutable historical data because their access patterns and eviction pressures differ. Unfinalized blocks churn quickly; finalized blocks are read far more and rarely evicted: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: memory-cache-unfinalized driver: memory memory: # High item count for fast-cycling recent blocks and tx receipts maxItems: 2000000 # Cap at 8GB: recent data is small-ish JSON, 2M items * ~4KB avg maxTotalSize: 8GB - id: memory-cache-finalized driver: memory memory: # Lower count: finalized items are large (full blocks, log ranges) maxItems: 500000 maxTotalSize: 4GB policies: - connector: memory-cache-unfinalized network: "*" # Only methods this fleet actually indexes — wildcard eth_get* wastes RTTs # on guaranteed misses for eth_getBalance, eth_getCode, eth_getProof, etc. method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: unfinalized # empty: allow — a null receipt means "not indexed yet"; still worth # caching so rapid polling doesn't hammer upstreams for the same miss empty: allow ttl: 0 - connector: memory-cache-unfinalized network: "*" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: unknown empty: allow ttl: 0 - connector: memory-cache-finalized network: "*" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: finalized empty: allow # 0 = no expiry: finalized data is reorg-immune and never goes stale ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "memory-cache-unfinalized", driver: "memory", memory: { // High item count for fast-cycling recent blocks and tx receipts maxItems: 2000000, // Cap at 8GB: recent data is small-ish JSON, 2M items * ~4KB avg maxTotalSize: "8GB", }, }, { id: "memory-cache-finalized", driver: "memory", memory: { // Lower count: finalized items are large (full blocks, log ranges) maxItems: 500000, maxTotalSize: "4GB", }, }, ], policies: [ { connector: "memory-cache-unfinalized", network: "*", // Only methods this fleet actually indexes — wildcard eth_get* wastes RTTs // on guaranteed misses for eth_getBalance, eth_getCode, eth_getProof, etc. method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "unfinalized", // empty: allow — a null receipt means "not indexed yet"; still worth // caching so rapid polling doesn't hammer upstreams for the same miss empty: "allow", ttl: 0, }, { connector: "memory-cache-unfinalized", network: "*", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "unknown", empty: "allow", ttl: 0, }, { connector: "memory-cache-finalized", network: "*", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "finalized", empty: "allow", // 0 = no expiry: finalized data is reorg-immune and never goes stale ttl: 0, }, ], }, } ``` **2. gRPC read-through connector with quantile hedge and per-call timeout.** When the primary cache backend is a remote gRPC server (BDS read-through), add a quantile hedge so a slow node doesn't hold up the request — the delay resolves against this connector's own 1-minute latency window (per method/finality executor), and falls back to `base + min` before any samples exist. The `400ms` timeout keeps the cache miss path fast enough that going straight to upstreams is always cheaper than waiting on a struggling connector: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: grpc-cache driver: grpc grpc: # getTimeout: applied when parent context has no deadline or a farther deadline # 400ms: if the cache read takes longer, skip it and go to upstreams getTimeout: 400ms servers: - https://rpc.example.com:50051 headers: Authorization: "Bearer \${CACHE_API_TOKEN}" failsafeForGets: - matchMethod: "*" timeout: # Hard ceiling on a single get call; hedge fires before this duration: 400ms hedge: delay: # p95 of this connector's own completed reads (1-minute window) quantile: 0.95 # floor; also cold-start fallback (no samples yet → base+min) min: 50ms max: 200ms maxCount: 1 retry: maxAttempts: 2 # 0: retry immediately — no point waiting for a slow cache node delay: "0" policies: - connector: grpc-cache network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unfinalized empty: allow # get-only: gRPC connector is read-only, no Set support appliesTo: get ttl: 0 - connector: grpc-cache network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unknown empty: allow appliesTo: get ttl: 0 - connector: grpc-cache network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: finalized empty: allow appliesTo: get ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "grpc-cache", driver: "grpc", grpc: { // getTimeout: applied when parent context has no deadline or a farther deadline // 400ms: if the cache read takes longer, skip it and go to upstreams getTimeout: "400ms", servers: ["https://rpc.example.com:50051"], headers: { Authorization: "Bearer \${CACHE_API_TOKEN}" }, }, failsafeForGets: [{ matchMethod: "*", timeout: { duration: "400ms" }, hedge: { // p95 of this connector's own reads (1m window); cold start → base+min delay: { quantile: 0.95, min: "50ms", max: "200ms" }, maxCount: 1, }, retry: { maxAttempts: 2, delay: "0" }, }], }], policies: [ { connector: "grpc-cache", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "unfinalized", empty: "allow", appliesTo: "get", ttl: 0, }, { connector: "grpc-cache", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "unknown", empty: "allow", appliesTo: "get", ttl: 0, }, { connector: "grpc-cache", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "finalized", empty: "allow", appliesTo: "get", ttl: 0, }, ], }, } ``` **3. Chain-specific gRPC reader in front of a wildcard fallback pool.** Production fleets often have a high-fidelity per-chain reader colocated in the same cluster alongside a broader pooled connector that covers every chain. The chain-specific connector wins the connector dedup for its network; the wildcard connector catches everything else. Per-chain reader policies come first so their `network: "evm:1"` entries win before the wildcard `network: "*"` entry: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: eth-reader driver: grpc grpc: getTimeout: 400ms servers: - grpc://eth-reader-lb.cache.svc.cluster.local:50051 failsafeForGets: - matchMethod: "*" retry: { maxAttempts: 2, delay: "0" } timeout: { duration: 400ms } hedge: { delay: 100ms, maxCount: 1 } - id: edge-cache-pool driver: grpc grpc: getTimeout: 400ms servers: - https://cache-base.rpc.example.com:50051 - https://cache-arbitrum.rpc.example.com:50051 failsafeForGets: - matchMethod: "*" retry: { maxAttempts: 2, delay: "0" } timeout: { duration: 400ms } hedge: { delay: 100ms, maxCount: 1 } - id: memory-cache-finalized driver: memory memory: { maxItems: 500000, maxTotalSize: 4GB } policies: # Chain-specific per-chain reader policies come first — connector dedup means these # win the evm:1 slot; the wildcard pool never sees evm:1 requests - connector: eth-reader network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unfinalized empty: allow appliesTo: get ttl: 0 - connector: eth-reader network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unknown empty: allow appliesTo: get ttl: 0 - connector: eth-reader network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: finalized empty: allow appliesTo: get ttl: 0 # Wildcard pool covers all other chains - connector: edge-cache-pool network: "*" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: unfinalized empty: allow appliesTo: get ttl: 0 - connector: edge-cache-pool network: "*" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: unknown empty: allow appliesTo: get ttl: 0 - connector: edge-cache-pool network: "*" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*" finality: finalized empty: allow appliesTo: get ttl: 0 # In-memory finalized cache for all chains — written by upstreams, read locally - connector: memory-cache-finalized network: "*" method: "*" finality: finalized ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "eth-reader", driver: "grpc", grpc: { getTimeout: "400ms", servers: ["grpc://eth-reader-lb.cache.svc.cluster.local:50051"], }, failsafeForGets: [{ matchMethod: "*", retry: { maxAttempts: 2, delay: "0" }, timeout: { duration: "400ms" }, hedge: { delay: "100ms", maxCount: 1 }, }], }, { id: "edge-cache-pool", driver: "grpc", grpc: { getTimeout: "400ms", servers: ["https://cache-base.rpc.example.com:50051", "https://cache-arbitrum.rpc.example.com:50051"], }, failsafeForGets: [{ matchMethod: "*", retry: { maxAttempts: 2, delay: "0" }, timeout: { duration: "400ms" }, hedge: { delay: "100ms", maxCount: 1 }, }], }, { id: "memory-cache-finalized", driver: "memory", memory: { maxItems: 500000, maxTotalSize: "4GB" } }, ], policies: [ // Chain-specific per-chain reader policies come first — connector dedup means these // win the evm:1 slot; the wildcard pool never sees evm:1 requests { connector: "eth-reader", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "unfinalized", empty: "allow", appliesTo: "get", ttl: 0 }, { connector: "eth-reader", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "unknown", empty: "allow", appliesTo: "get", ttl: 0 }, { connector: "eth-reader", network: "evm:1", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt", finality: "finalized", empty: "allow", appliesTo: "get", ttl: 0 }, // Wildcard pool covers all other chains { connector: "edge-cache-pool", network: "*", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "unfinalized", empty: "allow", appliesTo: "get", ttl: 0 }, { connector: "edge-cache-pool", network: "*", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "unknown", empty: "allow", appliesTo: "get", ttl: 0 }, { connector: "edge-cache-pool", network: "*", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_query*", finality: "finalized", empty: "allow", appliesTo: "get", ttl: 0 }, // In-memory finalized cache for all chains — written by upstreams, read locally { connector: "memory-cache-finalized", network: "*", method: "*", finality: "finalized", ttl: 0 }, ], }, } ``` **4. Intentionally no realtime caching.** Some fleets deliberately skip the `finality: realtime` bucket so `eth_blockNumber`, `eth_getBlockByNumber("latest")`, and `eth_gasPrice` always go to fresh upstreams. This is the right choice when your cache connector doesn't implement `CacheHeadReporter` (all drivers except gRPC) — without a block timestamp the realtime age gate fails open and you'd serve stale chain-tip data. The three-bucket shape below makes the intent explicit and avoids the silent miss: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 500000, maxTotalSize: 4GB } policies: # Deliberately no finality: realtime policy — eth_blockNumber and "latest" # calls always bypass cache and go to upstreams for a fresh head - connector: mem network: "*" method: "*" finality: finalized ttl: 0 - connector: mem network: "*" method: "*" finality: unfinalized # ~2x Ethereum block time; adjust to 2x your slowest chain's block time ttl: 24s - connector: mem network: "*" method: "*" finality: unknown ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "mem", driver: "memory", memory: { maxItems: 500000, maxTotalSize: "4GB" } }], policies: [ // Deliberately no finality: realtime policy — eth_blockNumber and "latest" // calls always bypass cache and go to upstreams for a fresh head { connector: "mem", network: "*", method: "*", finality: "finalized", ttl: 0 }, { connector: "mem", network: "*", method: "*", finality: "unfinalized", // ~2x Ethereum block time; adjust to 2x your slowest chain's block time ttl: "24s", }, { connector: "mem", network: "*", method: "*", finality: "unknown", ttl: 0 }, ], }, } ``` **5. Shadow-write debugging mode.** Write cache entries for a new connector without risking stale reads — `appliesTo: set` means reads always go to upstreams while you verify the connector is populating correctly. Flip to `appliesTo: both` once you've confirmed hit rates in `erpc_cache_set_success_total`: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: new-pg driver: postgresql postgresql: connectionUri: "postgres://\${DB_USER}:\${DB_PASS}@db-new:5432/erpc" # table auto-set to "erpc_json_rpc_cache" at cache scope when blank policies: - connector: new-pg finality: finalized # set only: reads still hit upstreams; verify connector fills correctly appliesTo: set ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "new-pg", driver: "postgresql", postgresql: { connectionUri: "postgres://\${DB_USER}:\${DB_PASS}@db-new:5432/erpc", // table auto-set to "erpc_json_rpc_cache" at cache scope when blank }, }], policies: [{ connector: "new-pg", finality: "finalized", // set only: reads still hit upstreams; verify connector fills correctly appliesTo: "set", ttl: 0, }], }, } ``` ### Request/response behavior - **Cache key structure.** Partition key: `{networkId}:{blockRef}`, or `{networkId}:{cacheKeySuffix}:{blockRef}` when `networks[].cacheKeySuffix` is set. `:` and `\` in the block ref (and suffix) are backslash-escaped; other refs, including `"*"`, are stored as-is. Range key: `{method}:{sha256(params)}`. When `blockRef = "*"` (tag-based or multi-block range), the connector is queried via the reverse index (`ConnectorReverseIndex = "idx_reverse"`). When `blockRef = ""`, the lookup is bypassed entirely. Reverse-index wildcard is `{networkId}:{suffix}:*` (from `CachePartitionKey`), so suffixed and unsuffixed networks on the same chainId do not share a reverse-index slot even when the block ref contains `:`. - **`X-ERPC-Skip-Cache-Read` header / `skip-cache-read` query param.** Value `"true"` skips all connectors. A glob pattern (e.g. `"mem*"`) skips matching connectors only. Passing an empty connector ID with a pattern always returns false — patterns are only evaluated per-connector. - **Responses with a JSON-RPC `error` field are never cached.** Neither are empty results for blocks beyond the network's confidence head, regardless of `empty` policy setting. - **Set has a hard 5-second per-connector write timeout**, independent of any configured failsafe. If both are configured, the shorter one fires first. - **Realtime age gate uses block timestamp, not wall-clock cache age.** The `erpc_cache_get_age_guard_reject_total` metric fires when age exceeds TTL; its label is `method` not `category` — unique among cache metrics. ### Best practices - **Always define four policies (one per finality bucket) when you want to cache all traffic.** A single catch-all policy with no explicit `finality:` silently caches only finalized data. `eth_blockNumber`, `eth_gasPrice`, `eth_call` with `"latest"`, and `eth_getBalance` with `"latest"` are all `realtime` and will miss unless a `finality: realtime` policy exists. - **Keep realtime TTL between 1 and 3 s.** Lower than 1 s means the freshness gate will almost always reject on slower connectors; higher than 3 s risks serving chain-tip data that is multiple blocks stale. - **Set `finality: unfinalized` TTL at 2× block time.** For Ethereum mainnet (~12 s) use 24 s. This gives enough room for the block to finalize without serving stale data for too long. - **Place the fastest connector first in the policy list when sharing a finality bucket.** The Get fan-out races all connectors in parallel, but list order determines which connector wins ties and how quickly cancelation propagates. Memory connectors should come before Redis or PostgreSQL. - **Do not set `compression.enabled: false` unless you have profiled actual CPU overhead.** zstd at `"fastest"` level saves 50–80% storage on typical ABI-encoded JSON-RPC results. The benefit almost always outweighs the CPU cost, and the memory connector would double-compress without it (both layers detect magic bytes and short-circuit, but the extra pass is wasted work only when compression is enabled on both). - **Use `minItemSize` to avoid caching tiny responses.** Responses under 200 B are often `null`, short errors, or simple scalars. Caching them creates key-count pressure on Ristretto with negligible savings. - **Monitor `erpc_cache_get_age_guard_reject_total` vs `erpc_cache_get_success_hit_total` for realtime policies.** A high reject ratio means your realtime TTL is too tight relative to connector polling latency or your `GrpcConnector` head poll interval (60 s). Raise the TTL or switch to a connector with an embedded block timestamp in responses. ### Edge cases & gotchas 1. **`finality: finalized` is the zero value — intentionally the safest default.** The Go comment at [`common/data.go:L10-L15`](https://github.com/erpc/erpc/blob/main/common/data.go#L10-L15) explicitly states finalized gets 0 so that an unspecified finality defaults to the safest sane cache default. Omitting `finality` means only finalized requests match; realtime, unfinalized, and unknown requests bypass this policy and always hit upstreams. 2. **Realtime finality must be stated explicitly — omission silently drops all realtime traffic.** Common realtime methods that silently miss without `finality: realtime`: `eth_blockNumber`, `eth_gasPrice`, `eth_call` with `"latest"`, `eth_getBalance` with `"latest"`. This is the most common misconfiguration. 3. **findGetPolicies deduplicates by connector; findSetPolicies does not.** A connector can receive multiple writes for the same request if multiple policies reference it. Source: [`architecture/evm/json_rpc_cache.go:L926-L978`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L926-L978). 4. **Emptyish hit under `empty=ignore` is detected in the fan-out goroutine, not post-fan-out.** Without this, the emptyish result would win the race and cancel peers, losing a chance for a peer with `empty=allow` and non-empty data to win. Source: [`architecture/evm/json_rpc_cache.go:L343-L351`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L343-L351). 5. **The realtime age gate checks block timestamp, not cache-entry age.** A response cached 5 minutes ago is accepted if its block was produced 3 seconds ago. A response cached 30 seconds ago is rejected if its block is 2 minutes old and TTL is 60 s. Source: [`architecture/evm/json_rpc_cache.go:L841-L920`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L841-L920). 6. **`eth_blockNumber`, `eth_gasPrice`, and `eth_getLogs` carry no block timestamp** in their response. The realtime age gate falls back to the connector's `CacheLatestBlock`, which is only implemented by `GrpcConnector` (polls every 60 seconds). For all other connectors the gate fails open (accepts the cached result). Source: [`architecture/evm/json_rpc_cache.go:L879-L889`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L879-L889). 7. **Compression threshold has two definitions.** The inline code default in `NewEvmJsonRpcCache` is 512 bytes, but `SetDefaults` sets it to 1024 bytes. `SetDefaults` always runs at startup, so the effective default is 1024. The 512 value is only reachable when the cache object is constructed directly without `SetDefaults` (i.e., in unit tests). Source: [`common/defaults.go:L597-L599`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L597-L599). 8. **Set has a hard 5-second timeout per connector in addition to any failsafe timeout.** If both are configured, the shorter one fires first. The 5-second fallback protects connectors with no failsafe configured. Source: [`architecture/evm/json_rpc_cache.go:L768`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L768). 9. **`minItemSize` and `maxItemSize` measure pre-compression result length, not stored blob size.** A 4 KB result that compresses to 400 bytes still fails a `maxItemSize: 2KB` check. The measured value is `JsonRpcResponse.ResultLength()` — raw JSON result bytes, not the full JSON-RPC envelope. Source: [`architecture/evm/json_rpc_cache.go:L1067-L1072`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1067-L1072). 10. **Memory connector has independent internal zstd compression.** Combined with the `EvmJsonRpcCache` layer's own compression pass, values stored in the memory connector may be double-compressed. Both layers detect already-compressed data by magic bytes and short-circuit. Source: [`architecture/evm/json_rpc_cache.go:L1150-L1157`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1150-L1157). 11. **`SkipCacheRead` accepts both boolean and string values.** Both normalized to string on parse: `true` → `"true"`, `false` → `"false"`. The directive is accepted from config, the `X-ERPC-Skip-Cache-Read` HTTP header, and the `skip-cache-read` query parameter. Passing a glob pattern with an empty `connectorId` always returns false. Source: [`common/request.go:L895-914`](https://github.com/erpc/erpc/blob/main/common/request.go#L895-L914). 12. **Policy ordering matters for Get when finality = unknown.** All matching policies race in parallel; the fastest connector with data wins. Place the fastest connector first so it most likely wins. For Set, all matching policies receive the write regardless of order. 13. **`gRPC` connector is read-only.** It does not support `Set`. Supported methods: `eth_getBlockByNumber`, `eth_getBlockByHash`, `eth_getLogs`, `eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`, `eth_chainId`, `eth_blockNumber`. `eth_blockNumber` is derived by fetching the latest block internally. Source: [`data/grpc.go:L270-278`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L270-L278). 14. **`appliesTo: "set"` without a paired `"get"` policy** writes succeed but reads always miss — useful for shadow-write debugging but rarely the right production shape. 15. **`reqRefs` with multiple conflicting block references collapse to `"*"`.** `eth_getLogs` with different `fromBlock`/`toBlock` values routes to the reverse index and the partition key becomes `*`. Users must cache only finalized data for range-query methods to avoid serving stale reorged data. Source: [`architecture/evm/block_ref.go:L296-L300`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_ref.go#L296-L300). 16. **`ErrRecordNotFound` and `ErrEndpointMissingData` are semantic misses, not errors.** They must not increment `erpc_cache_get_error_total`. A regression where this happened caused 36k+ spurious errors per 15 minutes. Source: [`erpc/evm_json_rpc_cache_fanout_test.go`](https://github.com/erpc/erpc/blob/main/erpc/evm_json_rpc_cache_fanout_test.go). 17. **`database.evmJsonRpcCache: nil` completely disables the cache subsystem.** The `EvmJsonRpcCache` object is never created, saving memory and eliminating block-ref extraction overhead on every request. Source: [`common/defaults.go:L831-836`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L831-L836). 18. **Compression is auto-enabled — you cannot disable it by omitting the block.** `CacheConfig.SetDefaults` always creates `&CompressionConfig{}` and calls `SetDefaults()` on it (sets `enabled=true`). The only escape is explicitly setting `compression.enabled: false`. Source: [`common/defaults.go:L482-488`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L482-L488). 19. **Cancellation guard uses `fanCtx.Err()`, not `errors.Is(err, context.Canceled)`.** An inner failsafe wrapper can produce an opaque typed error that `errors.Is` cannot unwind. The fan-out loop trusts `fanCtx.Err()` as the authoritative cancellation signal so a losing peer's wrapped error never inflates `erpc_cache_get_error_total`. Source: [`erpc/evm_json_rpc_cache_fanout_test.go`](https://github.com/erpc/erpc/blob/main/erpc/evm_json_rpc_cache_fanout_test.go). 20. **Empty results for future (not-yet-produced) blocks are never cached, regardless of `empty` policy setting.** `emptyResultBeyondConfidence` compares the requested block number against the network's latest (or finalized) head. If the block hasn't been produced yet, the empty result is silently discarded — preventing the cache from poisoning responses for blocks that simply don't exist yet. Source: [`architecture/evm/json_rpc_cache.go:L1079-L1082`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1079-L1082), [`architecture/evm/common.go:L55-L89`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L55-L89). 21. **gRPC connector's block-head timestamp is set to zero when timestamp parse fails.** This is intentional: storing a stale timestamp from a previous poll would make `CacheLatestBlock` report a dangerously stale age. Storing 0 makes the realtime guard fail-open (accept the cached result) rather than reject based on wrong age data. Source: [`data/grpc.go:L350-L356`](https://github.com/erpc/erpc/blob/main/data/grpc.go#L350-L356). 22. **`appliesTo: "get"` enables independent write/read policies with different TTLs or finality.** Setting `appliesTo: "get"` on a policy means it will never be written to — a separate write-only policy (possibly with a different finality bucket or size limit) can populate the connector while the read-only policy controls what is served. The default `"both"` means the same policy governs both directions. 23. **Same-chain networks share partition keys unless `cacheKeySuffix` is set.** Two eRPC projects on chainId 998 with a shared Redis both write `evm:998:{blockRef}`. `X-ERPC-Skip-Cache-Read` skips the read but still writes, so the last fetch poisons the other project. Set `cacheKeySuffix` on one network (e.g. `systx` → `evm:998:systx:{blockRef}`). Colon is rejected in the suffix. A `:` inside the block ref is backslash-escaped in the partition key (`systx:foo` → `systx\:foo`) so it cannot equal suffix `systx` plus ref `foo`. Refs without `:` or `\` keep the historical key. The reverse-index wildcard (`evm:998:systx:*`) is passed explicitly by the cache layer via `CachePartitionKey`, not inferred from splitting the concrete key — so hash-keyed Gets (`eth_getTransactionByHash` / Receipt) stay isolated from the unsuffixed `evm:998:*` slot even when the block ref itself contains `:`. Memory/Redis `Delete` must use the same `WithReverseIndex` ctx as `Set`; otherwise the `rvi#` companion leaks (or, with last-colon inference, can clear the unsuffixed slot). DynamoDB/Postgres delete the main row, so the GSI/row reverse index goes with it. Source: [`common/config.go:L3022-L3028`](https://github.com/erpc/erpc/blob/main/common/config.go#L3022-L3028), [`architecture/evm/json_rpc_cache.go:L1250`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1250), [`data/connector.go`](https://github.com/erpc/erpc/blob/main/data/connector.go), [`data/memory.go`](https://github.com/erpc/erpc/blob/main/data/memory.go), [`data/redis.go`](https://github.com/erpc/erpc/blob/main/data/redis.go). 24. **Enabling `customPolicy` on a network that already warmed the same connectors:** cache keys do not carry a mark or policy, so pre-feature (or pre-selector) entries remain readable until TTL. Flush or rotate the connector (or wait out the longest TTL) when first turning on a selector against a previously open-write cache. Going forward, Forward skips Set for unmarked responses on selector-enabled networks so no-consensus sibling routes cannot re-poison the store under `defaultAllow`. Source: [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go), test `TestNetworkForward_SelectorSkipsUnmarkedSet`. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cache_get_skipped_total` | counter | project, network, category | No matching policy found for request | | `erpc_cache_get_success_hit_total` | counter | project, network, category, connector, policy, ttl | Cache hit returned to caller | | `erpc_cache_get_success_miss_total` | counter | project, network, category, connector, policy, ttl | All connectors confirmed miss | | `erpc_cache_get_error_total` | counter | project, network, category, connector, policy, ttl, error | Connector transport/non-semantic error | | `erpc_cache_get_age_guard_reject_total` | counter | project, network, **method**, connector, policy, ttl | Block timestamp age exceeded policy TTL; only realtime requests with non-zero TTL. Label is `method` not `category` — unique among cache metrics | | `erpc_cache_get_success_hit_duration_seconds` | histogram | project, network, category, connector, policy, ttl | Latency of a cache hit | | `erpc_cache_get_success_miss_duration_seconds` | histogram | project, network, category, connector, policy, ttl | Latency of a cache miss | | `erpc_cache_get_error_duration_seconds` | histogram | project, network, category, connector, policy, ttl, error | Latency when a connector returns a transport error | | `erpc_cache_set_success_total` | counter | project, network, category, connector, policy, ttl | Connector Set succeeded | | `erpc_cache_set_error_total` | counter | project, network, category, connector, policy, ttl, error | Connector Set failed | | `erpc_cache_set_skipped_total` | counter | project, network, category, connector, policy, ttl | `shouldCacheResponse` returned false (size limit, error field, empty-ignore, future block) | | `erpc_cache_set_original_bytes_total` | counter | project, network, category, connector, policy, ttl | Cumulative uncompressed bytes before any compression attempt; emitted for every successful set | | `erpc_cache_set_compressed_bytes_total` | counter | project, network, category, connector, policy, ttl | Cumulative bytes after zstd compression. Only emitted when compression was actually applied (enabled, value ≥ threshold, compressed < original). A zero value does NOT indicate a bug — it means compression was not applied in that window | | `erpc_cache_set_success_duration_seconds` | histogram | project, network, category, connector, policy, ttl | Latency of a successful set | | `erpc_cache_set_error_duration_seconds` | histogram | project, network, category, connector, policy, ttl, error | Latency when a connector Set returns an error | | `erpc_ristretto_cache_current_cost` | gauge | connector | Memory connector current cost in bytes | | `erpc_ristretto_cache_sets_failed_total` | counter | connector | Ristretto dropped or rejected a set | | `erpc_cache_connector_earliest_block_number` | gauge | connector, network | gRPC connector earliest known block number (refreshed every 60 s) | | `erpc_cache_connector_latest_block_number` | gauge | connector, network | gRPC connector latest block number (refreshed every 60 s) | | `erpc_cache_connector_finalized_block_number` | gauge | connector, network | gRPC connector finalized block number (refreshed every 60 s) | | `erpc_cache_connector_earliest_block_timestamp_seconds` | gauge | connector, network | gRPC connector earliest block unix timestamp (refreshed every 60 s) | | `erpc_cache_connector_latest_block_timestamp_seconds` | gauge | connector, network | gRPC connector latest block unix timestamp (refreshed every 60 s) | | `erpc_cache_connector_finalized_block_timestamp_seconds` | gauge | connector, network | gRPC connector finalized block unix timestamp (refreshed every 60 s) | **OTel trace spans:** | Span | Source | |---|---| | `Cache.Get` | `architecture/evm/json_rpc_cache.go:L153` | | `Cache.FindGetPolicies` | `architecture/evm/json_rpc_cache.go:L173` | | `Cache.GetForPolicy` | `architecture/evm/json_rpc_cache.go:L241` | | `Cache.Set` | `architecture/evm/json_rpc_cache.go:L572` | | `Evm.ExtractBlockReferenceFromRequest` | `architecture/evm/block_ref.go:L18` | | `Evm.ExtractBlockTimestampFromResponse` | `architecture/evm/block_ref.go:L190` | | `Request.GenerateCacheHash` | `common/json_rpc.go:L1387` | Span attributes on `Cache.Get`: `network.id`, `request.method`, `request.finality`, `cache.policies_matched`, `cache.hit` (bool), `cache.miss_reason`, `cache.miss_connector_id`, `cache.miss_policy`. Span attributes on `Cache.GetForPolicy`: `cache.policy_summary`, `cache.connector_id`, `cache.method`, `cache.get_outcome` (`found`/`miss`/`ttl_rejected`/`orphaned`/`empty_ignored`/`error`/`cancelled`), `cache.block_ref`, `cache.group_key`, `cache.request_key`. `orphaned`: an unfinalized entry names a block the chain tracker no longer pins at its number (a reorg replaced it); the read goes to an upstream and its answer replaces the entry. ### Debug log messages These `DEBUG`-level log messages appear in eRPC output and are useful for tracing cache behavior: | Message | Condition | |---|---| | `"will not cache the response because we cannot resolve a block reference"` | `blockRef` is empty on Set — method not in the cacheable set | | `"skip caching because response contains an error"` | `shouldCacheResponse` skipped due to JSON-RPC error field | | `"skip caching because response size does not match policy limits"` | result length outside `minItemSize`/`maxItemSize` | | `"skip caching empty result for a not-yet-produced (future) block"` | `emptyResultBeyondConfidence` — block number is ahead of network head | | `"rejecting cached result because block age exceeds policy TTL"` | age guard rejection in `shouldAcceptCachedResult` | | `"cached result rejected due to age exceeding TTL"` | same, logged at the Get fan-out level | | `"cache connector errored during GET"` | connector transport error (not a semantic miss) | | `"skipping cache connector due to skip-cache-read directive pattern"` | `SkipCacheRead` directive matched a connector ID glob | | `"returning cached response"` | hit served (Trace level also logs raw result) | | `"compressed cache value"` | zstd compression applied (includes original/compressed/savings) | | `"decompressed cache value"` | zstd decompression applied on read | ### Source code entry points - [`architecture/evm/json_rpc_cache.go:L153-L400`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L153-L400) — `EvmJsonRpcCache.Get`: parallel fan-out, fanCtx, 30-second backstop, winner selection - [`architecture/evm/json_rpc_cache.go:L572-L800`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L572-L800) — `EvmJsonRpcCache.Set`: parallel fan-out, 5-second hard write timeout, `shouldCacheResponse` - [`architecture/evm/json_rpc_cache.go:L841-L920`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L841-L920) — `shouldAcceptCachedResult`: realtime age gate, block-timestamp extraction, connector-head fallback, fail-open - [`data/cache_policy.go:L1-L200`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L1-L200) — `CachePolicy` struct; `MatchesForGet`, `MatchesForSet`, `matchParams`, `MatchesSizeLimits`, `GetTTL` - [`architecture/evm/block_ref.go:L277-L368`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_ref.go#L277-L368) — `ExtractBlockReferenceFromRequest`, `ExtractBlockReferenceFromResponse`: block-ref derivation, reqRefs/respRefs path walking - [`common/defaults.go:L474-L650`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L474-L650) — `CacheConfig.SetDefaults`, `CachePolicyConfig.SetDefaults`, `CompressionConfig.SetDefaults` - [`common/request.go:L895-L914`](https://github.com/erpc/erpc/blob/main/common/request.go#L895-L914) — `ShouldSkipCacheRead`: header/query parsing, boolean vs glob logic - [`erpc/evm_json_rpc_cache_fanout_test.go`](https://github.com/erpc/erpc/blob/main/erpc/evm_json_rpc_cache_fanout_test.go) — behavior-locking tests: slow-peer non-blocking, miss-as-error classification, cancellation wrapping ### Related pages - [Storage connectors](/config/database/connectors.llms.txt) — configure the memory, Redis, DynamoDB, PostgreSQL, and gRPC backends referenced by policies. - [Rate limiters](/config/rate-limiters.llms.txt) — limit how many upstream calls the cache miss path can trigger. - [Failsafe](/config/failsafe/retry.llms.txt) — retry/timeout/circuit-breaker applied per-connector via `failsafeForGets`/`failsafeForSets`. - [Reduce RPC costs](/use-cases/reduce-rpc-costs.llms.txt) — the primary use case this feature serves. - [EVM method reference](/reference/evm/methods.llms.txt) — per-method finality classification and built-in reqRefs/respRefs defaults. --- --- # Goldsky cache (gRPC) > Source: https://docs.erpc.cloud/config/database/goldsky-cache > Plug Goldsky's hosted, read-only gRPC cache into eRPC — historical blocks, logs, transactions and receipts served from Goldsky's indexed chain data before your requests reach your upstreams — and Monad's MIP-16 eth_queryLogs and eth_queryTransactions served natively. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Goldsky cache (gRPC) Goldsky hosts a read-only gRPC cache backed by its indexed chain data. Add it as a `grpc` [cache connector](/config/database/drivers.llms.txt) and eRPC asks it first for historical reads; a miss goes to your upstreams exactly as before. ## Set it up ### Get a Goldsky API key Sign up or sign in at [app.goldsky.com](https://app.goldsky.com), open **Edge RPC**, click **New endpoint**, then **Create endpoint**. Copy the **API Key** shown in the **Edge Endpoint Created** dialog. The same key works for Edge RPC and for the cache. Keep it out of your config file: ```bash export GOLDSKY_API_KEY=gs_edge_... ``` ### Add the connector and a policy One URL per chain; eRPC calls `ChainId` on each at startup to map it to its network. **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: goldsky-cache driver: grpc grpc: servers: - grpcs://edge.goldsky.com/cache/ethereum - grpcs://edge.goldsky.com/cache/base headers: x-api-key: \${GOLDSKY_API_KEY} # a read the cache can't answer this fast goes to your upstreams; # raise it to keep wide eth_getLogs ranges in the cache getTimeout: 200ms - id: memory-cache driver: memory policies: - connector: goldsky-cache network: "evm:1|evm:8453" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_getBlockReceipts|eth_chainId" finality: finalized - connector: goldsky-cache network: "evm:1|evm:8453" method: eth_blockNumber finality: realtime - connector: memory-cache network: "*" method: "*" finality: finalized ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [ { id: "goldsky-cache", driver: "grpc", grpc: { servers: [ "grpcs://edge.goldsky.com/cache/ethereum", "grpcs://edge.goldsky.com/cache/base", ], headers: { "x-api-key": "\${GOLDSKY_API_KEY}" }, // a read the cache can't answer this fast goes to your upstreams; // raise it to keep wide eth_getLogs ranges in the cache getTimeout: "200ms", }, }, { id: "memory-cache", driver: "memory" }, ], policies: [ { connector: "goldsky-cache", network: "evm:1|evm:8453", method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt|eth_getBlockReceipts|eth_chainId", finality: "finalized", }, { connector: "goldsky-cache", network: "evm:1|evm:8453", method: "eth_blockNumber", finality: "realtime", }, { connector: "memory-cache", network: "*", method: "*", finality: "finalized" }, ], }, } ``` The Goldsky cache is read-only. Keep a memory or Redis connector (above: `memory-cache`) for writes and for recent blocks the cache has not indexed yet. ### Check it works At startup eRPC logs one line per URL: ``` gRPC client initialized for network server=grpcs://edge.goldsky.com/cache/ethereum networkId=evm:1 ``` Then request an old block and look at the `X-ERPC-Cache` response header — `HIT` when the response came from a cache, `MISS` when it went to an upstream: ```bash curl -si http://localhost:4000/main/evm/1 \ -H 'content-type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"eth_getBlockByNumber","params":["0x1000000",false]}' \ | grep -i x-erpc-cache ``` Per connector, the Prometheus counter `erpc_cache_get_success_hit_total{connector="goldsky-cache"}` counts hits. ## What it serves - **Methods:** `eth_getBlockByNumber`, `eth_getBlockByHash`, `eth_getLogs`, `eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`, `eth_chainId`, `eth_blockNumber`. eRPC never sends other methods to the connector. - **Misses:** data not indexed yet (e.g. the chain tip) answers gRPC `OUT_OF_RANGE`; eRPC treats it as a cache miss and calls your upstreams. - **`eth_getLogs`:** up to 30,000 blocks per call. Block, transaction and receipt reads answer well within `getTimeout: 200ms`; a wide or dense `eth_getLogs` range takes longer and goes to your upstreams unless you raise it. - **Chains:** abstract, arbitrum, arbitrum-sepolia, arc, avalanche, base, base-sepolia, bsc, celo, ethereum, gnosis, hyperevm, ink, monad, optimism, polygon, robinhood, robinhood-testnet, sei, sepolia, tempo, tron. Use the name in the URL: `grpcs://edge.goldsky.com/cache/`. - **No writes:** the connector is read-only and eRPC never writes to it, so the policy needs no `appliesTo`. ## Monad `eth_query*` (MIP-16) On Monad (chain 143), the same endpoint also serves `eth_queryLogs` and `eth_queryTransactions` ([MIP-16](https://github.com/monad-crypto/MIPs/pull/89)) natively through `bds.evm.QueryService`: one paged read from Goldsky's index instead of a node call per block. Add it as a gRPC **upstream** (not a cache connector) that allows those methods. eRPC tries it first and answers `eth_queryBlocks`, `eth_queryTraces` and `eth_queryTransfers` with the [query shim](/reference/evm/method-handlers.llms.txt) on your archive node: **Config path:** `upstreams` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: goldsky-monad endpoint: grpcs://edge.goldsky.com/cache/monad grpc: headers: x-api-key: \${GOLDSKY_API_KEY} evm: chainId: 143 ignoreMethods: ["*"] allowMethods: - eth_chainId - eth_getBlockByNumber - eth_queryLogs - eth_queryTransactions - id: monad-archive endpoint: https://your-monad-archive-node evm: chainId: 143 # serves eth_queryBlocks, eth_queryTraces and eth_queryTransfers, # and any range the Goldsky upstream cannot answer queryShim: enabled: true ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [ { id: "goldsky-monad", endpoint: "grpcs://edge.goldsky.com/cache/monad", grpc: { headers: { "x-api-key": "\${GOLDSKY_API_KEY}" } }, evm: { chainId: 143 }, ignoreMethods: ["*"], allowMethods: ["eth_chainId", "eth_getBlockByNumber", "eth_queryLogs", "eth_queryTransactions"], }, { id: "monad-archive", endpoint: "https://your-monad-archive-node", evm: { chainId: 143, // serves eth_queryBlocks, eth_queryTraces and eth_queryTransfers, // and any range the Goldsky upstream cannot answer queryShim: { enabled: true }, }, }, ] ``` - **Both transports:** JSON-RPC `eth_query*` and gRPC `QueryService` streams use the same upstreams and return the same MIP-16 pages. - **Range:** genesis to the chain tip. eRPC resolves `latest`, `safe` and `finalized` to block numbers before it calls the upstream. - **Without an archive node:** leave out `monad-archive`. `eth_queryBlocks`, `eth_queryTraces` and `eth_queryTransfers` then return `-32004` (method not supported). - **Edge RPC:** Goldsky Edge RPC endpoints for Monad (`https://edge.goldsky.com/standard/evm/143`) already serve all five `eth_query*` methods this way. --- # Shared state > Source: https://docs.erpc.cloud/config/database/shared-state > Give every pod in your fleet the same real-time view of each upstream's block height — routing stays consistent as you scale out, with zero added latency on the request path. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Shared state Scale eRPC horizontally and every pod independently tracks upstream block heights. Without coordination, one pod may route a request to a lagging upstream while another pod wouldn't. Shared state fixes this: a background pipeline publishes every new block observation to a common store and fans updates out to every peer, so all pods route from the same global picture. The request path never waits — reads stay in-process and the network round-trip is always off the critical path. ## Quick taste Illustrative, not a tuned production config — connect all pods to one Redis instance: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: # unique key per deployment — prevents cross-pod contamination if two clusters share one Redis clusterKey: "prod-main" connector: # redis gives sub-millisecond cross-pod propagation via pub/sub driver: redis redis: uri: "redis://:secret@redis.internal:6379/?pool_size=10" ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { // unique key per deployment — prevents cross-pod contamination if two clusters share one Redis clusterKey: "prod-main", connector: { // redis gives sub-millisecond cross-pod propagation via pub/sub driver: "redis", redis: { uri: "redis://:secret@redis.internal:6379/?pool_size=10" }, }, }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add shared state to a multi-pod deployment** ```text I'm running eRPC on multiple pods and they each independently track upstream block heights, causing inconsistent routing. Set up database.sharedState in my eRPC config using Redis so all pods share the same block-number view. Set a unique clusterKey for my deployment and leave the foreground latency defaults unless there's a strong reason to change them. Read the full reference first: https://docs.erpc.cloud/config/database/shared-state.llms.txt ``` **Prompt Example #2: tune foreground latency for co-located Redis** ```text My eRPC pods use shared state with Redis on the same host (sub-millisecond RTT). Audit my eRPC config sharedState settings — specifically updateMaxWait, lockMaxWait, fallbackTimeout, and lockTtl — and tighten the foreground latency budget without breaking the lockTtl > fallbackTimeout constraint. Reference: https://docs.erpc.cloud/config/database/shared-state.llms.txt ``` **Prompt Example #3: debug inconsistent block routing across pods** ```text Some of my eRPC pods are routing requests to lagging upstreams even though other pods see a higher block. I have sharedState configured in my eRPC config. Walk me through what Prometheus metrics and log messages to check to confirm cross-pod propagation is working, and whether my clusterKey is set correctly so pods aren't cross-contaminating each other. Reference: https://docs.erpc.cloud/config/database/shared-state.llms.txt ``` **Prompt Example #4: migrate from DynamoDB to Redis for shared state** ```text Our eRPC shared state currently uses DynamoDB and we're seeing ~5s cross-pod convergence lag. Migrate the database.sharedState connector in my eRPC config to Redis for sub-millisecond pubsub propagation. Keep the clusterKey unchanged so existing counter state is preserved at the new connector. Reference: https://docs.erpc.cloud/config/database/shared-state.llms.txt ``` **Prompt Example #5: run two independent clusters on one Redis** ```text I have a staging and a production eRPC deployment both pointing at the same Redis instance. Ensure their shared-state counters don't interfere with each other by setting distinct clusterKey values in each my eRPC config, and explain what happens if I accidentally leave both at the default. Reference: https://docs.erpc.cloud/config/database/shared-state.llms.txt ``` --- ### Shared state — full agent reference ### How it works **Registry and key space.** `NewSharedStateRegistry` wraps one `Connector` and a `clusterKey` prefix. Every counter is stored under `/` — for example `prod-main/v2/latestBlock//` (see **Counter families** below). The registry holds a `sync.Map` of live `counterInt64` instances; calling `GetCounterInt64` with the same key always returns the same object (idempotent `LoadOrStore`). On first call, two async bootstrap tasks start: one seeds the local counter with a single remote `Get`, and one calls `WatchCounterInt64` to open a long-lived change stream from the connector. **Write path.** `TryUpdate` is synchronous and local-only — it atomically advances the in-memory counter via a CAS loop and then schedules a background push without touching the network. `scheduleBackgroundPushCurrent` coalesces concurrent pushes: a single goroutine per counter (1) publishes the current state via `connector.PublishCounterInt64` for fast peer notification, (2) acquires the distributed lock within `lockMaxWait`, (3) reads remote state and adopts it if the remote value is newer, then writes local state if local is newer. If the lock cannot be acquired within `lockMaxWait`, the goroutine falls back to publish-only propagation and reschedules if another update arrived while it was running. **Foreground latency budget.** `TryUpdateIfStale` is used by the EVM state poller to debounce expensive RPC calls. It launches the upstream RPC in a background goroutine and waits at most `updateMaxWait` for the result. If the RPC finishes within that window the fresh value is returned synchronously; otherwise the stale local value is returned immediately and the RPC completes asynchronously. The foreground path never acquires the distributed lock. One caller may wait longer: a request naming the `finalized` tag at its idle edge, when fewer than the quorum's voters reported finalized within the freshness window W, waits for its finalized refresh up to W, past `updateMaxWait` (see [block tracking](/reference/evm/block-tracking.llms.txt)). **Rollback handling.** All counter updates enforce a rollback policy. `latestBlock` and `finalizedBlock` use `ignoreRollbackOf = 1024` — decreases up to 1024 blocks are silently discarded as noise from lagging upstreams; a larger gap applies only once the lower side has moved: a later reading above the first lower one, with no reading within 1024 of the counter in between (`admitLargeRollback`). A genuine deep reorg or a chain restarted lower keeps moving from its new height, so it applies at its second reading and triggers the `OnLargeRollback` callback; a provider answering now and then from a node stuck far behind repeats one value, and its readings at the real head in between clear the count, so it never applies. Lower readings alone for 5 minutes (`largeRollbackMaxHold`) also apply, so a chain that restarted lower and halted is still followed. `earliestBlock` uses `ignoreRollbackOf = 0` — all decreases are accepted because node pruning genuinely shifts the historical anchor. **Timestamp order and conflict resolution.** Each counter state is serialised as `{"v":,"t":,"b":""}`. The `t` field is the reconcile order key, by the writer's clock; it never decides freshness. `allocateUpdatedAtMs` ensures local timestamps are strictly monotonic even under concurrent goroutines (a CAS spin-loop). Head counters (`latestBlock`, `finalizedBlock`) are max-only on every path (pubsub, initial fetch, reconcile, background push): a higher remote value is taken whatever its timestamp, so a writer whose clock runs ahead cannot freeze the others; timestamps decide only drops larger than `ignoreRollbackOf`. Other counters (`earliestBlock`, cordon, SVM floors) adopt a remote state only when `st.UpdatedAt > currentTs`. When a remote update has a newer timestamp but a value that would imply a small rollback (within `ignoreRollbackOf`), `advanceTimestampPast` is called to advance the local order key past the remote's so the local (higher) value wins the next reconciliation cycle. **Transport differences by connector.** All five connectors implement the same `GetCounterInt64` / `PublishCounterInt64` / `WatchCounterInt64` interface; propagation latency differs significantly: - **Redis** — push via `PUBLISH counter:` (e.g. `counter:prod-main/v2/latestBlock//`) and subscribe via a single shared `PSubscribe("counter:*")` connection that matches all counters regardless of cluster; subscribers filter by exact key inside `runMessageLoop`. Reconnects automatically with exponential backoff (1 s → 30 s with jitter) and a 5-minute periodic poll fallback; `pollAllKeys()` is triggered after each reconnect to close the gap during the reconnection window. Subscriber channels are buffered (size 1, drop-on-full) so slow consumers never block the message loop. Source: [`data/redis_pubsub_manager.go:L155-460`](https://github.com/erpc/erpc/blob/main/data/redis_pubsub_manager.go#L155-L460), [`data/redis.go:L591`](https://github.com/erpc/erpc/blob/main/data/redis.go#L591) - **PostgreSQL** — push via `pg_notify` using a channel name derived by `sanitizeChannelName(fmt.Sprintf("counter_%s", key))` to strip characters illegal in PostgreSQL NOTIFY channel names; LISTEN-based subscription with a 30 s polling fallback. Source: [`data/postgresql.go:L620-718`](https://github.com/erpc/erpc/blob/main/data/postgresql.go#L620-L718) - **DynamoDB** — no push primitive. `PublishCounterInt64` is a documented no-op; propagation relies on polling at `statePollInterval` (default 5 s). Each poll delivers the stored state whenever it differs from the last one delivered, an older timestamp included: the counter decides. Cross-pod convergence latency is bounded by the poll interval, not a push event. Source: [`data/dynamodb.go:L715-766`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L715-L766) - **Memory** — both `WatchCounterInt64` and `PublishCounterInt64` are no-ops; in-process only, no cross-pod coordination. Source: [`data/memory.go:L195-207`](https://github.com/erpc/erpc/blob/main/data/memory.go#L195-L207) - **gRPC** — both `WatchCounterInt64` and `PublishCounterInt64` return an error; the gRPC connector cannot participate in shared state. **Deadlock-prevention invariant.** The foreground paths (`TryUpdate` and `TryUpdateIfStale`) never acquire the distributed lock. Only the background `scheduleBackgroundPushCurrent` goroutine acquires it, and only after any local update is complete. This strict lock-ordering rule was introduced to fix a deadlock where the old design could have `scheduleBackgroundPushCurrent` hold the distributed lock and wait for `updateMu`, while `TryUpdateIfStale` held `updateMu` and waited for the distributed lock. The test `TestLockOrderSimulation_OldBuggyBehavior` documents the old behavior. **Counter families.** These counters are materialised during normal operation, all stored under `/` in the backing store: 1. `v2/latestBlock/` — latest block per upstream (`ignoreRollbackOf=1024`). 2. `v2/finalizedBlock/` — finalized block per upstream (`ignoreRollbackOf=1024`). 3. `v2/earliestBlock//` — earliest available block per upstream per probe type (`ignoreRollbackOf=0`; all decreases accepted because node pruning genuinely shifts the historical anchor). 4. `v2/operatorCordon//` — operator cordon state per upstream. 5. `network///finalizedBlock` — the highest network-wide `finalized` any instance served (see [Finalized floor](/reference/evm/block-tracking.llms.txt#finalized-floor)) (`ignoreRollbackOf=1024`). `` is `common.UniqueUpstreamKey(up)`: the upstream id followed by a hash of its id, endpoint and JSON-RPC headers. It does not depend on chain detection, so it stays the same for the upstream's lifetime. Two upstreams share a key only when they call the same endpoint with the same headers, and so report the same chain. Changing an upstream's endpoint or headers starts a new counter, and so does upgrading from a version that also hashed the network id; the old keys are left behind in the store. Source: [`common/upstream.go:L68-82`](https://github.com/erpc/erpc/blob/main/common/upstream.go#L68-L82) **Instance ID.** Each counter state carries an `UpdatedBy` field (`"b"` in JSON) identifying which pod wrote it. It is resolved from the first non-empty value of: env `INSTANCE_ID` → env `POD_NAME` → env `HOSTNAME` → `os.Hostname()` → `"unknown"`. This is diagnostic-only and does not affect routing. Source: [`data/shared_state_registry.go:L82-98`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L82-L98) **SuggestLatestBlock fast path.** When the eRPC proxy observes a block number in an upstream response, it immediately calls `SuggestLatestBlock(blockNumber)` which calls `TryUpdate` if the new value is greater than the current local value. This avoids a full polling round-trip and immediately triggers background propagation, advancing the shared counter without waiting for the next polling tick. Source: [`architecture/evm/evm_state_poller.go:L459-481`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L459-L481) **IsStale semantics.** `IsStale(d)` reads this instance's clock only: it returns `true` unless the counter's report time (`ReportAt`: a local report's evidence time, a remote value's receive time) or the end of its last refresh (an answer, an error or the foreground timeout) is within `d`. It is the gate inside `TryUpdateIfStale` before attempting a refresh. Source: [`data/shared_state_variable.go:L133-141`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L133-L141) **OnValue / OnLargeRollback callbacks.** Registered at counter construction time; called synchronously from `triggerValueCallback` within both `processNewValue` (local write path) and `processNewState` (remote sync path) after a successful CAS. The EVM state poller registers `OnValue` to push the new block number into the health tracker for metrics and `OnLargeRollback` to record large rollback events. Source: [`architecture/evm/evm_state_poller.go:L126-139`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L126-L139) **Rollback write (rewind).** When the network-wide chain tracker re-anchors its pins, or moves to a lower head, each upstream whose own hash vote is on the new branch and whose latest counter is above that vote has the counter lowered to the vote's height through `EvmStatePoller.RewindLatestBlock` → `Rewind`. A rewind takes any drop, fires `OnRewind` (the health tracker's per-upstream head follows it) and then `OnValue`, never `OnLargeRollback`, takes a fresh `UpdatedAt` and is published with `"r":true`. Another instance takes a rewind-marked lower state newer than its own, without pushing back; an unmarked lower state keeps the rules above. While a counter's value comes from a drop (a large rollback or a rewind), a higher state stamped no later than the drop predates it and is rejected (`stale_timestamp`), on pubsub and in reconcile, until the counter rises again. Source: [`data/shared_state_variable.go:L637-692`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L637-L692) **Poll timeout in EVM state poller.** The state poller computes its per-tick context timeout as `lockTtl + 15s` (minimum 30 s) to allow time for acquiring the distributed lock plus network operations. Source: [`architecture/evm/evm_state_poller.go:L174-187`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L174-L187) **Bootstrap task retry.** If `WatchCounterInt64` fails at startup (connector not ready, network error), `initCounterSync` marks the watch task as failed and the `Initializer` retries it in the background. During this window the counter operates in local-only mode. Source: [`data/shared_state_registry.go:L168-222`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L168-L222) **Served tip.** Each instance computes the served tip from the shared per-upstream counters (see [Block tracking](/reference/evm/block-tracking.llms.txt)). The one network-level counter is `network///finalizedBlock`, the highest network-wide `finalized` any instance served: a floor for `finalized` only while a voter of the reading instance reports it. No served `latest` is shared. Per-group served-tip lanes are in-process, not shared state. **Fallback when absent.** `erpc/erpc.go:L49-L66` synthesises an in-memory registry if `sharedState == nil`; the same `GetCounterInt64` API works identically but no cross-pod propagation occurs. Init failures are non-fatal: `erpc/init.go` logs a warning and continues with a synthesised in-memory registry. A broken Redis config therefore produces degraded per-pod behavior, not a hard startup failure. ### Config schema All fields are under `database.sharedState` in `erpc.yaml`. The block is optional; its absence causes a silent fallback to a process-local in-memory registry. Struct at [`common/config.go:L269-286`](https://github.com/erpc/erpc/blob/main/common/config.go#L269-L286), defaults at [`common/defaults.go:L789-828`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L789-L828), validation at [`common/validation.go:L263-309`](https://github.com/erpc/erpc/blob/main/common/validation.go#L263-L309). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `database.sharedState` | `*SharedStateConfig` | `nil` | Root pointer. `nil` by default; when absent, `erpc/erpc.go:L49-L66` synthesises an identical in-memory config at runtime. The same `GetCounterInt64` API works in both cases; the only difference is no cross-pod propagation. Source: [`common/config.go:L266`](https://github.com/erpc/erpc/blob/main/common/config.go#L266), [`erpc/erpc.go:L49-66`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go#L49-L66) | | `database.sharedState.clusterKey` | `string` | Inherits top-level `clusterKey` (default `"erpc-default"`) | Prefix prepended to every counter key as `/`. Multiple logical clusters can share the same Redis/PG instance without collision. **Footgun:** all instances default to `"erpc-default"` — distinct independent deployments pointing at the same store must set distinct keys or they cross-contaminate block-number state. Source: [`common/config.go:L271`](https://github.com/erpc/erpc/blob/main/common/config.go#L271), [`common/defaults.go:L803-804`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L803-L804) | | `database.sharedState.connector` | `*ConnectorConfig` | Auto-defaulted to in-memory (`driver="memory"`) when block is present but connector is omitted | Backing store for counter persistence and pub/sub. Drivers: `memory`, `redis`, `postgresql`, `dynamodb`. **GOTCHA — id auto-assignment:** if `connector.id` is empty, shared-state scope sets it to `string(connector.driver)` (e.g. `"redis"`) at `common/defaults.go:L799-L801`, NOT `"shared-state-redis"` (the `scope+"-"+driver` pattern used by cache/auth connectors). Copying a connector block from `database.evmJsonRpcCache` into `database.sharedState` and relying on auto-assigned ids produces different ids. Always set `connector.id` explicitly. Source: [`common/defaults.go:L799-801`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L799-L801) | | `database.sharedState.fallbackTimeout` | `Duration` | `3s` | Deadline for background remote I/O (Get, Set, Publish) and the hard cap on the async-refresh helper goroutine (`fallbackTimeout + 1s`). **Does NOT bound request-path latency** — that is `updateMaxWait`. Setting this very low degrades background propagation without improving client latency. Source: [`common/defaults.go:L809-812`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L809-L812), [`data/shared_state_variable.go:L426`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L426), [`data/shared_state_variable.go:L511`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L511) | | `database.sharedState.lockTtl` | `Duration` | `4s` | Expiry of the distributed lock key in the backing store. Must exceed `fallbackTimeout` (enforced by validation) to allow one full Get+Set cycle under the lock. If the lock expires while the goroutine is still working, `Unlock` logs "lock was already expired" at DEBUG level — this is expected. Source: [`common/defaults.go:L814-817`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L814-L817), [`common/validation.go:L292-295`](https://github.com/erpc/erpc/blob/main/common/validation.go#L292-L295) | | `database.sharedState.lockMaxWait` | `Duration` | `100ms` | Maximum time the background push goroutine waits to acquire the distributed lock before giving up and relying on publish-only propagation. Never blocks the request path. Must be `> 0` and `< fallbackTimeout`. Source: [`common/defaults.go:L820-823`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L820-L823), [`common/validation.go:L298-301`](https://github.com/erpc/erpc/blob/main/common/validation.go#L298-L301) | | `database.sharedState.updateMaxWait` | `Duration` | `50ms` | **Primary foreground latency knob.** `TryUpdateIfStale` waits at most this long for the upstream RPC before returning the stale value and continuing async. Fast Redis responses (<5 ms typical) complete synchronously; slow responses are cut off. Must be `> 0` and `< fallbackTimeout`. Source: [`common/defaults.go:L824-827`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L824-L827), [`data/shared_state_variable.go:L447`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L447) | **Top-level `clusterKey`** (`common/config.go:L40`): defaults to `"erpc-default"`. Propagated to `database.sharedState.clusterKey` if that field is empty. **DynamoDB-specific `statePollInterval`** (`common/config.go:L441`): default `5s`. Controls the polling rate inside `WatchCounterInt64` since DynamoDB has no pub/sub primitive. ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Minimal Redis config with an explicit cluster key (recommended baseline).** Every production deployment sets a unique `clusterKey` so that staging and production instances sharing one Redis instance don't contaminate each other's block-number state. The explicit `connector.id` avoids the auto-assignment gotcha where shared-state connectors get `"redis"` instead of `"shared-state-redis"`: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: # unique per deployment — prevents cross-pod block-height contamination # if two clusters share the same Redis instance (e.g. prod + staging) clusterKey: "prod-us-east-1" connector: # always set id explicitly: auto-assigned id here is "redis", not "shared-state-redis" id: "shared-state-redis" driver: redis redis: uri: "\${SHARED_STATE_REDIS_URL}" ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { // unique per deployment — prevents cross-pod block-height contamination // if two clusters share the same Redis instance (e.g. prod + staging) clusterKey: "prod-us-east-1", connector: { // always set id explicitly: auto-assigned id here is "redis", not "shared-state-redis" id: "shared-state-redis", driver: "redis", redis: { uri: "\${SHARED_STATE_REDIS_URL}" }, }, }, } ``` **2. Multi-region fleet with relaxed lock and wide foreground wait.** When pods span multiple regions, the Redis round-trip from any one pod may vary. This production multi-region config raises `lockTtl` to 30 s to accommodate the longer distributed-lock cycle, sets `lockMaxWait` to 200 ms to fail fast and fall back to publish-only propagation rather than blocking, and raises `updateMaxWait` to 2 s to give the foreground refresh more time before falling through to a stale value: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: clusterKey: "fly-prod-aggregator-shard0" # long TTL covers one full Get+Set cycle at cross-region Redis latency; # must stay > fallbackTimeout (default 3s), so 30s is generous lockTtl: "30s" # fail fast on lock contention — proceed with publish-only; never block requests lockMaxWait: "200ms" # cross-region Redis RTT can be 50–200ms; give the refresh goroutine time to finish # synchronously before falling through to the stale value updateMaxWait: "2s" connector: driver: redis redis: uri: "redis://erpc-redis.internal:6379" ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { clusterKey: "fly-prod-aggregator-shard0", // long TTL covers one full Get+Set cycle at cross-region Redis latency; // must stay > fallbackTimeout (default 3s), so 30s is generous lockTtl: "30s", // fail fast on lock contention — proceed with publish-only; never block requests lockMaxWait: "200ms", // cross-region Redis RTT can be 50–200ms; give the refresh goroutine time to finish // synchronously before falling through to the stale value updateMaxWait: "2s", connector: { driver: "redis", redis: { uri: "redis://erpc-redis.internal:6379" }, }, }, } ``` **3. Same Redis, two logical clusters (staging + prod).** When you can't provision separate Redis instances, use distinct `clusterKey` values. Counter keys are prefixed with the cluster key so `staging/latestBlock/...` and `prod/latestBlock/...` never collide, even though both clusters publish to the same Redis PUBLISH channel namespace. The `fallbackTimeout` and `lockTtl` defaults are left in place since in-cluster Redis latency is well under 3 s: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml # staging erpc.yaml database: sharedState: # distinct from the production clusterKey — same Redis, no cross-contamination clusterKey: "staging" connector: driver: redis redis: uri: "\${SHARED_STATE_REDIS_URL}" --- # production erpc.yaml database: sharedState: clusterKey: "prod" connector: driver: redis redis: uri: "\${SHARED_STATE_REDIS_URL}" ``` **TypeScript — `erpc.ts`:** ```typescript // staging config database: { sharedState: { // distinct from the production clusterKey — same Redis, no cross-contamination clusterKey: "staging", connector: { driver: "redis", redis: { uri: "\${SHARED_STATE_REDIS_URL}" } }, }, }, // production config database: { sharedState: { clusterKey: "prod", connector: { driver: "redis", redis: { uri: "\${SHARED_STATE_REDIS_URL}" } }, }, }, ``` **4. DynamoDB for AWS-only deployments.** When Redis or PostgreSQL aren't available, DynamoDB is a valid fallback, but `PublishCounterInt64` is a no-op — propagation relies entirely on polling. Cross-pod convergence latency is bounded by `statePollInterval` (default 5 s) rather than a push event. Acceptable for batch indexing workloads that tolerate slightly stale block-height views, but not recommended for latency-sensitive RPC fleets: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: clusterKey: "prod-main" connector: driver: dynamodb dynamodb: region: "us-east-1" table: "erpc-shared-state" # DynamoDB has no pub/sub — all propagation is via polling; # lower values cost more DynamoDB read capacity; default 5s is the floor statePollInterval: 5s ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { clusterKey: "prod-main", connector: { driver: "dynamodb", dynamodb: { region: "us-east-1", table: "erpc-shared-state", // DynamoDB has no pub/sub — all propagation is via polling; // lower values cost more DynamoDB read capacity; default 5s is the floor statePollInterval: "5s", }, }, }, } ``` **5. No shared state (single-pod or dev).** Omitting the block entirely gives you a silent per-process in-memory registry — no config needed, same API, no cross-pod propagation: ```yaml # No database.sharedState block — eRPC synthesises an in-memory registry automatically database: {} ``` ### Request/response behavior The shared-state layer has no effect on JSON-RPC request or response shapes visible to clients. Its impact is routing-internal: - **Block-number reads** (`latestBlock`, `finalizedBlock`) used by the upstream selector and tag-aware routing come from the in-process atomic copy — zero latency on the request path. - **Served-finalized counter** (`network///finalizedBlock`) is raised when an instance computes a higher network-wide `finalized`; the head computation reads the in-process copy and never waits on the store. Other instances serve it only within `maxRegressionBlocks` of their own tip and while one of their own voters reports it finalized, so a value no voter backs is ignored. Only raises are published. - **Block-number refreshes** are debounced via `TryUpdateIfStale`; the foreground caller waits at most `updateMaxWait` (default 50 ms). If the refresh completes within that window the fresh value influences the current request; otherwise the stale value is used and the refresh completes asynchronously for the next request. A `finalized`-tag request at its idle edge is the exception: it waits for the finalized refresh up to W. - A broken or unreachable shared-state connector degrades to per-pod local state — no error is returned to the client; routing quality degrades silently. - **Operator cordons** (`erpc_cordonUpstream`) are one more shared counter per upstream (`operatorCordon`, value = cordon time in unix-ms, `0` = lifted), with the same propagation, bootstrap fetch and local-first semantics as the block counters. See [Cordoning](/operation/cordoning.llms.txt). ### Best practices - Always set a **unique `clusterKey`** per logical deployment (e.g. `"prod-v2"`, `"staging"`). The default `"erpc-default"` is shared by every unconfigured instance pointing at the same store — cross-contamination breaks block-height monotonicity. - Always set **`connector.id` explicitly** (`id: "shared-state-redis"`). The auto-assigned id for shared-state connectors is `string(driver)` (e.g. `"redis"`), not the `"shared-state-redis"` pattern used by cache connectors — copying connector blocks between scopes silently changes the id. - Prefer **Redis or PostgreSQL** over DynamoDB for shared state. DynamoDB has no pub/sub; convergence latency is 5 s by default vs. milliseconds for Redis pubsub. - Do not set **`fallbackTimeout` low** to try to speed up request latency — `fallbackTimeout` governs background I/O only. The foreground latency knob is `updateMaxWait`. - Keep **`lockTtl > fallbackTimeout`** (the default 4 s > 3 s relationship). Validation enforces this, but understand it: `lockTtl` must be long enough for one full Get+Set cycle under the lock. - In AWS deployments with Redis, set **`pool_size`** in the Redis URI (`?pool_size=10`) to avoid connection exhaustion under bursty background push traffic. - Monitor `erpc_upstream_block_head_large_rollback` in production. A sustained non-zero value means an upstream is experiencing genuine reorgs or provider resets — something worth routing around. A provider flapping between a healthy node and one stuck far behind no longer sets it: its drops never apply. ### Edge cases & gotchas 1. **`Value=0` is valid, `UpdatedAt=0` is not.** Genesis block (`earliestBlock=0`) is a legitimate counter value. Uninitialised state is signalled by `UpdatedAt <= 0`, never by `Value == 0`. Source: [`data/connector.go:L32-34`](https://github.com/erpc/erpc/blob/main/data/connector.go#L32-L34) 2. **Stale lock expiry is silent.** If a remote operation takes longer than `lockTtl`, the lock key expires. `Unlock` returns "lock was already expired" logged at DEBUG — expected and benign. Setting `lockTtl < fallbackTimeout` is rejected by validation to prevent this in every call. Source: [`common/validation.go:L292-295`](https://github.com/erpc/erpc/blob/main/common/validation.go#L292-L295) 3. **Remote-ahead adoption happens in background.** A fresh pod can have its local counter bumped forward by a peer before the pod's first RPC poll completes. Source: [`data/shared_state_variable.go:L686-691`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L686-L691) 4. **Small-rollback rejection advances local timestamp.** When a remote update has a newer `UpdatedAt` but a value within the rollback threshold, `advanceTimestampPast` is called to ensure the local (higher) value wins the next reconciliation. Source: [`data/shared_state_variable.go:L211-218`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L211-L218) 5. **`TryUpdate` must not acquire `updateMu`.** Holding `updateMu` during `TryUpdate` would block a concurrent `TryUpdateIfStale` caller already holding the mutex that could in turn wait for background operations — a classic deadlock. The old design had this bug; test `TestLockOrderSimulation_OldBuggyBehavior` documents it. Source: [`data/shared_state_variable_deadlock_test.go:L95-212`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable_deadlock_test.go#L95-L212) 6. **`continueAsyncRefresh` goroutine leak protection.** If the downstream RPC ignores its context and never returns, a bounded timer of `fallbackTimeout + 1s` kills the helper. Source: [`data/shared_state_variable.go:L511`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L511) 7. **Double-checked staleness.** `TryUpdateIfStale` checks `IsStale` before and after acquiring `updateMu` to prevent a thundering herd where N goroutines all see stale and all fire a refresh after the first one already updated the value. Source: [`data/shared_state_variable.go:L399-413`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L399-L413) 8. **Redis pubsub channel buffered=1, drop-on-full.** If the registry consumer falls behind, messages are silently dropped. The 5-minute periodic `pollingLoop` is the recovery path. Source: [`data/redis_pubsub_manager.go:L450-457`](https://github.com/erpc/erpc/blob/main/data/redis_pubsub_manager.go#L450-L457) 9. **DynamoDB `PublishCounterInt64` is a no-op.** Cross-pod latency is bounded by `statePollInterval` (default 5 s). Using DynamoDB means significantly higher convergence latency than Redis or PostgreSQL. Source: [`data/dynamodb.go:L825-829`](https://github.com/erpc/erpc/blob/main/data/dynamodb.go#L825-L829) 10. **`WatchCounterInt64` channel closed on shutdown.** `RedisPubSubManager.stop()` closes all subscriber channels on app shutdown; the registry goroutine observing the channel receives `ok=false` and marks the watch task as failed. This is benign since the app context is also cancelled at that point. Source: [`data/shared_state_registry.go:L200-207`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L200-L207) 11. **`clusterKey` propagation order.** Explicit `database.sharedState.clusterKey` wins over the inherited top-level `clusterKey`. Source: [`common/defaults.go:L803-805`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L803-L805) 12. **The served tip is per instance.** Pods compute it from the same shared per-upstream heads; nothing about the pick itself is stored. Source: [`erpc/networks.go:L55-78`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L55-L78) 13. **init.go treats shared-state failure as a warning, not fatal.** A broken Redis config produces degraded per-pod behavior, not a hard startup failure. Source: [`erpc/init.go:L93-97`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L93-L97) 14. **`database.sharedState` nil means `SetDefaults` is never called on it.** The synthesised config at `erpc/erpc.go:L49-L66` exists only in local scope and does not write back to `cfg.Database.SharedState`. Source: [`common/defaults.go:L837-840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L837-L840) 15. **Connector `id` auto-assignment differs between shared-state and other scopes.** Shared-state connector id defaults to `string(driver)` (e.g. `"redis"`), not `"shared-state-redis"`. Source: [`common/defaults.go:L799-801`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L799-L801) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_latest_block_number` | Gauge | `project`, `vendor`, `network`, `upstream` | On every `OnValue` callback from `latestBlockShared` counter via `tracker.SetLatestBlockNumber` | | `erpc_upstream_finalized_block_number` | Gauge | `project`, `vendor`, `network`, `upstream` | On every `OnValue` callback from `finalizedBlockShared` counter via `tracker.SetFinalizedBlockNumber` | | `erpc_upstream_latest_block_polled_total` | Counter | `project`, `vendor`, `network`, `upstream` | Each time `PollLatestBlockNumber` issues an actual RPC call (not debounced by `TryUpdateIfStale`) | | `erpc_upstream_finalized_block_polled_total` | Counter | `project`, `vendor`, `network`, `upstream` | Each time `PollFinalizedBlockNumber` issues an actual RPC call | | `erpc_upstream_block_head_large_rollback` | Gauge | `project`, `vendor`, `network`, `upstream`, `finality` | On `OnLargeRollback` callback; value is the rollback size in blocks. `finality` is the head axis that rolled back (`latest` or `finalized`), not a `DataFinalityState`. Sticky: never reset, so it holds the last rollback size for the life of the process | | `erpc_shared_counter_remote_rejected_total` | Counter | `reason` | A remote counter state this instance rejected: `non_positive` (0 or less on a head counter), `small_rollback` (a drop within `ignoreRollbackOf`), `held_rollback` (a larger drop held until its lower side moves), `stale_timestamp` (an older large drop on a head counter, any older change on the others), `malformed` (a parse error or `t<=0` at a connector or the initial fetch, once per distinct payload in a row per key; a record with no value is missing, not malformed) | | `erpc_unexpected_panic_total` | Counter | `component`, `context`, `fingerprint` | On panic recovery inside `initCounterSync` (`component="shared-state-counter-sync"`), `messageLoop` (`component="redis-pubsub-message-loop"`), or `pollingLoop` (`component="redis-pubsub-polling-loop"`) | **OTel trace spans:** - `CounterInt64.TryUpdate` — every foreground local-update call; attributes: `key`, `new_value` (when detailed tracing enabled). - `CounterInt64.TryUpdateIfStale` — attributes: `key`, `staleness_ms`, `skipped_not_stale`, `skipped_not_stale_after_mutex`, `role`, `result_path` (`got_result` vs `timeout`), `async_refresh`, `foreground_remote_io_disabled`. - `CounterInt64.TryUpdateIfStale.AcquireMutex` — measures mutex wait time inside `TryUpdateIfStale`. - `CounterInt64.TryUpdateIfStale.ExecuteRefresh` — spans the actual RPC call inside the refresh goroutine; attribute `timeout_ms`. - `RedisConnector.PublishCounterInt64` — spans each publish call; attributes `key`, `value`, `updated_at`, `updated_by` (when detailed tracing enabled). - `PostgreSQLConnector.PublishCounterInt64` — same pattern as Redis span above. **Key log messages** (component `sharedState`): - `"no remote initial value found for counter"` (DEBUG) — normal first-run; counter seeds from zero. - `"fetched initial value for counter"` (DEBUG) — successful seed from remote on first bootstrap. - `"received new value from shared state sync"` (DEBUG) — pubsub/watch update received and processed. - `"failed to setup counter sync"` (ERROR) — watch setup failed; will retry via initializer. - `"lock held by another instance, proceeding with local lock"` (DEBUG) — normal under load; background push proceeds without distributed lock. - `"lock acquisition timed out waiting for other instance"` (WARN) — lock contention above `lockMaxWait`; falling back to publish-only propagation. - `"lock expired during operations (expected behavior)"` (DEBUG) — expected when operations take near `lockTtl`. - `"published counter value to remote"` (DEBUG) — successful remote publish. - `"pubsub reconnected successfully"` (INFO) — Redis pubsub recovery. - `"counter value increased (remote)"` (TRACE) — value advanced by remote pubsub event. - `"small rollback ignored (remote)"` (TRACE) — rollback inside threshold, discarded. - `"large rollback applied (remote)"` (TRACE) — real reorg or provider reset accepted. - `"large rollback held until the lower head moves (remote)"` / `(local)` (DEBUG) — a drop beyond the threshold waits for a second, higher reading. ### Source code entry points - [`data/shared_state_registry.go:L38-L80`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L38-L80) — `NewSharedStateRegistry`: registry construction, `clusterKey` prefix, `sync.Map` of live counters - [`data/shared_state_variable.go:L364-L707`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go#L364-L707) — `TryUpdate`, `TryUpdateIfStale`, `scheduleBackgroundPushCurrent`, lock ordering, rollback handling, timestamp CAS helpers - [`data/shared_state_registry.go:L102-L222`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L102-L222) — `GetCounterInt64`: idempotent counter creation, bootstrap tasks, `WatchCounterInt64` goroutine - [`data/redis_pubsub_manager.go:L155-L460`](https://github.com/erpc/erpc/blob/main/data/redis_pubsub_manager.go#L155-L460) — `RedisPubSubManager`: single `PSubscribe("counter:*")`, reconnect backoff, periodic poll fallback, copy-on-write subscriber slice - [`erpc/erpc.go:L49-L66`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go#L49-L66) — in-memory fallback synthesis when `sharedState == nil` - [`common/defaults.go:L789-L828`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L789-L828) — `SharedStateConfig.SetDefaults`; all default values including connector id override - [`data/shared_state_sources.go`](https://github.com/erpc/erpc/blob/main/data/shared_state_sources.go) — named constants for the `source` field in logs and traces (`UpdateSourceRemoteSync`, `UpdateSourceTryUpdate`, etc.) - [`data/shared_state_variable_deadlock_test.go:L95-L212`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable_deadlock_test.go#L95-L212) — lock-ordering correctness tests ### Related pages - [Connectors](/config/database.llms.txt) — the backing store options (Redis, PostgreSQL, DynamoDB, memory) that power shared state. - [Tag-aware routing](/config/projects/selection-policies.llms.txt) — `use-upstream` selectors scope the served tip to the matched upstreams; no shared counter is involved. - [EVM state poller](/reference/evm.llms.txt) — the consumer that calls `TryUpdateIfStale` per upstream; registers `OnValue`/`OnLargeRollback` callbacks. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — routing quality under failover depends on consistent block-height awareness across pods. - [Deployment](/deployment.llms.txt) — horizontal scaling guidance where shared state becomes necessary. --- --- # SVM JSON-RPC cache > Source: https://docs.erpc.cloud/config/database/svm-json-rpc-cache > Cache Solana JSON-RPC responses without ever serving a stale account balance — eRPC classifies every SVM read by Solana's own commitment rules, keys base58 params case-sensitively, and refuses to treat a moving rooted head as immutable. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # SVM JSON-RPC cache Solana's `finalized` commitment is **not** an immutability guarantee — it is the state at the latest *rooted* slot, and that slot advances roughly every 400 ms. A cache that reads "finalized" as "safe forever" will happily serve a two-hour-old `getBalance` result. eRPC's SVM cache is built around that single fact: only responses pinned to a specific past slot or signature are cached as immutable; everything that tracks the rooted head is treated as realtime and bounded by a TTL. **What you get** - Finality classification that follows Solana commitment semantics, not EVM block-depth semantics - Case-preserving cache keys — two base58 pubkeys differing only in letter case never collide - Effectful and sub-slot methods (`sendTransaction`, `requestAirdrop`, `getLatestBlockhash`, …) hard-excluded from both reads and writes, regardless of policy - The same connectors, policies, and zstd compression as the EVM cache, on a disjoint key namespace ## Quick taste Illustrative, not a tuned production config — cache slot-pinned finalized reads forever, everything else briefly: **Config path:** `database.svmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: svmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 100000 } policies: # getBlock / getTransaction at commitment:finalized are pinned to a slot # that is already rooted — genuinely immutable, safe to keep forever. - connector: mem network: "*" method: "*" finality: finalized ttl: 0 # Everything else tracks the rooted head. TTL is the ONLY staleness bound. # Object form tracks observed slot time; scalar "2s" is a fixed alternative. - connector: mem network: "*" method: "*" finality: realtime ttl: { blockTimeMultiplier: 1, fallback: 200ms } ``` **TypeScript — `erpc.ts`:** ```typescript database: { svmJsonRpcCache: { connectors: [{ id: "mem", driver: "memory", memory: { maxItems: 100000 } }], policies: [ // getBlock / getTransaction at commitment:finalized are pinned to a slot // that is already rooted — genuinely immutable, safe to keep forever. { connector: "mem", network: "*", method: "*", finality: "finalized", ttl: 0 }, // Everything else tracks the rooted head. TTL is the ONLY staleness bound. // Object form tracks observed slot time; scalar "2s" is a fixed alternative. { connector: "mem", network: "*", method: "*", finality: "realtime", ttl: { blockTimeMultiplier: 1, fallback: "200ms" } }, ], }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up SVM caching from scratch** ```text I want to cache Solana JSON-RPC responses in eRPC. Add a database.svmJsonRpcCache block with an in-memory connector and one policy per finality bucket (finalized, unfinalized, realtime), with TTLs that respect Solana commitment semantics — remember that commitment:finalized state reads are moving-head, not immutable. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/database/svm-json-rpc-cache.llms.txt ``` **Prompt Example #2: explain why getBalance is never cached permanently** ```text My eRPC SVM cache has a catch-all policy with finality: finalized and ttl: 0, but getBalance and getAccountInfo requests still hit upstreams every time even when I pass commitment: finalized. Explain the finality classification eRPC applies to SVM methods and tell me which policies I am missing. Reference: https://docs.erpc.cloud/config/database/svm-json-rpc-cache.llms.txt ``` **Prompt Example #3: share one Redis backend between EVM and SVM networks** ```text I run both EVM and SVM networks in one eRPC project and want a single Redis connector behind both caches without key collisions. Set up database.evmJsonRpcCache and database.svmJsonRpcCache pointing at the same Redis connector definition and explain why the keyspaces stay disjoint. Reference: https://docs.erpc.cloud/config/database/svm-json-rpc-cache.llms.txt ``` **Prompt Example #4: cache large getBlock payloads without blowing up storage** ```text Solana getBlock responses in my deployment are multiple megabytes. Configure database.svmJsonRpcCache so finalized getBlock/getTransaction results are cached permanently in Redis with zstd compression, and add a size limit so pathological responses are skipped rather than stored. Reference: https://docs.erpc.cloud/config/database/svm-json-rpc-cache.llms.txt ``` --- ### SVM JSON-RPC cache — full agent reference ### How it works **Separate config block, shared machinery.** SVM caching is configured under `database.svmJsonRpcCache` and takes the *same* `CacheConfig` schema as [`database.evmJsonRpcCache`](/config/database/evm-json-rpc-cache.llms.txt) — identical `connectors`, `policies`, and `compression` sub-blocks, identical [drivers](/config/database/drivers.llms.txt). The two blocks are independent: an EVM-only config is unaffected, and an SVM network with no `svmJsonRpcCache` block simply never caches. `SvmJsonRpcCache` implements the same `common.CacheDAL` interface as its EVM counterpart, so the network layer calls it through the same seam. **Key namespaces are disjoint by construction.** The partition key is prefixed with the network id (`svm:mainnet-beta`, `svm:fogo:mainnet`, `evm:1`), so pointing both caches at one Redis or DynamoDB connector is safe and is the intended deployment for mixed projects. **Finality classification — the load-bearing part.** `GetFinality` resolves an SVM request to a `DataFinalityState` in four ordered steps: | Step | Predicate | Result | |---|---|---| | 1 | `neverCacheMethods` | `realtime` — *and* hard-skipped by the cache layer | | 2 | `alwaysFinalizedMethods` | `finalized` (immutable by construction) | | 3 | `slotPinnedMethods` **and** effective commitment is `finalized` | `finalized` | | 4 | `slotPinnedMethods` at any weaker commitment | `unfinalized` | | 5 | everything else | `realtime` (moving-head read) | Step 5 is the rule that matters, and it is why step 3 needs an explicit table at all. **`commitment: finalized` on Solana means "the state at the latest ROOTED slot", and the rooted slot advances roughly every 400 ms — it is a moving head, not an immutability promise.** `getAccountInfo` and `getProgramAccounts` at `finalized` therefore answer a *different question every slot*, exactly like EVM's `latest` block tag. Classifying them `finalized` would be a permanent-cache bug: `finalized` is the zero value of the Go enum that a policy with no explicit `finality` matches, and an unset TTL means "no expiry" in every connector — so a later transfer would never invalidate the cached account. Direct balance reads (`getBalance`, `getTokenAccountBalance`) take that one step further: they are in `neverCacheMethods` and hard-skipped before any policy runs, so a realtime TTL cannot cache them either. Only a response pinned to an explicit positional identifier — a slot number or a transaction signature — is genuinely immutable once that slot is rooted. That is the whole content of `slotPinnedMethods`: ``` slotPinnedMethods = getBlock, getTransaction ``` At `finalized` these are promoted to `finalized`. Below `finalized` they are `unfinalized`: still pinned to a slot, but a not-yet-rooted slot can be dropped by a minority-fork switch, so the answer can still change. ``` alwaysFinalizedMethods = getInflationReward (defined only over finalized epochs) getBlockTime (takes no commitment param; stable once the slot exists) ``` ``` neverCacheMethods = sendTransaction, sendRawTransaction, simulateTransaction, requestAirdrop, getLatestBlockhash, getRecentBlockhash, getFeeForMessage, getSignatureStatuses, getVoteAccounts, getLeaderSchedule, getEpochInfo, getSlotLeaders, getRecentPerformanceSamples, getRecentPrioritizationFees, getBalance, getTokenAccountBalance ``` Three categories live in `neverCacheMethods`: **mutating or effectful** calls, where caching would break the at-least-once semantics callers expect; **transient realtime snapshots** that go stale in under one slot; and **direct balance reads** (`getBalance`, `getTokenAccountBalance`) that feed financial decisions and must never return a stale value. `getEpochSchedule` is deliberately *excluded* — its constants only change at epoch boundaries (~432,000 slots), so it falls through to the moving-head bucket and is cached under the realtime policy's TTL. **Never-cache is hard-enforced, not policy-driven.** `realtime` is still a *cacheable* finality at the policy layer, so mapping these methods to `realtime` is not sufficient on its own. `Get` and `Set` both check `neverCacheMethods` **before** policy matching and return early. An operator's stray `finality: realtime` catch-all therefore cannot cache `sendTransaction`. **Finality reflects the commitment eRPC pinned.** Step 3 calls `resolveCommitment` — the same predicate the [commitment-injection hook](/reference/svm/commitment.llms.txt) uses — so classification tracks the level eRPC actually pinned on the request, not the level a node happens to default to. When nothing is pinned (no caller `commitment`, no `svm.commitment`, or injection legitimately skips the legacy encoding-string form), the response is classified `unfinalized`. That is deliberately stricter than the routing predicate `IsFinalizedCommitment`, which follows the node's documented `finalized` default: cache permanence is a one-way door — `finality: finalized` is the zero value an unset-TTL policy matches, so a wrong promotion pins a value forever while a wrong demotion costs one re-fetch. Set `svm.commitment` to have unpinned slot-addressed reads cached as final. **Cache-key derivation.** Two keys, as in EVM, but both dimensions differ: - **Partition key: `:`, or `::` when `networks[].cacheKeySuffix` is set.** `slotRef` is the request's `minContextSlot` when one is present in any object param, otherwise the literal `"*"`. This replaces EVM's `blockRef` dimension. Because `slotRef` is derived purely from the request params, a given `(method, params)` tuple always produces the same partition key on both `Set` and `Get` — so SVM always reads `ConnectorMainIndex` and never needs EVM's reverse-index wildcard fallback. When `:` is itself a valid network id (`svm:` plus a suffix), colons in the network id are escaped (`svm\:mainnet-beta:systx:*`) so the partition is not the unsuffixed key of that longer id. Unsuffixed keys are unchanged. - **Request key: `:`.** Derived by `svmRequestKey`, **not** by the shared `req.CacheHash()`. **Cache keys are case-preserving, and this is a correctness requirement.** The shared EVM hasher lowercases every string param, which is the right normalization for hex but catastrophic for Solana: base58 pubkeys and transaction signatures are **case-sensitive**, so two distinct valid accounts differing only by letter case would collapse onto one key and be served each other's data. `svmRequestKey` preserves case exactly. It marshals params with `encoding/json` (not sonic) on purpose — the standard library documents that it sorts map keys, which is what makes the key deterministic across runs and across Go map iteration order, and its grammar is both type- and structure-delimiting, so `"abc"`, `["a","bc"]`, and `{"a":"bc"}` cannot collide, nor can the number `1` and the string `"1"`. The method name is both hashed and prefixed, so a method name containing `:` cannot forge another method's key. Params `nil` and `params: []` normalize to the same key. **No block-timestamp age guard.** EVM re-checks a realtime hit's block timestamp against the policy TTL before accepting it. SVM has no equivalent: because only genuinely immutable responses are classified `finalized`, the **connector storage TTL on the realtime policy is the staleness bound** — the same lever EVM uses for `latest`. That TTL may be a fixed duration or derived from the network's slot-time EMA via `ttl: { blockTimeMultiplier, fallback }` (see config schema). There is consequently no `erpc_cache_get_age_guard_reject_total` traffic on SVM networks. **Get is sequential, not a parallel fan-out.** `Get` walks the matched policies in list order and returns the first non-empty hit; there is no goroutine race, no `fanCtx`, and no peer cancellation. **Order your policies fastest-connector-first** — with SVM this is not a tie-break hint, it is the actual probe order. `Set` likewise writes to matched connectors sequentially. **Writes.** Responses carrying a JSON-RPC `error` body are never stored. Size limits gate on the **original** (uncompressed) payload — they express a response-size ceiling, not a storage-footprint one. zstd compression runs at most once per request and only after some policy has accepted the payload, so a multi-megabyte `getBlock` that every policy rejects on size never pays for compression. **Compression.** Identical to the EVM cache: enabled by default (the `compression` block is auto-created even when omitted), `threshold` default 1024 bytes, and detection on read is by the zstd magic bytes `0x28 0xB5 0x2F 0xFD` — so entries written while compression was enabled stay readable after it is turned off. Solana `getBlock` payloads routinely exceed a megabyte, so leaving compression on is the right default. ### Config schema All fields live under `database.svmJsonRpcCache` and use the **same `CacheConfig` schema as `database.evmJsonRpcCache`** — see the [EVM cache page's config schema](/config/database/evm-json-rpc-cache.llms.txt) for the full field-by-field tables of `connectors[*]`, `policies[*]`, and `compression`. Only the SVM-specific semantics are restated here. | Field | Type | Default | SVM-specific behavior | |---|---|---|---| | `database.svmJsonRpcCache` | `*CacheConfig` | `nil` (no SVM caching) | Independent of `evmJsonRpcCache`. Validated at startup; a broken block fails config validation rather than silently disabling the cache. | | `cachingStrategy` | `'defaultAllow' \| 'defaultIgnore'` | `defaultAllow` (omit → same) | Same write-side admission as the EVM cache (`strategy ×` response mark). See [EVM cache `cachingStrategy`](/config/database/evm-json-rpc-cache.llms.txt). | | `policies[*].finality` | enum | `finalized` (Go zero value) | `finalized` matches only `getBlock`/`getTransaction` at commitment `finalized`, plus `getInflationReward`/`getBlockTime`. **Every other SVM read is `realtime`.** | | `policies[*].ttl` | Duration \| `{ blockTimeMultiplier, fallback }` | `0` (no expiry) | On a `realtime` SVM policy this is the *only* staleness bound — there is no block-timestamp age guard. Scalar form is a fixed storage TTL. Object form resolves storage TTL as `slotTimeEMA × blockTimeMultiplier` once the tracker has warmed (≥3 samples from accepted head advances: wall-clock Δ / slot gap); until then `fallback` applies, or a built-in **200ms** cold-start default when `fallback` is omitted (Alpenglow ~200ms slot target; EVM's analogous default remains 2s). Metric labels always use the fixed/`fallback` component so cardinality stays stable. `blockTimeMultiplier` is validated only on `finality: realtime`. | | `policies[*].network` | string | `"*"` | Matches the SVM network id: `svm:` or `svm::`. | | `policies[*].method` | string | `"*"` | Matches Solana method names (`getBlock`, `getAccountInfo`, …). Methods in `neverCacheMethods` are excluded before matching and cannot be re-enabled by any policy. | ### Worked examples **1. The three-bucket baseline.** `finalized` for the two slot-pinned reads, `unfinalized` for those same reads below `finalized` commitment, and `realtime` for everything else. Without the `realtime` policy the overwhelming majority of SVM traffic — every account and token read — bypasses the cache entirely: **Config path:** `database.svmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: svmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 500000, maxTotalSize: 4GB } policies: # Immutable: getBlock/getTransaction pinned to a rooted slot, plus # getBlockTime and getInflationReward. - connector: mem network: "*" method: "*" finality: finalized ttl: 0 # getBlock/getTransaction at confirmed/processed — pinned to a slot, but a # fork switch can still drop it. ~2 slots of tolerance. - connector: mem network: "*" method: "*" finality: unfinalized ttl: 800ms # Everything else: getAccountInfo, getProgramAccounts, getSlot, # getBlockHeight, getSignaturesForAddress, ... all moving-head reads. # (getBalance / getTokenAccountBalance are neverCacheMethods — hard-skipped.) - connector: mem network: "*" method: "*" finality: realtime ttl: 2s ``` **TypeScript — `erpc.ts`:** ```typescript database: { svmJsonRpcCache: { connectors: [{ id: "mem", driver: "memory", memory: { maxItems: 500000, maxTotalSize: "4GB" } }], policies: [ // Immutable: getBlock/getTransaction pinned to a rooted slot, plus // getBlockTime and getInflationReward. { connector: "mem", network: "*", method: "*", finality: "finalized", ttl: 0 }, // getBlock/getTransaction at confirmed/processed — pinned to a slot, but a // fork switch can still drop it. ~2 slots of tolerance. { connector: "mem", network: "*", method: "*", finality: "unfinalized", ttl: "800ms" }, // Everything else: getAccountInfo, getProgramAccounts, getSlot, // getBlockHeight, getSignaturesForAddress, ... all moving-head reads. // (getBalance / getTokenAccountBalance are neverCacheMethods — hard-skipped.) { connector: "mem", network: "*", method: "*", finality: "realtime", ttl: "2s" }, ], }, } ``` **2. Two tiers: memory in front, Redis for the immutable pool.** Historical `getBlock`/`getTransaction` results are large, read repeatedly, and never change once rooted — they belong in a durable shared tier that survives restarts. Moving-head reads have a 2 s lifetime and never justify a network round-trip. Note that SVM probes policies **in list order**, so the memory connector must come first: **Config path:** `database.svmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: svmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 200000, maxTotalSize: 2GB } - id: redis driver: redis redis: uri: "redis://\${REDIS_HOST}:6379/0" policies: # Memory FIRST: Get walks policies in order and returns the first hit — # unlike EVM there is no parallel race, so order IS the probe order. - connector: mem network: "*" method: "getBlock|getTransaction" finality: finalized ttl: 0 - connector: redis network: "*" method: "getBlock|getTransaction" finality: finalized # Durable and permanent: a rooted slot's block never changes. ttl: 0 # Moving-head reads stay local — a Redis RTT costs more than the upstream # call it would save at a 2s TTL. - connector: mem network: "*" method: "*" finality: realtime ttl: 2s ``` **TypeScript — `erpc.ts`:** ```typescript database: { svmJsonRpcCache: { connectors: [ { id: "mem", driver: "memory", memory: { maxItems: 200000, maxTotalSize: "2GB" } }, { id: "redis", driver: "redis", redis: { uri: "redis://\${REDIS_HOST}:6379/0" } }, ], policies: [ // Memory FIRST: Get walks policies in order and returns the first hit — // unlike EVM there is no parallel race, so order IS the probe order. { connector: "mem", network: "*", method: "getBlock|getTransaction", finality: "finalized", ttl: 0 }, { connector: "redis", network: "*", method: "getBlock|getTransaction", finality: "finalized", // Durable and permanent: a rooted slot's block never changes. ttl: 0, }, // Moving-head reads stay local — a Redis RTT costs more than the upstream // call it would save at a 2s TTL. { connector: "mem", network: "*", method: "*", finality: "realtime", ttl: "2s" }, ], }, } ``` **3. One Redis backend behind both architectures.** A mixed EVM + SVM project can share storage. The network-id prefix on every partition key (`evm:1:…` vs `svm:mainnet-beta:…`) keeps the namespaces disjoint, so no coordination is needed beyond declaring the connector in both blocks: **Config path:** `database` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: redis driver: redis redis: uri: "redis://\${REDIS_HOST}:6379/0" policies: - connector: redis network: "*" method: "*" finality: finalized ttl: 0 svmJsonRpcCache: # Same physical Redis. Partition keys are prefixed with the network id, so # evm:1 and svm:mainnet-beta entries cannot collide. connectors: - id: redis driver: redis redis: uri: "redis://\${REDIS_HOST}:6379/0" policies: - connector: redis network: "*" method: "getBlock|getTransaction" finality: finalized ttl: 0 ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "redis", driver: "redis", redis: { uri: "redis://\${REDIS_HOST}:6379/0" } }], policies: [{ connector: "redis", network: "*", method: "*", finality: "finalized", ttl: 0 }], }, svmJsonRpcCache: { // Same physical Redis. Partition keys are prefixed with the network id, so // evm:1 and svm:mainnet-beta entries cannot collide. connectors: [{ id: "redis", driver: "redis", redis: { uri: "redis://\${REDIS_HOST}:6379/0" } }], policies: [{ connector: "redis", network: "*", method: "getBlock|getTransaction", finality: "finalized", ttl: 0 }], }, } ``` **4. Slot-partitioned caching for monotonic readers.** Clients that pass `minContextSlot` to enforce read-your-writes get a partition key per slot floor, so a request at `minContextSlot: N` never reads an entry stored for a different floor. This is a natural fit for indexers that advance a cursor; it also means a client that varies `minContextSlot` on every call gets a fresh partition every time and effectively bypasses the cache: **Config path:** `database.svmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: svmJsonRpcCache: connectors: - id: mem driver: memory memory: { maxItems: 1000000, maxTotalSize: 4GB } policies: - connector: mem network: "svm:mainnet-beta" method: "*" finality: realtime # High item count: a distinct minContextSlot value means a distinct # partition key, so key cardinality scales with distinct slot floors. ttl: 2s ``` **TypeScript — `erpc.ts`:** ```typescript database: { svmJsonRpcCache: { connectors: [{ id: "mem", driver: "memory", memory: { maxItems: 1000000, maxTotalSize: "4GB" } }], policies: [{ connector: "mem", network: "svm:mainnet-beta", method: "*", finality: "realtime", // High item count: a distinct minContextSlot value means a distinct // partition key, so key cardinality scales with distinct slot floors. ttl: "2s", }], }, } ``` ### Request/response behavior - **Cache key structure.** Partition key `:`, or `::` when `networks[].cacheKeySuffix` is set. `:` and `\` inside `slotRef` are backslash-escaped; other values, including `"*"`, are stored as-is. When `:` is itself a valid network id, colons in the network id are escaped instead. `slotRef` is the request's `minContextSlot` or `"*"`. Request key `:`, case-preserving. Always read from `ConnectorMainIndex` — no reverse index. - **`neverCacheMethods` short-circuit both directions.** `Get` returns a miss and `Set` returns without writing, before any policy is consulted. - **Responses with a JSON-RPC `error` field are never cached.** Native Solana error codes and `error.data` are preserved to the client instead — see the [error reference](/reference/errors.llms.txt#svm-solana-error-contract). - **A `getSlot` response is corrected after the cache read.** The post-forward hook enforces the highest known slot for the request's commitment even on a cache hit, so a cached value can never make the slot number appear to move backwards. See [slot tracking](/reference/svm/slot-tracking.llms.txt). - **No realtime age gate.** A `realtime` hit is accepted on connector TTL alone. There is no block-timestamp cross-check and no `ttl_rejected` outcome on SVM. When `ttl` uses `blockTimeMultiplier`, `Set` stores with the resolved slot-time TTL (or cold-start fallback); `Get` still trusts connector expiry. - **`X-ERPC-Skip-Cache-Read`** works identically to EVM — `"true"` skips every connector, a glob pattern skips matching connector ids. ### Best practices - **Always define a `realtime` policy.** It is not an edge case on SVM — it is the majority of your traffic. `getAccountInfo`, `getProgramAccounts`, `getSlot`, `getBlockHeight`, and `getSignaturesForAddress` are all `realtime` at *every* commitment level, including `finalized`. (`getBalance` / `getTokenAccountBalance` are hard-skipped via `neverCacheMethods` and never match a policy.) A config with only a `finality: finalized` policy caches almost nothing. - **Never "fix" a low hit rate by forcing state reads to `finalized`.** There is no config knob to do this on SVM, and that is deliberate — it would be a permanent-cache correctness bug, not a tuning win. If you need higher hit rates on account reads, raise the `realtime` TTL knowingly. - **Prefer `ttl: { blockTimeMultiplier: 1, fallback: 200ms }` for realtime** when you want storage expiry to track observed slot time (including as slot cadence changes). Once warm, multiplier `1` is roughly one slot of head staleness (~200ms under Alpenglow; historically ~400ms) — expect a lower realtime hit rate than a fixed multi-second TTL and watch upstream load on soak. Raise the multiplier or set a wider `fallback` if callers need a longer cold-start window. Omitting `fallback` uses the built-in 200ms cold-start default. Second-granularity connectors (e.g. DynamoDB) quantize sub-second TTLs to whole seconds. - **Set `unfinalized` TTL to roughly two slots (≈800 ms).** That bucket only ever holds `getBlock`/`getTransaction` below `finalized` commitment, where a fork switch is the risk being bounded. - **Order policies fastest-connector-first.** SVM's `Get` is a sequential walk, so a slow remote connector listed before a local memory connector adds its full latency to every hit. - **Leave compression enabled.** `getBlock` payloads regularly exceed a megabyte; zstd at the default threshold pays for itself immediately. - **Point EVM and SVM at the same connector definitions** in a mixed project. The keyspaces cannot collide, and one storage tier is one thing to operate. ### Edge cases & gotchas 1. **`finality: finalized` is the Go zero value — omitting `finality` creates a finalized-only policy.** On SVM this is far more surprising than on EVM, because the `finalized` bucket holds only four methods (`getBlock`, `getTransaction` at `finalized` commitment, plus `getInflationReward` and `getBlockTime`). A catch-all policy with no explicit `finality` will look like the cache is broken. 2. **`commitment: finalized` does not promote a state read.** `getBalance(pubkey, {commitment: "finalized"})` is `realtime`, by design. Solana `finalized` is the latest *rooted* slot — a head that moves every ~400 ms — so the answer changes continuously. 3. **`minContextSlot` is not a promotion signal either.** Per the Solana RPC reference it is the minimum bank slot at which the request may be *evaluated* — a node-freshness floor, not a lower bound on returned history. `getBalance(pubkey, {minContextSlot: 1})` still answers at the current head. It affects the cache *partition key* only. 4. **Cache keys are case-sensitive.** This is the opposite of the EVM cache, which lowercases string params. Base58 is case-significant, so `getAccountInfo("Abc…")` and `getAccountInfo("abc…")` are different accounts and get different keys. Do not normalize pubkey case in a client layer expecting eRPC to fold it. 5. **`getSignaturesForAddress` is `realtime`, deliberately.** The signature list for an address *grows* as new transactions land, so it tracks the head even though it names an address rather than a slot. 6. **`getBlocks` / `getBlocksWithLimit` are `realtime`, and a fully-historical range is not promoted.** `getBlocks(start)` with no end slot runs to the current head, and either form can name an upper bound the chain has not reached yet. A fully-in-the-past range *is* immutable and only gets realtime-TTL caching here; promoting it would make finality depend on mutable poller state and therefore vary over time for an identical request. `getBlocks` is cheap next to `getBlock`. 7. **`getEpochInfo` is never cached but `getEpochSchedule` is.** `getEpochInfo` carries the live slot index; `getEpochSchedule` returns epoch constants that change only at epoch boundaries. 8. **`getBlockTime` is treated as final by construction.** A slot's timestamp can in principle change if a not-yet-rooted slot is dropped. This is a low-risk simplification, not a guarantee. 9. **A `realtime` policy cannot resurrect a `neverCacheMethods` entry.** The hard skip runs before policy matching in both `Get` and `Set`. 10. **`params: null` and `params: []` share one key.** They are the same call; the encoder normalizes them so `json.Marshal` cannot emit `null` for one and `[]` for the other. 11. **No per-connector write timeout.** Unlike the EVM cache's hard 5 s `Set` ceiling, SVM `Set` relies on the connector's own configuration and the request context. Configure `failsafeForSets` on the connector if you need a bound. 12. **Constructor failures are downgraded to a warning at startup.** `erpc/init.go` logs a WARN and continues if `NewSvmJsonRpcCache` fails, which would leave the cache silently absent — this is exactly why the config block is schema-validated eagerly at startup instead. 13. **Same-chain networks share partition keys unless `cacheKeySuffix` is set.** Same rule as EVM: empty suffix keeps `:`. A `:` or `\` inside `slotRef` (a string `minContextSlot` is passed through) is backslash-escaped so the key cannot collide with another suffix split. A suffix on `svm:` would otherwise spell the unsuffixed key of `svm::`, which is a valid network id, so that case escapes the network id's colons (`svm\:::`). A suffix on `svm::` cannot spell a network id, and keeps `::`. Source: [`architecture/svm/json_rpc_cache.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/json_rpc_cache.go), [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go). 14. **Upgrading the partition encoding does not remove collided entries.** Previously, `svm:foo` with suffix `bar` and unsuffixed `svm:foo:bar` both used `svm:foo:bar:`. The new suffixed key changes, but the unsuffixed reader still accepts old entries, including responses from the other network. If these networks shared a cache, stop all old-version writers before purging the affected partitions from every configured cache connector. Alternatively, move both networks to clean, isolated namespaces. Do not resume affected cache reads until cleanup or isolation is complete. A rolling upgrade or suffixed-cache refill alone is insufficient. 15. **`policies[*].ttl.blockTimeMultiplier` is a no-op until the slot-time EMA warms.** The SVM state poller does not have on-chain slot timestamps; the tracker feeds the EMA from wall-clock Δ divided by the accepted slot gap on corroborated head advances. Until ≥3 samples land, `ResolveTTL` uses `ttl.fallback` (or the built-in 200ms cold-start default). Empty polls and non-advancing tips do not sample — that is intentional so poller cadence is not mistaken for chain production rate. 16. **Warming `GetNetworkBlockTime` for `svm:*` is shared, not cache-only.** This change reuses the existing EMA rather than a parallel SVM TTL stack, so other consumers that already call `GetNetworkBlockTime` / `EvmBlockTime` leave their cold path once the estimate warms: failsafe block-unavailable retry delay becomes `slotTime × BlockUnavailableDelayMultiplier` (default multiplier `1.0`; overrides a static `emptyResultDelay` when the dynamic provider returns non-zero), selection-policy `*LagSeconds` thresholds start converting head/finalization lag into wall time, and `maxRetryableBlockDistance`'s derived floor can widen from the slot-time horizon. This PR only starts feeding the estimate those paths already read. ### Observability The SVM cache emits the **same `erpc_cache_*` metric family** as the EVM cache, so existing dashboards work unchanged. The `network` label distinguishes SVM traffic (`svm:mainnet-beta`, …). | Metric | Type | When it fires | |---|---|---| | `erpc_cache_get_success_hit_total` | counter | A policy returned a non-empty stored value | | `erpc_cache_get_success_miss_total` | counter | Every matched policy missed | | `erpc_cache_get_skipped_total` | counter | No policy matched the request's network/method/finality | | `erpc_cache_get_error_total` | counter | A connector `Get` errored; the walk continues to the next policy | | `erpc_cache_set_success_total` | counter | A connector `Set` succeeded | | `erpc_cache_set_skipped_total` | counter | Payload rejected by a policy's size limits | | `erpc_cache_set_error_total` | counter | A connector `Set` errored (logged at WARN, swallowed) | | `erpc_cache_set_original_bytes_total` / `erpc_cache_set_compressed_bytes_total` | counter | Pre- and post-zstd payload accounting; the compressed counter only advances when compression actually shrank the value | | `erpc_cache_get_success_hit_duration_seconds` / `erpc_cache_get_success_miss_duration_seconds` / `erpc_cache_set_success_duration_seconds` / `erpc_cache_set_error_duration_seconds` | histogram | Hit, miss, successful-set, and failed-set latency | | `erpc_network_dynamic_block_time_milliseconds` | gauge | Tracker EMA slot/block time for the network (`project`, `network` labels). Zero/absent until ≥3 samples; this is the input `ResolveTTL` multiplies when `policies[*].ttl.blockTimeMultiplier` is set. | Use the `*_total` **counters** (not duration histograms) for hit/miss rates. `neverCacheMethods` short-circuits stay silent — they are not cache skips and do not inflate skipped counters. **Notably absent on SVM:** `erpc_cache_get_age_guard_reject_total` never fires — there is no block-timestamp age gate. **Debug/warn logs:** `"svm cache get failed; trying next policy"` (DEBUG, per-policy connector error) and `"svm cache set failed"` (WARN, carries `groupKey` and `requestKey`). ### Source code entry points - [`architecture/svm/json_rpc_cache.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/json_rpc_cache.go) — `SvmJsonRpcCache`: `Get`/`Set`, `generateKeys`, `svmRequestKey` (case-preserving hashing), `extractSlotRef`, zstd compress/decompress, `doGet` main-index rationale. - [`architecture/svm/finality.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/finality.go) — `GetFinality`, `neverCacheMethods`, `alwaysFinalizedMethods`, `slotPinnedMethods`, `IsFinalizedCommitment`, and the moving-head rationale in full. - [`common/config.go — DatabaseConfig.SvmJsonRpcCache`](https://github.com/erpc/erpc/blob/main/common/config.go#L273-L275) - [`common/validation.go — eager svmJsonRpcCache validation`](https://github.com/erpc/erpc/blob/main/common/validation.go#L258-L266) ### Related pages - [EVM JSON-RPC cache](/config/database/evm-json-rpc-cache.llms.txt) — the shared `CacheConfig` schema in full: connectors, policies, compression, size limits. - [Storage connectors](/config/database/drivers.llms.txt) — memory, Redis, DynamoDB, PostgreSQL driver options. - [SVM commitment & finality](/reference/svm/commitment.llms.txt) — how the effective commitment is resolved and injected. - [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) — the state poller, `getSlot` correction, and ingestion-lag cordoning. - [Networks](/config/projects/networks.llms.txt) — declaring an SVM network and its `svm.*` options. - [Error taxonomy](/reference/errors.llms.txt#svm-solana-error-contract) — the SVM error contract and missing-data family. --- --- # Example config > Source: https://docs.erpc.cloud/config/example > A production-ready starting point you can copy today, plus a complete annotated reference of every config section — caching, failover, hedging, rate limits, and observability included. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Example config A production-ready starting point you can copy today, and a complete annotated reference below it. The recommended config turns on what makes eRPC worth running — multi-provider failover, hedging, permanent caching, observability — with sane values you'd actually deploy; delete what you don't need and defaults fill the gaps. ## Recommended starting point Copy, set two API keys, done. Each block's comment says what power it buys you: **Config path:** `(root)` **YAML — `erpc.yaml`:** ```yaml logLevel: info # Observability on from day one: Prometheus on :4001/metrics metrics: enabled: true port: 4001 # Permanent cache: finalized chain data never changes, so never pay for it twice. # Start in-process; uncomment redis to share the cache across replicas. database: evmJsonRpcCache: connectors: - id: hot driver: memory # - id: shared # driver: redis # redis: { addr: redis:6379 } policies: - connector: hot finality: finalized # immutable: cached forever - connector: hot finality: unfinalized ttl: 5s # fresh data: short-lived cache # A reusable budget so no single consumer can starve the rest rateLimiters: budgets: - id: frontend-budget rules: - method: "*" maxCount: 500 period: 1s projects: - id: main rateLimitBudget: frontend-budget # Uncomment to require an API key (see /config/auth for JWT, SIWE, IP rules) # auth: # strategies: # - type: secret # secret: { value: \${MY_API_KEY} } # One key per vendor unlocks every chain they support — upstreams appear # lazily on first request per chain providers: - endpoint: alchemy://\${ALCHEMY_API_KEY} - endpoint: drpc://\${DRPC_API_KEY} upstreams: # Mix in your own node; selection scoring decides who deserves traffic - endpoint: https://your-node.example.com/ evm: { chainId: 1 } # Free public RPC as last resort: the tier:fallback tag keeps it out of # rotation until paid upstreams are unhealthy - endpoint: https://ethereum-rpc.publicnode.com evm: { chainId: 1 } tags: ["tier:fallback"] # Resilience defaults for every chain: bounded latency, automatic # failover, and hedged slow-tails networkDefaults: failsafe: - matchMethod: "*" timeout: duration: 30s # nothing hangs longer than this retry: maxAttempts: 3 # errors fail over across upstreams hedge: # race a backup at the p70 latency mark delay: { quantile: 0.7, min: 100ms, max: 2s } maxCount: 1 # Per-upstream safety net: bench repeat offenders, probe recovery upstreamDefaults: failsafe: - matchMethod: "*" retry: maxAttempts: 1 circuitBreaker: failureThresholdCount: 20 failureThresholdCapacity: 80 halfOpenAfter: 5m successThresholdCount: 8 networks: - architecture: evm evm: { chainId: 1 } alias: ethereum # /main/ethereum instead of /main/evm/1 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ logLevel: "info", // Observability on from day one: Prometheus on :4001/metrics metrics: { enabled: true, port: 4001 }, // Permanent cache: finalized chain data never changes, so never pay for it // twice. Start in-process; add a redis connector to share across replicas. database: { evmJsonRpcCache: { connectors: [ { id: "hot", driver: "memory" }, // { id: "shared", driver: "redis", redis: { addr: "redis:6379" } }, ], policies: [ // immutable: cached forever { connector: "hot", finality: "finalized" }, // fresh data: short-lived cache { connector: "hot", finality: "unfinalized", ttl: "5s" }, ], }, }, // A reusable budget so no single consumer can starve the rest rateLimiters: { budgets: [{ id: "frontend-budget", rules: [{ method: "*", maxCount: 500, period: "1s" }], }], }, projects: [{ id: "main", rateLimitBudget: "frontend-budget", // Uncomment to require an API key (see /config/auth for JWT, SIWE, IP rules) // auth: { // strategies: [{ type: "secret", secret: { value: process.env.MY_API_KEY } }], // }, // One key per vendor unlocks every chain they support — upstreams appear // lazily on first request per chain providers: [ { endpoint: \`alchemy://\${process.env.ALCHEMY_API_KEY}\` }, { endpoint: \`drpc://\${process.env.DRPC_API_KEY}\` }, ], upstreams: [ // Mix in your own node; selection scoring decides who deserves traffic { endpoint: "https://your-node.example.com/", evm: { chainId: 1 } }, // Free public RPC as last resort: the tier:fallback tag keeps it out of // rotation until paid upstreams are unhealthy { endpoint: "https://ethereum-rpc.publicnode.com", evm: { chainId: 1 }, tags: ["tier:fallback"], }, ], // Resilience defaults for every chain: bounded latency, automatic // failover, and hedged slow-tails networkDefaults: { failsafe: [{ matchMethod: "*", timeout: { duration: "30s" }, retry: { maxAttempts: 3 }, hedge: { delay: { quantile: 0.7, min: "100ms", max: "2s" }, maxCount: 1 }, }], }, // Per-upstream safety net: bench repeat offenders, probe recovery upstreamDefaults: { failsafe: [{ matchMethod: "*", retry: { maxAttempts: 1 }, circuitBreaker: { failureThresholdCount: 20, failureThresholdCapacity: 80, halfOpenAfter: "5m", successThresholdCount: 8, }, }], }, networks: [{ architecture: "evm", evm: { chainId: 1 }, alias: "ethereum", // /main/ethereum instead of /main/evm/1 }], }], }); ``` What this gives you out of the box: every chain your vendors support via one endpoint, permanent caching of immutable data, p99-taming hedges, automatic failover with a circuit-breaker safety net, a fallback tier that only activates when paid upstreams fail, and metrics from request one. The [default selection policy](/config/projects/selection-policies.llms.txt) needs no configuration — it already excludes unhealthy upstreams and honors the `tier:fallback` tag. ## Complete example — all sections The annotated example below mirrors `erpc.dist.yaml` and `erpc.dist.ts` from the repo root. Read the inline comments for the reasoning behind each value; detailed field references live in the per-section docs linked at the bottom. **Config path:** `logLevel, server, metrics, database, projects, rateLimiters` **YAML — `erpc.yaml`:** ```yaml # ── Global ─────────────────────────────────────────────────────────────── # trace|debug|info|warn|error. Override at runtime with LOG_LEVEL env var. # Set LOG_WRITER=console for human-readable output instead of JSON. logLevel: warn # ── Cache database ──────────────────────────────────────────────────────── # eRPC supports memory, Redis, PostgreSQL, and DynamoDB/ScyllaDB connectors. # Cache reads/writes are non-blocking — a miss or write failure never delays # the upstream request. Disable entirely with: evmJsonRpcCache: ~ database: evmJsonRpcCache: connectors: - id: memory-cache driver: memory # memory.maxItems / maxTotalSize default to 100 000 / "1GB". # Omit sub-block to accept defaults. - id: redis-cache driver: redis redis: addr: redis://localhost:6379 - id: postgres-cache driver: postgresql postgresql: connectionUri: "postgres://erpc:erpc@localhost:5432/erpc" - id: scylladb-cache driver: dynamodb dynamodb: region: DC1 # ScyllaDB Alternator endpoint endpoint: http://localhost:8067 # Policies are evaluated in order; first match per (network, method, # finality) triple wins. Use finality tiers to route short-lived data # to fast/volatile stores and permanently-final data to cheaper storage. policies: - network: "*" method: "*" # block-tip / pending data — short TTL, fast store finality: realtime empty: allow connector: memory-cache ttl: 2s - network: "*" method: "*" # confirmed but not irreversible finality: unfinalized empty: allow connector: redis-cache ttl: 10s - network: "*" method: "*" # irreversible; ttl: 0 = never expires finality: finalized empty: allow connector: scylladb-cache ttl: 0 # ── HTTP server ─────────────────────────────────────────────────────────── server: httpHostV4: "0.0.0.0" httpPortV4: 4000 # listenV6: false # httpHostV6: "[::]" # httpPortV6: 5000 # Hard deadline for the full request lifecycle (all retries + hedges). # Must be non-zero. Should be >= sum of upstream retry delays + hedge delay. maxTimeout: 50s # TLS termination — leave commented unless doing edge termination on eRPC. # tls: # enabled: true # certFile: "/path/to/cert.pem" # keyFile: "/path/to/key.pem" # ── Prometheus metrics ──────────────────────────────────────────────────── metrics: enabled: true hostV4: "0.0.0.0" port: 4001 # ── Projects ────────────────────────────────────────────────────────────── # Each project maps to a URL prefix: //evm/ # Multiple projects let you apply different auth, rate limits, or failsafe # policies to different caller populations (frontend vs. indexer, etc.). projects: - id: main # Health-tracker rolling window. Per-upstream rolling counters # (errorRate, p50/p70/p95 latency, throttledRate, misbehaviorRate) # are kept as a 10-bucket ring spanning this duration; one bucket # rotates out every windowSize/10. Defaults to 1m when omitted; # widen if your aggregate RPS is low enough that 1m gives a noisy score. scoreMetricsWindowSize: 10s upstreamDefaults: evm: # State-poller cadence — hits eth_blockNumber + eth_syncing on this # interval even for excluded upstreams, so health metrics stay fresh. # Keep this <= scoreMetricsWindowSize. statePollerInterval: 2s # ── Networks ──────────────────────────────────────────────────────── # Network entries are optional. Omit them to use global defaults. # Define them to override failsafe, integrity, or selection policy # on a per-chain basis. networks: - architecture: evm evm: chainId: 1 # failsafe[] is an ordered list of policies matched in order. # Each policy applies to requests whose method AND finality match. # The first matching policy wins. failsafe: timeout: duration: 30s retry: maxAttempts: 3 delay: 500ms backoffMaxDelay: 10s backoffFactor: 0.3 jitter: 500ms # Hedge fires a parallel request to a second upstream after # "delay" if the first hasn't responded. Returns whichever wins. # Strongly recommended — dramatically cuts tail latency. hedge: delay: 3000ms maxCount: 2 - architecture: evm evm: chainId: 42161 failsafe: timeout: duration: 30s retry: maxAttempts: 5 delay: 500ms backoffMaxDelay: 10s backoffFactor: 0.3 jitter: 200ms hedge: delay: 1000ms maxCount: 2 # ── Upstreams ──────────────────────────────────────────────────────── # Vendor shorthand endpoints (alchemy://, tenderly://, etc.) are # converted to providers at startup; they cover multiple chains # automatically using the vendor's chain registry. # Raw HTTPS endpoints require evm.chainId to skip auto-detection. upstreams: - id: alchemy-multi-chain endpoint: alchemy://\${ALCHEMY_API_KEY} rateLimitBudget: global failsafe: timeout: duration: 15s retry: maxAttempts: 2 delay: 1000ms backoffMaxDelay: 10s backoffFactor: 0.3 jitter: 500ms - id: tenderly-eth endpoint: tenderly://\${TENDERLY_API_KEY} rateLimitBudget: global-tenderly evm: chainId: 1 failsafe: timeout: duration: 15s - id: blastapi-arb type: evm endpoint: https://arbitrum-one.blastapi.io/\${BLASTAPI_KEY} rateLimitBudget: global-blast evm: chainId: 42161 # ignoreMethods filters methods never sent to this upstream. # allowMethods is an allowlist (implicitly adds ignoreMethods: ["*"]). ignoreMethods: - "alchemy_*" # Enable batching when the upstream supports it. jsonRpc: supportsBatch: true batchMaxSize: 10 batchMaxWait: 100ms failsafe: timeout: duration: 15s retry: maxAttempts: 2 delay: 1000ms backoffMaxDelay: 10s backoffFactor: 0.3 jitter: 500ms - id: quicknode-arb type: evm endpoint: https://\${QUICKNODE_SUBDOMAIN}.arbitrum-mainnet.quiknode.pro/\${QUICKNODE_KEY}/ rateLimitBudget: global-quicknode evm: chainId: 42161 # autoIgnoreUnsupportedMethods tracks methods this upstream rejects # and skips them in future requests. Caution: some vendors return # inconsistent "unsupported" signals — can cause false positives. autoIgnoreUnsupportedMethods: true failsafe: timeout: duration: 15s retry: maxAttempts: 2 delay: 1000ms # ── Rate limiters ───────────────────────────────────────────────────────── # Budgets are shared — if two upstreams both reference "global", their # combined traffic counts against the limit. # Rules are evaluated in order; first matching method wins per budget. rateLimiters: budgets: - id: global-tenderly rules: - method: '*' maxCount: 10000 period: 1s - id: global-blast rules: - method: '*' maxCount: 1000 period: 1s - id: global-quicknode rules: - method: '*' maxCount: 300 period: 1s - id: global rules: - method: '*' maxCount: 10000 period: 1s # waitTime: 0 = reject immediately when budget exhausted; # set to e.g. 50ms to absorb brief bursts waitTime: 0 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig, DataFinalityStateFinalized, DataFinalityStateRealtime, DataFinalityStateUnfinalized, } from "@erpc-cloud/config"; // TypeScript configs use process.env.VAR — NOT \${VAR} shell substitution. // The Go loader reads env vars via os.Environ() before running this file. export default createConfig({ logLevel: "trace", database: { evmJsonRpcCache: { connectors: [ { id: "default-memory", driver: "memory", memory: { maxItems: 100000, maxTotalSize: "1GB", }, }, ], policies: [ { connector: "default-memory", network: "*", method: "*", finality: DataFinalityStateUnfinalized, ttl: "10s", }, { connector: "default-memory", network: "*", method: "*", finality: DataFinalityStateFinalized, ttl: "0s", }, ], }, }, server: { listenV4: true, httpHostV4: "0.0.0.0", // also accepted; resolves to httpPortV4 httpPort: 4000, maxTimeout: "50s", }, metrics: { enabled: true, hostV4: "0.0.0.0", port: 4001, }, projects: [ { id: "main", scoreMetricsWindowSize: "10s", upstreamDefaults: { evm: { statePollerInterval: "2s" }, }, networks: [ { architecture: "evm", evm: { chainId: 1 }, // Ordered failsafe list: first matching (method + finality) wins. failsafe: [ { matchMethod: "*", matchFinality: [DataFinalityStateRealtime], timeout: { duration: "3s" }, retry: { maxAttempts: 2 }, }, { matchMethod: "eth_getLogs", timeout: { duration: "5s" }, retry: { maxAttempts: 5 }, }, { matchMethod: "*", timeout: { duration: "10s" }, retry: { maxAttempts: 3 }, hedge: { delay: "3000ms", maxCount: 2 }, }, ], }, ], upstreams: [ { endpoint: \`alchemy://\${process.env.ALCHEMY_API_KEY}\`, rateLimitBudget: "global", failsafe: [ { matchMethod: "*", timeout: { duration: "15s" }, retry: { maxAttempts: 2, delay: "1000ms" }, }, ], }, { endpoint: \`chainstack://\${process.env.CHAINSTACK_API_KEY}\`, failsafe: [ { matchMethod: "*", timeout: { duration: "15s" } }, ], }, { // Raw URL upstream — chainId prevents auto-detection round trip. id: "my-own-node", type: "evm", endpoint: process.env.CUSTOM_RPC_1 ?? "", evm: { chainId: 1 }, failsafe: [ { matchMethod: "*", timeout: { duration: "15s" } }, ], }, ], }, ], rateLimiters: { budgets: [ { id: "global", rules: [{ method: "*", maxCount: 10000, period: "1s" }], }, ], }, }); ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up eRPC from scratch** ```text I want to set up eRPC for the first time with two providers (Alchemy and a raw HTTPS node), Redis caching, and basic failsafe policies. Use the full config example as a starting shape and trim it to what I actually need. My config will live at my eRPC config. Read the reference first: https://docs.erpc.cloud/config/example.llms.txt ``` **Prompt Example #2: validate and debug my config** ```text Run erpc validate on my eRPC config and explain every error or warning. Then use erpc dump to show me what defaults got filled in automatically, and flag anything that looks wrong — especially rate-limit budgets, maxTimeout vs retry sums, and env-var substitution pitfalls. Reference: https://docs.erpc.cloud/config/example.llms.txt ``` **Prompt Example #3: migrate my config from YAML to TypeScript** ```text Migrate my eRPC config from YAML to TypeScript so I get IDE autocompletion and type-checking. Preserve every field exactly, replace \${VAR} shell substitutions with process.env.VAR template literals, keep the default export as the last statement, and confirm the result passes erpc validate. Reference: https://docs.erpc.cloud/config/example.llms.txt ``` **Prompt Example #4: debug endpoints resolving to alchemy://undefined** ```text My eRPC TypeScript config is generating endpoint strings like alchemy://undefined at runtime. Explain why YAML-style \${VAR} expansion does not apply to TypeScript files and fix my config to use process.env correctly. Reference: https://docs.erpc.cloud/config/example.llms.txt ``` **Prompt Example #5: wire erpc validate and erpc dump into CI** ```text Add erpc validate --format json and erpc dump steps to my CI pipeline so config errors fail the build before deploy. Show how to pipe validate output through jq to surface only errors, and use erpc dump to confirm the effective failsafe defaults my config produces. Reference: https://docs.erpc.cloud/config/example.llms.txt ``` --- ### Full config example — agent navigation reference This page is intentionally a flat annotated example. Every section has a dedicated reference page with complete field tables and behavioral invariants. Use the map below to find the right page for any config question. ### How it works **Config file discovery.** When no `--config` flag is given, eRPC probes these paths in order and uses the first it finds ([`cmd/erpc/main.go:L279-L293`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L293)): 1. `./erpc.yaml` — relative to the working directory 2. `./erpc.yml` 3. `./erpc.ts` 4. `./erpc.js` 5. `/erpc.yaml`, `/erpc.yml`, `/erpc.ts`, `/erpc.js` 6. `/root/erpc.yaml`, `/root/erpc.yml`, `/root/erpc.ts`, `/root/erpc.js` YAML is probed before TypeScript in the same directory — a stale `erpc.yaml` silently shadows a newly added `erpc.ts`. If nothing is found and `--require-config` is unset, eRPC starts with a synthetic `main` project using public endpoints. A `.env` file in the working directory is loaded automatically before config parsing via `github.com/joho/godotenv` ([`cmd/erpc/main.go:L42-L46`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L42-L46)). Variables from `.env` are available as `${VAR}` in YAML and as `process.env.VAR` in TypeScript. **YAML loading.** `os.ExpandEnv` runs on the raw file bytes before YAML parsing ([`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102)). Every `$VAR` and `${VAR}` pattern is substituted. Unset variables resolve to the empty string. If the substituted value contains YAML-special characters (`:`, `{`…) and the field is unquoted, the parse will fail — always quote values that may contain secrets: `password: "${REDIS_PASSWORD}"`. **TypeScript loading.** Shell-style expansion is never applied. The TS file is compiled by embedded esbuild and run in a sobek JS runtime where `process.env` is pre-populated from `os.Environ()`. Use JS template literals: `` `alchemy://${process.env.ALCHEMY_API_KEY}` ``. Writing `${VAR}` in a TS string literal without `process.env.` evaluates the JS variable `VAR`, which is `undefined` unless declared — resulting in the string `"undefined"` and a confusing downstream error. **Validate and dump commands.** ```bash # Validate config without starting — exits 1 if errors found erpc validate --config erpc.yaml erpc validate --config erpc.ts --format md # Dump the effective config as eRPC will see it (defaults filled in) erpc dump --config erpc.ts erpc dump --config erpc.yaml --format json ``` `validate` builds the full resource tree (projects → networks → upstreams, rate-limit budgets), checks for orphaned budgets and public endpoints, and prints a structured JSON or Markdown report. Exit 0 if `errors` is empty. All zerolog output is suppressed during validate — pipe stdout through `jq .errors` to see only errors ([`cmd/erpc/main.go:L109`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L109)). `dump` resolves the effective selection policies (including TypeScript `evalFunc` sentinels back to their source) and prints the complete config as YAML or JSON. **Defaults cascade.** `SetDefaults` fills every nil/zero field after decode — no field is silently undefined at runtime. If `projects` is empty after loading, a synthetic `main` project with a `repository` provider is injected automatically. [`common/defaults.go:L49-176`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49-L176) ### Per-section documentation map | Config section | Canonical page | Key topics | |---|---|---| | `logLevel`, `clusterKey`, CLI flags, env vars | Config formats (this page, agent panel below) | YAML vs TS loading, discovery order, `validate`/`dump` subcommands | | `server` | [Server](/config/server.llms.txt) | HTTP/gRPC listen, TLS, timeouts, graceful shutdown, response headers | | `metrics` | [Monitoring](/operation/monitoring.llms.txt) | All 122 Prometheus metrics, histogram bucket config, cardinality controls | | `database.evmJsonRpcCache` | [Cache policies](/config/database/evm-json-rpc-cache.llms.txt) | Finality tiers, TTL semantics, `empty` behavior, policy ordering | | `database.evmJsonRpcCache.connectors` | [Storage drivers](/config/database/drivers.llms.txt) | memory, Redis, PostgreSQL, DynamoDB/ScyllaDB connector fields | | `database.sharedState` | [Shared state](/config/database/shared-state.llms.txt) | Distributed lock, consensus state, cluster key scoping | | `projects[].networks[]` | [Networks](/config/projects/networks.llms.txt) | Per-chain failsafe, integrity checks, block tracking | | `projects[].upstreams[]` | [Upstreams](/config/projects/upstreams.llms.txt) | RPC lifecycle, batching, method filtering, vendor shorthands | | `projects[].providers[]` | [Providers & vendors](/config/projects/providers.llms.txt) | Vendor key-based auto-fan-out, `onlyNetworks`/`ignoreNetworks` | | `projects[].auth` | [Authentication](/config/auth.llms.txt) | secret, JWT, SIWE, network strategies | | `projects[].cors` | [CORS](/config/projects/cors.llms.txt) | `allowedOrigins`, credentials, preflight | | `projects[].selectionPolicy` | [Selection & scoring](/config/projects/selection-policies.llms.txt) | evalFunc, score multipliers, exclusion thresholds | | `projects[].networks[].failsafe[].timeout` | [Timeout](/config/failsafe/timeout.llms.txt) | Hard deadline fields, interaction with retries | | `projects[].networks[].failsafe[].retry` | [Retry](/config/failsafe/retry.llms.txt) | Backoff, jitter, retryable error classes | | `projects[].networks[].failsafe[].hedge` | [Hedge](/config/failsafe/hedge.llms.txt) | Adaptive vs static delay, maxCount, write-method exclusion | | `projects[].networks[].failsafe[].circuitBreaker` | [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) | Half-open, thresholds, interaction with selection policy | | `projects[].networks[].failsafe[].consensus` | [Consensus](/config/failsafe/consensus.llms.txt) | DVN/quorum, dispute log, low-participant behavior | | `projects[].networks[].failsafe[].integrity` | [Integrity](/config/failsafe/integrity.llms.txt) | Block-finality enforcement, re-query on mismatch | | `rateLimiters.budgets[]` | [Rate limiters](/config/rate-limiters.llms.txt) | Shared budgets, `waitTime`, per-method rules | | `proxyPools[]` | [HTTP client & proxy pools](/reference/http-client.llms.txt) | Proxy routing, pool sizing | | `tracing` | [Tracing & logging](/operation/tracing.llms.txt) | OTel, sampleRate, endpoint, log formats | | `admin` | [Admin API](/operation/admin.llms.txt) | Cordon, drain, live config inspection | | `healthCheck` | [Healthcheck](/operation/healthcheck.llms.txt) | Mode, `defaultEval`, upstream requirements | ### Config loading invariants - Strict YAML mode (`KnownFields: true`) — any unknown key is a fatal error. [`common/config.go:L103`](https://github.com/erpc/erpc/blob/main/common/config.go#L103) - `os.ExpandEnv` runs on raw YAML bytes before parse; never applied to TypeScript files. [`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) - `SetDefaults` fills every nil/zero field after decode — no field is silently undefined at runtime. [`common/defaults.go:L49-176`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49-L176) - `Validate` runs after `SetDefaults` and returns an error if any invariant is violated; `erpc validate` exposes the full report. [`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15) - TypeScript configs are bundled by embedded esbuild (no Node.js required) and evaluated in sobek; `process.env` is pre-populated from `os.Environ()`. [`common/config.go:L2686`](https://github.com/erpc/erpc/blob/main/common/config.go#L2686) - If `projects` is empty after loading, a synthetic `main` project with a `repository` provider is injected automatically. [`common/defaults.go:L100-167`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L167) ### Worked examples **1. Validate before deploying.** Run the validate subcommand against any format to catch typos, orphaned rate-limit budgets, and reference errors before the server starts: ```bash erpc validate --config erpc.yaml # exits 0 if errors: [] — pipe through jq .errors to see just the problems erpc validate --config erpc.ts --format md ``` **2. Debug what defaults fill in.** Use `dump` to see the exact effective config the engine will run with — especially useful for TypeScript configs where `evalFunc` sentinels can be resolved back to source: ```bash erpc dump --config erpc.ts erpc dump --config erpc.yaml --format json | jq '.projects[0].networks' ``` **3. Start with CLI flags, no config file.** Pass one or more `--endpoint` flags to inject synthetic upstreams into a default `main` project — useful for quick smoke tests: ```bash erpc --endpoint https://eth.llamarpc.com --endpoint alchemy://$ALCHEMY_KEY ``` **4. Per-finality failsafe in TypeScript.** The TS dist example shows how to use `matchFinality` to give realtime (block-tip) requests a short timeout and retry budget while giving archival calls more headroom: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" matchFinality: realtime timeout: duration: 3s retry: maxAttempts: 2 - matchMethod: "*" timeout: duration: 30s retry: maxAttempts: 5 hedge: delay: 1000ms maxCount: 2 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "*", matchFinality: [DataFinalityStateRealtime], timeout: { duration: "3s" }, retry: { maxAttempts: 2 }, }, { matchMethod: "*", timeout: { duration: "30s" }, retry: { maxAttempts: 5 }, hedge: { delay: "1000ms", maxCount: 2 }, }, ] ``` ### Best practices - **Set `server.maxTimeout` ≥ total retry budget + hedge delay.** If `maxTimeout: 10s` but retries sum to 15s, the server deadline fires first and silently cuts retries short. Use `erpc dump` to verify the sum. - **Always quote YAML values that expand env vars containing special characters.** `connectionUri: "${DATABASE_URL}"` — unquoted `${DATABASE_URL}` breaks YAML parsing when the URL contains `:` or `{`. - **Never use `${VAR}` syntax in TypeScript configs.** Use `` `alchemy://${process.env.ALCHEMY_API_KEY}` `` — omitting `process.env.` gives the string `"alchemy://undefined"` and a confusing validation failure. - **Use `ttl: 0` only for `finality: finalized` data.** Setting `ttl: 0` on `realtime` or `unfinalized` policies means stale pending-transaction states are cached forever. Short TTLs (2s–10s) are correct for non-final data. - **Keep `rateLimitBudget` IDs consistent.** Every budget referenced by an upstream or network must exist in `rateLimiters.budgets`. Validation catches this (`erpc validate`), but older runtime versions silently skip rate-limiting when a budget is missing. - **Don't leave a stale `erpc.yaml` when migrating to `erpc.ts`.** YAML is probed first — the old file silently shadows the new one. Remove or rename it. - **Vendor shorthand endpoints (`alchemy://`, `tenderly://`, etc.) become providers, not upstreams.** After `SetDefaults` they move from `p.Upstreams` to `p.Providers`; `erpc validate` reports them under `providersTotal`, not `upstreamsTotal`. This is expected. ### Edge cases & gotchas - **`--set` / `-s` is not implemented.** The flag is commented out in the source. Passing `-s logLevel=debug` produces `"flag provided but not defined: -s"` from the CLI framework. There is no Helm-style dot-path override; use env vars or config file edits. Source: [`cmd/erpc/main.go:L86-L90`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L86-L90) - **`validate` and `dump` suppress all log output.** `zerolog.SetGlobalLevel(zerolog.Disabled)` is called before `getConfig` runs. No warnings from `SetDefaults`, legacy migration, or validation appear on stderr. Pipe stdout through `jq .errors` to see errors. Source: [`cmd/erpc/main.go:L109`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L109) - **`dump --format csv` (or any unknown format) exits 1** via a distinct code path, not a marshal error. Valid values are `"yaml"`, `"yml"`, and `"json"` only. - **Positional argument works in ALL subcommands.** `erpc validate ./my-config.yaml` and `erpc dump ./my-config.yaml` treat the first positional arg as a config path with `requireConfig=true`. Source: [`cmd/erpc/main.go:L303-L305`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L303-L305) - **TypeScript default export must be the last statement.** The sobek runtime's `exports.default` is inspected after the script runs; a later expression can overwrite it. Error: `"config object must be default exported from TypeScript code AND must be the last statement in the file"`. - **TS module executes multiple times** — once at load and once per policy-pool runtime acquire. Top-level side effects (logging, expensive computation) are repeated; keep the config pure. - **`erpc.dist.yaml` fails validation as shipped** — upstreams reference `rateLimitBudget: global` but no `global` budget exists. Use it as a shape reference only, not copy-paste directly. Source: [`erpc.dist.yaml`](https://github.com/erpc/erpc/blob/main/erpc.dist.yaml) - **`LOG_LEVEL` env var overrides config-file `logLevel` at two points** — first in `init()` (applies to the config-loading phase) and second after decode (overrides `cfg.LogLevel` itself). A file setting of `logLevel: error` can be trumped by `LOG_LEVEL=debug` without editing the file. ### Source code entry points - [`cmd/erpc/main.go:L279-L293`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L293) — config file discovery loop - [`common/config.go:L87-L132`](https://github.com/erpc/erpc/blob/main/common/config.go#L87-L132) — `LoadConfig`: YAML vs TS dispatch, `os.ExpandEnv`, strict decode, defaults, validation - [`common/defaults.go:L49-L176`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49-L176) — `Config.SetDefaults`: full default cascade including synthetic project injection - [`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15) — `Config.Validate`: all cross-field validation rules - [`common/config.go:L2686-L2766`](https://github.com/erpc/erpc/blob/main/common/config.go#L2686-L2766) — `loadConfigFromTypescript`: esbuild bundle, walker, sobek eval, JSON round-trip - [`cmd/erpc/main.go:L109`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L109) — `validate` subcommand: zerolog suppression, structured JSON/MD report - [`erpc/config_analyzer.go`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go) — `GenerateValidationReport`: static analysis producing the validation report ### Config formats — YAML vs TypeScript eRPC accepts the same schema as `erpc.yaml`/`erpc.yml` (strict YAML) or `erpc.ts`/`erpc.js` (TypeScript compiled in-process). Everything below — discovery order, the TS loading pipeline, env-var semantics, validate/dump tooling — applies to whichever format you pick. #### How it works **File discovery.** When no `--config` flag or positional argument is supplied, eRPC probes a hardcoded list in order: `./erpc.yaml`, `./erpc.yml`, `./erpc.ts`, `./erpc.js`, then the same four filenames under `/` and `/root/`. The first path where `fs.Stat` succeeds wins. YAML takes priority over TypeScript within the same directory — a leftover `erpc.yaml` silently shadows a newly added `erpc.ts`. Passing an explicit path forces that file and treats a missing file as a fatal error (exit 1001). A `.env` file in the working directory is loaded at process `init()` time via `godotenv` before any config parsing. **YAML loading.** `common.LoadConfig` reads the file, runs `os.ExpandEnv` on the raw bytes (substituting every `$VAR` and `${VAR}` pattern from the OS environment), then decodes with `gopkg.in/yaml.v3` in strict mode (`KnownFields(true)` — unknown keys are errors). After decode, it applies `LegacyTranslateFn` (legacy key migration), then `SetDefaults`, then `Validate`. **TypeScript loading pipeline.** `loadConfigFromTypescript` (`common/config.go:L2686`) runs these steps: 1. esbuild (embedded Go library) bundles the `.ts`/`.js` file as a self-contained IIFE, resolving all imports including `@erpc-cloud/config`. `createConfig` is a pure identity function — it costs nothing. 2. A `tsLoaderWalker` JS fragment is appended that depth-first walks `exports.default`, assigns sequential IDs (`fn_0`, `fn_1`, …) to every function-valued object property, and registers them on `globalThis.__erpcFns`. 3. The result is compiled to a `sobek.Program` once and stored as `cfg.UserScript`. 4. A throwaway runtime evaluates the program; `exports.default` is the config object. 5. `JSON.stringify` with a replacer converts registered functions to sentinel strings (`"__ts_fn__:fn_"`); unregistered functions are dropped (never `.toString()`-serialised). 6. The JSON is decoded through the same strict YAML decoder used for `.yaml` files, so schema validation is identical — typos fail with the same unknown-field error. **`os.ExpandEnv` is YAML-only.** TypeScript/JS files are never subjected to shell-variable expansion. Use `process.env.MY_KEY` (a JS expression) instead of `${MY_KEY}`. **Function preservation at runtime.** `cfg.UserScript` is re-evaluated once per policy-engine runtime-pool acquire, rebuilding `__erpcFns` natively in that runtime so closures and module-level helpers remain live. At tick time, a `__ts_fn__:fn_` sentinel is resolved by id lookup in `__erpcFns` and invoked directly. **Shared post-load pipeline.** Both formats share `LegacyTranslateFn` → `SetDefaults` → `Validate`. Validation errors cause exit 1001. `erpc validate` loads config, runs static analysis (orphan rate-limit budgets, missing upstreams, etc.), and prints a JSON or Markdown report. `erpc dump` loads config and renders the fully defaulted effective config as YAML or JSON — useful for seeing what TS sentinel functions resolve to. #### Config schema **Top-level `Config` fields** ([`common/config.go:L38-68`](https://github.com/erpc/erpc/blob/main/common/config.go#L38-L68)) | YAML path | Type | Default | Behavior / notes | |---|---|---|---| | `logLevel` | string | `"INFO"` | Parsed by zerolog. Valid values: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`, `disabled`. Invalid value defaults to `debug` with a warning. Overridable at runtime by `LOG_LEVEL` env var. [`common/defaults.go:L50-52`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L50-L52) | | `clusterKey` | string | `"erpc-default"` | Identifies the logical replica group for shared-state scoping. Propagated to `database.sharedState.clusterKey` when that field is unset — an explicit `database.sharedState.clusterKey` always wins. [`common/defaults.go:L53-55`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L53-L55) | | `server` | object | synthetic empty struct then `SetDefaults` | HTTP/gRPC server config; see [Server](/config/server.llms.txt). | | `metrics` | object | `enabled=true`, `port=4001`, `errorLabelMode="compact"` | Prometheus metrics server. | | `database` | object | nil | EVM JSON-RPC cache and/or shared state. | | `projects` | array | synthetic `main` project if empty | Ordered list of project configs. | | `rateLimiters` | object | nil | Rate limiter budgets. | | `healthCheck` | object | `mode=networks`, `defaultEval=any:initializedUpstreams` | Health check endpoint behaviour. | | `admin` | object | nil | Admin API; CORS defaults to `*` origin with no credentials. | | `tracing` | object | nil | OTel tracing; default protocol=grpc, endpoint=localhost:4317, sampleRate=1.0, serviceName=erpc. | | `proxyPools` | array | nil | HTTP proxy pool definitions. | **`MetricsConfig` fields** ([`common/config.go:L2543-2563`](https://github.com/erpc/erpc/blob/main/common/config.go#L2543-L2563), [`common/defaults.go:L749-767`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L749-L767)) | YAML path | Type | Default | Behavior | |---|---|---|---| | `metrics.enabled` | bool | `true` (non-test); unset in test builds | If false/nil, metrics server is not started. | | `metrics.hostV4` | string | `"0.0.0.0"` | Prometheus scrape endpoint IPv4 bind host. | | `metrics.hostV6` | string | `"[::]"` | IPv6 bind host. | | `metrics.port` | int | `4001` | Prometheus scrape port. | | `metrics.errorLabelMode` | string | `"compact"` | Controls the `error` label on error-count metrics. `"compact"` condenses error codes; `"verbose"` emits full class names. | | `metrics.histogramBuckets` | string | `""` (built-in defaults) | Comma-separated float64 bucket boundaries for request-duration histograms. Validation rejects non-float values. | | `metrics.customizations` | []object | nil | List of `{subject, action, labels, buckets}` entries controlling which metric families are exposed, which labels they carry, and their histogram buckets. `subject` is a metric name without the `erpc_` prefix, optionally ending in `*`. Rules apply by specificity (exact > longer prefix > shorter prefix > `*`), not list order. | | `metrics.histogramDropLabels` | []string | nil | **Deprecated** — use `metrics.customizations` with `labels: [{subject, action: drop}]`. Label names removed from every histogram to reduce cardinality; counters/gauges unaffected. | | `metrics.histogramLabelOverrides` | map | nil | **Deprecated** — use `metrics.customizations`. Per-metric label keep-list; key is metric name without `erpc_` prefix (e.g. `"network_request_duration_seconds"`). | | `metrics.counterDropLabels` | []string | nil | **Deprecated** — use `metrics.customizations` with `labels: [{subject, action: drop}]`. Label names removed from every counter carrying caller-controlled dimensions; sums are preserved, the dimension is not. | | `metrics.counterLabelOverrides` | map | nil | **Deprecated** — use `metrics.customizations`. Per-metric label keep-list for counters; key is metric name without `erpc_` prefix. | **Default project synthesis.** When `projects` is empty, `SetDefaults` injects a synthetic `main` project ([`common/defaults.go:L100-167`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L167)) with: - a `repository` provider (id `public`) - An aliasing rule so `/evm/` resolves without a project prefix - Network defaults: `evm.getLogsMaxAllowedRange=30_000`, `getLogsSplitOnError=true`, integrity enforcement enabled - Network-level failsafe: retry(maxAttempts=5), timeout(120s), hedge(p70 quantile, maxCount=2) - Upstream-level failsafe: retry(maxAttempts=1, delay=500ms), timeout(60s) - Upstream defaults: `evm.getLogsAutoSplittingRangeThreshold=5000` **Validation rules** ([`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15)). Key rules beyond basic non-null checks: - `server.maxTimeout` must be non-zero - Each project needs at least one upstream or provider - `project.*.networks.*.alias` must match `[a-zA-Z0-9_-]+` and be unique within the project - Referenced `rateLimitBudget` IDs must exist in `rateLimiters.budgets` - `onlyNetworks` and `ignoreNetworks` on a provider are mutually exclusive - `selectionPolicy.evalTimeout` must be strictly less than `selectionPolicy.evalInterval` - `selectionPolicy.evalFunc` must compile (or be a TS sentinel) - Connector failsafe may not use `consensus` or `hedge.quantile` (no latency source at connector level) - `database.sharedState.lockMaxWait` and `updateMaxWait` must be less than `fallbackTimeout` **TypeScript scalar types.** (`typescript/config/src/types/generic.ts`) | TS type | Accepted forms | Footgun | |---|---|---| | `Duration` | `` `${number}ms` ``, `` `${number}s` ``, `` `${number}m` ``, `` `${number}h` ``, or bare `number` | Bare number → **milliseconds** (not nanoseconds). | | `ByteSize` | `` `${number}b` ``, `` `${number}kb` ``, `` `${number}mb` ``, or bare `number` | Only B/KB/MB parsed — **no `gb` form** for cache-policy `minItemSize`/`maxItemSize`. Memory connector `maxTotalSize` uses a different parser that does accept GB. | | `LogLevel` | `"trace"` \| `"debug"` \| `"info"` \| `"warn"` \| `"error"` \| `"disabled"` \| `undefined` | — | **TS enum values.** TS constants serialize as JSON numbers; the Go YAML decoder accepts both numbers and names: | Constant | Value | Notes | |---|---|---| | `DataFinalityStateRealtime` | `0` | Also accepted as `"realtime"` or `"0"` in YAML. | | `DataFinalityStateUnfinalized` | `1` | Also `"unfinalized"` or `"1"`. | | `DataFinalityStateFinalized` | `2` | Also `"finalized"` or `"2"`. | | `DataFinalityStateUnknown` | `3` | Also `"unknown"` or `"3"`. | | `CacheEmptyBehaviorIgnore` | `0` | — | | `CacheEmptyBehaviorAllow` | `1` | — | | `CacheEmptyBehaviorOnly` | `2` | — | | `RateLimitPeriodSecond` | `0` | Also `"1s"`; Go also accepts duration aliases like `"24h"`, `"7d"`. | **TS sobek runtime environment.** Inside a TS config (or `evalFunc`): - `process.env.X` — full OS environment as a key/value map (snapshot at runtime creation) - `env` global — raw `os.Environ()` string array (`"KEY=VALUE"` pairs) - `console.log/info/warn/debug/trace` — forwarded to zerolog at the matching level; suppressed below global log level - Node stdlib (`fs`, `http`, …) — **NOT available** in sobek; only env/process/console are installed Config formats own no additional YAML runtime fields. The table below documents the loader's environment contract and CLI flags. **CLI flags** ([`cmd/erpc/main.go:L76-94`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L76-L94)) | Flag | Type | Default | Behavior / footguns | |---|---|---|---| | `--config` | string | `""` | Path to config file; skips auto-discovery; sets `requireConfig=true` implicitly — missing file exits 1001. | | positional arg | string | — | Same as `--config`; forces `requireConfig=true`; works with all subcommands (`start`, `validate`, `dump`). | | `--require-config` | bool | `false` | Abort if no config found in search path; no effect when `--config` is given (already implied). | | `--endpoint` / `-e` | `[]string` | `[]` | Inject upstream endpoint URLs when no providers/upstreams exist in config. Provider-scheme URLs (e.g. `alchemy://key`) are converted to providers at `SetDefaults` time. Invalid URLs abort with exit 1001. | | `validate --format` | string | `"json"` | `"json"` or `"md"`. | | `dump --format` | string | `"yaml"` | `"yaml"`, `"yml"`, or `"json"`. Any other value exits 1 via an explicit error branch. | | `--set` / `-s` | — | **not available** | Commented out of the source. Passing `-s` produces `"flag provided but not defined: -s"` — not a graceful error. | **Environment variables** | Env var | Scope | Behavior | Citation | |---|---|---|---| | `$VAR` / `${VAR}` in YAML | YAML loader | `os.ExpandEnv` on raw bytes before parse; unset vars → empty string. Unquoted values containing `:` or `{` will break YAML parse. | [`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) | | `process.env.X` in TS | TS runtime | Populated from `os.Environ()` when the sobek runtime is created; `.env` file loaded first. Snapshot — not updated if env changes after startup. | [`common/runtime.go:L23-36`](https://github.com/erpc/erpc/blob/main/common/runtime.go#L23-L36) | | `LOG_LEVEL` | bootstrap | Zerolog global level; overrides `logLevel` in config. Applied twice: at `init()` and again after decode. Valid values: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`, `disabled`. Invalid value falls back to `debug` with a warning. | [`cmd/erpc/main.go:L59-L66`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L59-L66) | | `LOG_WRITER` | bootstrap | When `"console"`, switches zerolog to human-readable output (`04:05.000ms` time format). Set at `init()` — cannot be changed at runtime. | [`cmd/erpc/main.go:L53-L57`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L53-L57) | | `INSTANCE_ID` | shared state + consensus | First in the instance-identity priority chain: `INSTANCE_ID` → `POD_NAME` → `HOSTNAME` → `os.Hostname()` → `"unknown"` (shared-state) or SHA-256 hash of (unixNano+pid) (consensus). Used as `UpdatedBy` field in shared-state writes and as the `{instanceId}` token in consensus dispute-log filenames. In Kubernetes, setting `POD_NAME` via the downward API is recommended. | [`data/shared_state_registry.go:L82-L98`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L82-L98) | | `POD_NAME` | shared state + consensus | Second in priority chain (Kubernetes pod name). Same two contexts as `INSTANCE_ID`. | — | | `HOSTNAME` | shared state + consensus | Third in priority chain (OS hostname). Same two contexts as `INSTANCE_ID`. | — | | `ERPC_NOLOGS` | test builds only | When `"1"`, sets zerolog global level to `Disabled` and replaces the logger with `io.Discard`. Suppresses all log output. Only effective in non-production builds (build tag `!test` guard on `initflags.go`). | [`cmd/erpc/initflags.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go) | | `ERPC_NOMETRICS` | test builds only | When `"1"`, swaps `prometheus.DefaultRegisterer`/`DefaultGatherer` with a no-op registry. Metric registrations succeed but accumulate no memory. Irreversible within the process. | [`cmd/erpc/initflags.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go) | | `ERPC_PPROF_PORT` | pprof build only | Port for the pprof HTTP server (default `6060`). Only active when binary built with `-tags pprof`. **Security:** binds `0.0.0.0:` (all interfaces, not localhost-only) — must be firewall-restricted in production. | [`cmd/erpc/pprof.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/pprof.go) | | `$VAR` in `server.responseHeaders` values | HTTP server init | Expanded once at startup via `os.ExpandEnv` during HTTP server construction (after full config decode, distinct from YAML-level expansion). Headers that expand to empty string are silently omitted. | [`erpc/http_server.go:L135-L148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148) | | `$VAR` in provider-generated endpoints | provider resolution | After the vendor's `GenerateConfigs` returns each `UpstreamConfig`, `os.ExpandEnv` is called on each `Endpoint` string — distinct from (and after) YAML-level expansion. Double-expansion possible if `GenerateConfigs` builds an endpoint that itself contains `$VAR` literals. | [`thirdparty/provider.go:L67-L71`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L67-L71) | **`validate` command JSON output schema** (`erpc/config_analyzer.go:L76-L123`) ``` { "errors": [], "warnings": [], "notices": [], "resources": { "totals": { "projectsTotal", "networksTotal", "upstreamsTotal", "rateLimitBudgetsTotal" }, "tree": { "projects": [...], "rateLimiters": { "budgets": [...] } } } } ``` Exits 0 if `errors` is empty, exits 1 otherwise. #### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. YAML with `.env` secrets — simplest production shape.** Env vars are substituted before parse; quote every value that might contain `:` or `{` to avoid YAML parse errors after expansion: ```yaml # erpc.yaml (with .env file providing ALCHEMY_API_KEY, INFURA_API_KEY) logLevel: warn projects: - id: main networks: - architecture: evm evm: { chainId: 1 } upstreams: # Always quote env-interpolated values — a bare ${VAR} containing ":" # produces invalid YAML after os.ExpandEnv substitution. - endpoint: "alchemy://${ALCHEMY_API_KEY}" - endpoint: "infura://${INFURA_API_KEY}" ``` **2. TypeScript config split into shared modules — the production multi-chain shape.** A large fleet uses one `erpc.ts` that imports typed fragments from `shared/` files. The module-level `networkDefaults` and `upstreamDefaults` objects are evaluated once at load and reused across chains — closures in `evalFunc` bodies capture them without serialisation: ```ts // erpc.ts — assembly point; env vars only here export default createConfig({ logLevel: "warn", database: { evmJsonRpcCache: cacheConfig(), }, projects: [{ id: "main", // Defaults applied to every network / upstream in this project networkDefaults, upstreamDefaults, networks: [{ architecture: "evm", evm: { chainId: 1 } }], upstreams: [{ // process.env — NOT ${VAR} — JS template literals need process.env. // ${ALCHEMY_API_KEY} without process.env resolves to "undefined" silently. endpoint: `alchemy://${process.env.ALCHEMY_API_KEY}`, }], }], }); ``` **3. TypeScript with a real closure in `evalFunc` — upstream weight map.** The TS path preserves closures; the module-level `weights` constant is available inside the function body at policy-tick time, with no serialisation. This is the canonical reason to prefer TypeScript over YAML for complex selection policies: ```ts // erpc.ts // Module-level constant — captured by reference in evalFunc and available // on every policy-pool runtime acquire without stringifying the function. const weights: Record = { "alchemy": 3, "infura": 1 }; export default createConfig({ logLevel: "info", projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 } }], upstreams: [ { endpoint: `alchemy://${process.env.ALCHEMY_API_KEY}` }, { endpoint: `infura://${process.env.INFURA_API_KEY}` }, ], selectionPolicy: { evalFunc: (upstreams) => upstreams.sort((a, b) => (weights[b.upstream.id] ?? 0) - (weights[a.upstream.id] ?? 0) ), }, }], }); ``` **4. Per-method failsafe tiers in `upstreamDefaults` — production upstream-level policies.** Production fleets use `upstreamDefaults.failsafe` to apply tight adaptive timeouts per method group at the upstream boundary, so the network-level retry budget isn't burned on upstreams that are merely slow. Method-specific entries must come before the catch-all (`hedge: null` suppresses upstream-level hedging — hedging belongs at network scope): ```ts // shared/upstreams.ts const upstreamFailsafe: FailsafeConfig[] = [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", // Heavy range queries routinely take seconds — floor of 2s prevents premature // upstream-level timeouts that burn network-level retry budget on subgraph backfills. timeout: { duration: "15s", quantile: 0.9, minDuration: "2s", maxDuration: "15s" } as any, // Hedge and retry are null at upstream scope — handled at network scope instead. hedge: null, retry: null, }, { matchMethod: "eth_call", // eth_call latency is bimodal (cache hit ~5ms, heavy simulation ~10s). // Adaptive timeout tracks actual p80 so fast calls aren't capped at the ceiling. timeout: { duration: "20s", quantile: 0.8, minDuration: "500ms", maxDuration: "20s" } as any, hedge: null, retry: null, }, { matchMethod: "*", timeout: { duration: "60s", quantile: 0.8, minDuration: "500ms", maxDuration: "60s" } as any, hedge: null, retry: null, }, ]; export const upstreamDefaults: UpstreamConfig = { // Disable filter methods — providers rarely support them reliably. ignoreMethods: ["eth_newFilter", "eth_newBlockFilter", "eth_newPendingTransactionFilter"], failsafe: upstreamFailsafe, }; ``` **5. Using `erpc validate` and `erpc dump` in CI.** Validate exits 1 on errors and suppresses all log output; pipe through `jq` to surface only errors. Use `erpc dump` after switching formats to confirm effective failsafe defaults: ```sh # CI pre-deploy check — fails build if config has errors erpc validate --format json ./erpc.ts | jq .errors # Markdown report for humans (e.g. in a PR comment) erpc validate --format md ./erpc.yaml # Inspect effective defaults after migrating YAML → TS erpc dump --format yaml ./erpc.ts # Check a specific section (e.g. first network's failsafe after adding defaults) erpc dump --format json ./erpc.ts | jq '.projects[0].networks[0].failsafe' ``` #### Request/response behavior Config loading is a startup-phase operation, not a per-request path. No HTTP headers or JSON-RPC bodies are involved. The loader reports its outcome through log messages and exit codes only. **Exit codes** ([`util/exit.go:L7-10`](https://github.com/erpc/erpc/blob/main/util/exit.go#L7-L10)): - `1001` (`ExitCodeERPCStartFailed`) — CLI/config load failure, validation error, or `erpc.Init` error. - `1002` (`ExitCodeHttpServerFailed`) — HTTP or gRPC server fatal error. #### Best practices - **Quote all YAML env-interpolated values.** `password: "${REDIS_PASSWORD}"` is safe; `password: ${REDIS_PASSWORD}` breaks if the value contains `:` or `{`. Source: [`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) - **Use `process.env.VAR`, not `${VAR}`, in TypeScript configs.** `${MY_KEY}` in a TS template literal is a JS variable reference — if undeclared, it evaluates to `"undefined"`, silently producing `alchemy://undefined`. Source: [`common/config.go:L95-109`](https://github.com/erpc/erpc/blob/main/common/config.go#L95-L109) - **Keep the TS config module pure.** The module is evaluated multiple times (load, each policy-pool runtime acquire, `erpc dump`). Top-level side effects like logging or HTTP calls repeat on every acquire. - **Run `erpc validate` in CI before deploying.** All log output is suppressed during validation; errors appear only in the JSON/Markdown output. Pipe `validate` stdout through `jq .errors` to diagnose failures. - **Run `erpc dump` to verify effective defaults.** After switching from manual config to system-template, use `erpc dump` to confirm the failsafe defaults (retry, timeout, hedge) are what you expect. - **Never rely on `--set` / `-s`.** The flag is commented out. Use `.env` or `process.env` for environment-specific overrides. - **Pin `@erpc-cloud/config` to the matching binary version.** The npm package is always released in lockstep with the Go binary; a version mismatch means the TS types may not match the runtime schema. #### Edge cases & gotchas 1. **YAML beats TS in auto-discovery.** `./erpc.yaml` and `./erpc.yml` are probed before `./erpc.ts` and `./erpc.js`. A stale `erpc.yaml` in the working directory silently shadows your `erpc.ts`. 2. **YAML env value with special characters breaks parse.** If `$MY_VAR` expands to a value containing `:` or `{`, the substituted text becomes invalid YAML. Quote all env-interpolated values: `value: "${MY_VAR}"`. 3. **TS `${VAR}` without `process.env.` is a JS variable reference, not env expansion.** `${MY_KEY}` in a TS template literal references a JS variable `MY_KEY`. If undeclared, it evaluates to `"undefined"`, producing endpoint strings like `alchemy://undefined`. This is a silent failure — no parse error, just a wrong URL. 4. **TS default export must be last.** `exports.default` is read after the program runs. A reassignment by any later expression overwrites the config. Error: `"config object must be default exported from TypeScript code AND must be the last statement in the file"`. 5. **Functions outside walkable positions are silently dropped.** The walker registers only function-valued object properties. A function placed directly as an array element is not walked; the `JSON.stringify` replacer drops it (`undefined`), and the decoded field is missing. Source: [`common/config.go:L2636-L2652`](https://github.com/erpc/erpc/blob/main/common/config.go#L2636-L2652). 6. **TS module evaluates multiple times.** Load, each policy-pool runtime acquire, and `erpc dump` each re-run the full module. Top-level side effects (logging, HTTP calls, `Date.now()`) repeat. Keep the config module pure. 7. **`validate` and `dump` suppress all log output.** `zerolog.SetGlobalLevel(zerolog.Disabled)` fires before `getConfig`, so warnings from `SetDefaults` and legacy migration are invisible. Pipe `validate` stdout through `jq .errors` to diagnose failures. 8. **`--set` / `-s` is not implemented.** The flag is commented out. Passing it produces a CLI framework error, not a graceful "unsupported" message. 9. **`dump --format csv` exits 1 via an explicit error branch, not a marshal failure.** Valid formats are `yaml`, `yml`, and `json` only. Source: [`cmd/erpc/main.go:L190-L194`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L190-L194). 10. **TS `process.env` is a snapshot.** The env map is built once when the sobek runtime is created. Changes to OS env vars after startup are not reflected; a restart is required. 11. **Provider-scheme endpoints are converted to providers, not upstreams.** `alchemy://key` in `--endpoint` or in `upstreams[].endpoint` is converted to a `ProviderConfig` and removed from `upstreams` by `SetDefaults`. `erpc validate` reports it under providers, so `upstreamsTotal` looks lower than the endpoint count. 12. **`erpc.dist.yaml` ships broken.** The canonical YAML example references a `global` rate-limit budget that does not exist in `rateLimiters.budgets` and contains a duplicate upstream id. `erpc validate --config erpc.dist.yaml` exits 1. The TypeScript example (`erpc.dist.ts`) validates cleanly when env vars are set. 13. **`erpc dump` may print `__ts_fn__:fn_N`** for a TS `evalFunc` when source resolution fails (best-effort `.toString()`; any error leaves the sentinel). Source: [`internal/policy/dump.go:L32-L136`](https://github.com/erpc/erpc/blob/main/internal/policy/dump.go#L32-L136). 14. **Strict decode applies to TS configs too.** `decoder.KnownFields(true)` on the JSON intermediary means a property typo still fails at load with the same unknown-field error YAML gives. 15. **`AuthStrategyConfig` union is wrong for non-secret strategies in TS.** The hand-written `network`/`jwt`/`siwe` arms declare their payload under the key `secret` instead of the correct key names. Also, the `database` auth type is absent from the TS union. Source: [`typescript/config/src/types/generic.ts:L120-L141`](https://github.com/erpc/erpc/blob/main/typescript/config/src/types/generic.ts#L120-L141). 16. **`grpc` cache-connector driver is unrepresentable in TS.** Go supports `DriverGrpc` + `ConnectorConfig.grpc`, but the hand-written `TsConnectorConfig` union used for `cache.connectors` has no `grpc` arm. Same for `UpstreamType` missing `evm+blockdaemon`. Source: [`typescript/config/src/types/generic.ts:L63-L83`](https://github.com/erpc/erpc/blob/main/typescript/config/src/types/generic.ts#L63-L83). 17. **`scoreMetricsWindowSize` doc comment discrepancy.** The Go source comment claims "Defaults to 10m when zero"; the actual fallback in `projects_registry.go` is `1 * time.Minute`. The `erpc.dist.yaml` comment claims "Defaults to 5s". The code always wins — default is 1m. Source: [`erpc/projects_registry.go:L50,L133-L134`](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go#L50). 18. **`ERPC_PPROF_PORT` binds all interfaces.** The pprof server uses `0.0.0.0:`, not `127.0.0.1`. In production the port must be firewall-restricted or the binary must be built without `-tags pprof`; any host that can reach the port gets full Go runtime profiling access. 19. **TS-required fields that Go would default.** Tygo marks non-`omitempty` fields as required, so `MemoryConnectorConfig` forces `maxItems` + `maxTotalSize` in TS even though Go defaults them to `100000` / `"1GB"`. YAML users can omit them. Source: [`common/defaults.go:L935-L944`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L935-L944). 20. **Legacy YAML keys work in TS objects too.** Both formats share the same `UnmarshalYAML` hooks after the TS JSON round-trip, so e.g. `group: 'main'` on an upstream becomes a `tier:main` tag in both YAML and TS. 21. **Metrics server is disabled in test builds.** `MetricsConfig.SetDefaults` sets `Enabled` only when `!util.IsTest()`. In `go test` runs, metrics are off by default. Tests needing metrics must set `metrics.enabled: true` explicitly. Source: [`common/defaults.go:L750-L752`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L750-L752). #### Observability The config-loading and format subsystems emit no Prometheus metrics. Operational signals are log-only: | Log message | Level | When | |---|---|---| | `"executing command"` | INFO | Every CLI action; includes `action`, `version`, `commit` fields | | `"looking for config file: "` | INFO | Each path probed during auto-discovery | | `"resolved configuration file to: "` | INFO | Winning path identified | | `"initializing eRPC core"` | INFO | Before `NewERPC` construction | | `"initializing transports"` | INFO | After core init, before server start | | `"networks bootstrap completed"` | INFO | After all configured networks are initialised | | `"shutting down gracefully..."` | INFO | On SIGINT/SIGTERM context cancel | | `"pprof server started at http://localhost:"` | INFO | Only when built with `-tags pprof` | | `"failed to load configuration"` | ERROR | Any `LoadConfig` error before exit 1001 | | `"build failed: "` | ERROR | esbuild compilation error in `.ts`/`.js` file | | `"compile ts config: …"` | ERROR | sobek compile error after bundling | | `"ts config json-stringify: …"` | ERROR | JSON.stringify step failed on TS config object | | `"ts config decode: …"` | ERROR | Strict YAML decode of the TS JSON output failed (field typo) | | `"config default export serialized to null/undefined"` | ERROR | TS config did not produce a valid default export | | `"evaluate user TS config in policy runtime: …"` | ERROR | Policy engine failed to re-run `UserScript` in a pooled runtime | | `"ts selectionPolicy.evalFunc lookup: …"` | ERROR | Sentinel `__erpcFns` id not found or registry not populated | | `"no projects found in config; will add a default 'main' project"` | WARN | `SetDefaults` synthetic project injection | | `"no providers or upstreams found in project; will use default 'public' endpoints"` | WARN | Public fallback injected for a project with no upstreams/providers | | `"failed to initialize evm json rpc cache: …"` | WARN | Cache init failure is non-fatal; eRPC continues without caching | | `"failed to initialize shared state registry: …"` | WARN | Shared-state init failure is non-fatal | | `"invalid log level '...', defaulting to 'debug'"` | WARN | Emitted at init time and at runtime if `LOG_LEVEL` has an invalid value | #### Source code entry points - [`cmd/erpc/main.go:L279-L322`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L322) — config file auto-discovery loop, `getConfig`, `--endpoint` injection, `.env` loading - [`common/config.go:L87-L132`](https://github.com/erpc/erpc/blob/main/common/config.go#L87-L132) — `LoadConfig`: suffix dispatch (YAML vs TS/JS), `os.ExpandEnv`, strict YAML decode, legacy migration, `SetDefaults`, `Validate` - [`common/config.go:L2686-L2766`](https://github.com/erpc/erpc/blob/main/common/config.go#L2686-L2766) — `loadConfigFromTypescript`: esbuild bundle, walker append, sobek compile + run, JSON stringify with sentinel replacer, strict YAML decode of JSON - [`common/compiler.go:L10-L41`](https://github.com/erpc/erpc/blob/main/common/compiler.go#L10-L41) — `CompileTypeScript`: esbuild Go API options (IIFE, ES2020, Node platform, inline sourcemap) - [`common/runtime.go:L15-L44`](https://github.com/erpc/erpc/blob/main/common/runtime.go#L15-L44) — `NewRuntime`: sobek runtime factory; populates `env` array and `process.env` map from `os.Environ()` - [`common/defaults.go:L49-L176`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49-L176) — `Config.SetDefaults`: default cascade including synthetic `main` project injection - [`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15) — `Config.Validate`: exhaustive schema validation - [`internal/policy/runtime_pool.go:L41-L82`](https://github.com/erpc/erpc/blob/main/internal/policy/runtime_pool.go#L41-L82) — re-runs `UserScript` per pooled runtime, preserving closures and module-level helpers - [`common/config_test.go:L147-L348`](https://github.com/erpc/erpc/blob/main/common/config_test.go#L147-L348) — TS unified-pipeline + closure-preservation tests (key behavior contracts) ### Related pages - [Auth](/config/auth.llms.txt) — note: the TypeScript `AuthStrategyConfig` union has known bugs for non-secret strategies; prefer YAML when using jwt/siwe/network auth. - [Upstreams](/config/projects/upstreams.llms.txt) — every upstream field, vendor shorthands, batching, method filtering. - [Networks](/config/projects/networks.llms.txt) — per-chain failsafe, finality, integrity checks. - [Cache policies](/config/database/evm-json-rpc-cache.llms.txt) — finality tiers, TTL semantics, connector routing. - [Rate limiters](/config/rate-limiters.llms.txt) — shared budgets, waitTime, per-method rules. - [Failsafe overview](/config/failsafe/timeout.llms.txt) — retry, hedge, circuit breaker, consensus. --- --- # Failsafe > Source: https://docs.erpc.cloud/config/failsafe > Six composable failsafe policies that keep every RPC request succeeding — even when upstreams are slow, wrong, or temporarily down. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Failsafe A broken upstream becomes invisible to your callers. eRPC wraps every request in six independently tunable policies — retry, hedge, timeout, circuit breaker, consensus, and integrity — that run in a fixed, deterministic chain. Configure once per method or finality tier; let eRPC handle the rest. - **[Timeout](/config/failsafe/timeout.llms.txt)** — Bound how long a request may take — static or quantile-adaptive, at the network lifecycle or single-upstream level. - **[Retry](/config/failsafe/retry.llms.txt)** — Replay transient failures with exponential backoff and jitter. Separate knobs for hard errors vs. data-unavailability conditions. - **[Hedge](/config/failsafe/hedge.llms.txt)** — Race a speculative duplicate request to a second upstream when the primary is slow — quantile-adaptive delay with min/max guardrails. - **[Circuit breaker](/config/failsafe/circuit-breaker.llms.txt)** — Per-upstream state machine that stops routing to a failing endpoint after a rolling-window failure threshold, then self-heals. - **[Consensus](/config/failsafe/consensus.llms.txt)** — Fan out to N upstreams, group identical responses by canonical hash, and select a winner — with misbehavior tracking and punishment. - **[Integrity](/config/failsafe/integrity.llms.txt)** — Layered EVM response-validation rules that discard stale, malformed, or logically inconsistent upstream responses before they reach callers. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: make my RPC survive provider outages** ```text My app uses a single RPC provider and goes down when it has an outage. Configure eRPC's failsafe layer in my eRPC config — retry, hedge, timeout, and circuit breaker — so requests automatically route around failures without my callers noticing. Read the full reference: https://docs.erpc.cloud/config/failsafe.llms.txt ``` **Prompt Example #2: tune failsafe policies for a latency-sensitive workload** ```text My frontend makes a lot of eth_call and eth_getLogs requests and I want to minimize p99 latency while still having retry coverage for transient errors. Tune the failsafe entries in my eRPC config — including per-method matchMethod and matchFinality — so realtime calls get short timeouts and archival calls get longer budgets. Reference: https://docs.erpc.cloud/config/failsafe.llms.txt ``` **Prompt Example #3: debug ErrFailsafeConfiguration at startup** ```text eRPC is crashing at startup with ErrFailsafeConfiguration. Inspect my eRPC config and find any circuit breaker blocks placed at network scope or consensus blocks placed at upstream scope — these are the two scope mismatch errors that cause this. Fix each one and explain why the scope restriction exists. Reference: https://docs.erpc.cloud/config/failsafe.llms.txt ``` **Prompt Example #4: add alerts for failsafe effectiveness** ```text I want Prometheus alerts to catch when eRPC's failsafe layer is under stress: high retry rates, frequent circuit-breaker trips, or hedge fire rates spiking. Using the metrics in my eRPC config's Prometheus output, write PromQL alert expressions for each condition and explain the thresholds. Reference: https://docs.erpc.cloud/config/failsafe.llms.txt ``` --- ### Resilience — full agent reference ### How it works **Executor composition.** The non-consensus executor chain is `retry(hedge(runUpstreamSweep))`; with consensus active it becomes `consensus(retry(hedge(tryOneUpstream)))`. The network-scope timeout wraps the entire `networkExecutor.Run` call — so it bounds ALL retries and hedges, not individual attempts. ([`erpc/network_executor.go:L183-203`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L183-L203)) **Scope restrictions.** - Circuit breakers are **upstream-scope only**. Placing a `circuitBreaker` block in a network-level `failsafe` entry causes startup failure with `ErrFailsafeConfiguration`. ([`erpc/network_executor.go:L68-73`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L68-L73)) - Consensus is **network-scope only**. Placing a `consensus` block in an upstream-level `failsafe` entry fails config validation at startup. ([`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go)) - `matchCommitment` is **network-scope only**. Setting it on upstream, `upstreamDefaults`, or connector failsafe entries fails config validation at startup. **Failsafe entry matching (`matchMethod` + `matchFinality`).** Upstream-scope entries use a 4-tier priority (`SelectExecutor`-style scan in `upstream/upstream.go`): 1. Specific method + specific finality (highest priority) 2. Specific method, any finality 3. Wildcard method (`"*"`), specific finality 4. Wildcard method, any finality — catch-all (lowest priority) Within each tier, the first matching entry in config order wins. ([`upstream/upstream.go`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go)) **Network-scope** failsafe (including consensus) uses a simpler **first-match-in-config-order** scan on `matchMethod` + `matchFinality` + `matchCommitment`. Place specific commitment rules before broader ones. ([`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go)) `matchRequestKind` accepts `user` or `*`, both matching every client request: no eRPC-own request (tracker fetch, head poll, probe) goes through a failsafe policy, and `matchRequestKind: internal` is refused at load. **`matchFinality` valid values.** `finalized`, `unfinalized`, `realtime`, `unknown`. A value like `"latest"` is not a valid finality token and silently never matches any request. **`matchCommitment` valid values.** `none`, `processed`, `confirmed`, `finalized`. Empty = wildcard. On SVM it matches the commitment erpc pins on the wire: the caller's value, else the `svm.commitment` default that injection writes (clamped per method, e.g. `processed` becomes `confirmed` for `getBlock`), else `none`. Because the injected bytes are what the multiplexer and cache key on, two requests that share a key always take the same rule. A caller value outside the four levels (e.g. `recent`) matches no rule. Write methods (`sendTransaction`, `simulateTransaction`, `requestAirdrop`) are always `none`: their commitment field governs a preflight or simulation, not a read. Exact match only (no hierarchy). On non-SVM networks every request evaluates as `none`, so `matchCommitment: [none]` matches all of that traffic and any other level matches nothing. `getSignatureStatuses` matches an explicit caller commitment. eRPC does not inject `svm.commitment` for this method because older validators do not honor that field. Omitted commitment matches `none` and preserves the method's processed default. A matching policy does not prove that an upstream supports the requested commitment. **Defaults merge algorithm.** Each network failsafe entry inherits unset policy fields from the first default that matches method and finality and covers every commitment selected by the network entry. An omitted default `matchCommitment` covers all commitments. A network entry with omitted `matchCommitment` inherits only from an unrestricted default. If the network has no failsafe entries, the entire defaults array is copied. ([`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go)) **Network-scope timeout is lifecycle-scoped, not per-attempt.** A 500ms network timeout with `maxAttempts: 3` has a 500ms total budget shared across all 3 retry rounds. There is no per-attempt timeout at the network scope. **`retryEmpty` directive is the master gate** for all empty/missing-data retries. When off (`false`, the default), neither the network scope nor the upstream scope retries empty/missing-data results, and the empty-as-error conversion hook is also suppressed. ([`erpc/network_executor.go:L401-404`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L401-L404)) ### Worked examples **1. Standard production failsafe — latency-sensitive workload.** Adaptive p70 hedge fires after the method's p70 latency; network retries up to 5 times on errors; network timeout bounds the entire request lifecycle: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" timeout: duration: 30s retry: maxAttempts: 5 delay: 200ms backoffFactor: 1.5 backoffMaxDelay: 5s hedge: delay: quantile: 0.7 min: 100ms max: 2s maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", timeout: { duration: "30s" }, retry: { maxAttempts: 5, delay: "200ms", backoffFactor: 1.5, backoffMaxDelay: "5s", }, hedge: { delay: { quantile: 0.7, min: "100ms", max: "2s" }, maxCount: 1, }, }] ``` **2. Per-method finality tuning.** `eth_getLogs` on finalized data gets a longer timeout and more retries; all other finalized methods get a tighter budget: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs" matchFinality: [finalized] timeout: duration: 60s retry: maxAttempts: 5 - matchMethod: "*" matchFinality: [finalized] timeout: duration: 10s retry: maxAttempts: 3 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_getLogs", matchFinality: ["finalized"], timeout: { duration: "60s" }, retry: { maxAttempts: 5 }, }, { matchMethod: "*", matchFinality: ["finalized"], timeout: { duration: "10s" }, retry: { maxAttempts: 3 }, }, ] ``` **3. Upstream-scope circuit breaker.** Upstream-level failsafe adds an auto-healing circuit breaker; the network-level failsafe above still applies for retries and hedging: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" circuitBreaker: failureThresholdCount: 20 failureThresholdCapacity: 80 halfOpenAfter: 5m successThresholdCount: 8 successThresholdCapacity: 200 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", circuitBreaker: { failureThresholdCount: 20, failureThresholdCapacity: 80, halfOpenAfter: "5m", successThresholdCount: 8, successThresholdCapacity: 200, }, }] ``` ### Best practices - Place **circuit breakers at upstream scope only**; placing them at network scope causes `ErrFailsafeConfiguration` at startup. - Place **consensus at network scope only**; placing it at upstream scope fails config validation at startup. - Always use a **catch-all defaults entry** (`matchMethod: "*"`) in `networkDefaults.failsafe` so method-specific entries inherit the base policy without repeating every field. - The **network-scope timeout** wraps all retries and hedges — always set it shorter than `server.maxTimeout` (default 150s), or it will never fire on its own. - Stacking `upstreams[].failsafe[].retry.maxAttempts: 3` with `networks[].failsafe[].retry.maxAttempts: 3` can produce up to 9 upstream calls per request — size budgets accordingly. - `emptyResultMaxAttempts` (default 2) is a **shared counter across ALL network retry rounds**, not per-round. With default `maxAttempts=5`, empty-type retries are capped at 1 extra call total. - Enable `retryEmpty: true` in `directiveDefaults` (or per-request via `X-ERPC-Retry-Empty: true`) if you need missing-data retries — it is off by default. ### Edge cases & gotchas 1. `matchFinality: ["latest"]` silently never matches. Valid values: `finalized`, `unfinalized`, `realtime`, `unknown`. 2. `matchCommitment: ["recent"]` fails config validation. Valid values: `none`, `processed`, `confirmed`, `finalized`. An omitted commitment matches the `svm.commitment` default only when eRPC injects that default. SVM write methods, unpinned `getSignatureStatuses`, and methods without commitment injection match `none`. On non-SVM networks every request evaluates as `none`, so `matchCommitment: [none]` matches all of that traffic and any other level silently never matches. 3. Stacking upstream retry (`maxAttempts: 3`) with network retry (`maxAttempts: 3`) can produce up to 9 upstream calls per request. 4. Write methods are excluded from hedging, and the excluded set is per-architecture. **EVM**: `eth_sendTransaction` and the filter-creation methods; `eth_sendRawTransaction` is intentionally NOT excluded — it supports idempotent broadcast. **SVM**: `sendTransaction`, `sendRawTransaction`, and `requestAirdrop` are all excluded from hedging *and* from retry — so unlike EVM, an SVM raw-transaction broadcast is never hedged. `simulateTransaction` is read-only and stays hedgeable. See [the SVM write-method guard](/reference/errors.llms.txt#svm-write-method-guard). 5. `emptyResultMaxAttempts` is a shared counter across all network retry rounds, not per-round. With the default value of 2, one original attempt plus one empty-type retry fires — at most 1 empty-type retry across the entire request lifetime. 6. Consensus `ignoreFields` is a set-replacement, not a merge. Setting any entry replaces the entire built-in default map (which suppresses `blockTimestamp` disagreements for `eth_getLogs` and receipts methods). 7. The circuit breaker's rolling window must fill to `failureThresholdCapacity` (default 80) before it can trip — early-startup behavior is Closed regardless of error rate. 8. Scope mismatches abort startup before any request is served: a circuit breaker at network scope fails with `ErrFailsafeConfiguration`, and consensus at upstream scope fails config validation. 9. Failsafe defaults merge uses **wildcard method matching**, not exact match. A default entry with `matchMethod: "eth_*"` will provide defaults for any network entry whose method starts with `eth_`. A catch-all `matchMethod: "*"` is required to cover all entries uniformly. 10. On network-scope failsafe, put specific `matchCommitment` rules *before* a catch-all with omitted `matchCommitment`, or the catch-all wins first. 11. Defaults merge matches `matchMethod` + `matchFinality` and requires the default's `matchCommitment` to cover every commitment selected by the network entry. An omitted default matcher covers all commitments. A commitment-specific default cannot supply policies to a network catch-all. ### Observability | Metric | Type | When it fires | |--------|------|---------------| | `erpc_network_request_received_total` | counter | Every inbound request reaching the network executor | | `erpc_network_timeout_fired_total` | counter | Network-scope or upstream-scope failsafe timeout exceeded | | `erpc_network_retry_attempt_total` | counter | Every network-scope retry round that fires | | `erpc_network_hedged_request_total` | counter | Each hedge attempt fired | | `erpc_network_hedge_discards_total` | counter | Losing hedge response cancelled | | `erpc_upstream_breaker_state_change_total` | counter | Circuit breaker state transition (Closed/Open/HalfOpen) | | `erpc_consensus_misbehavior_detected_total` | counter | Upstream response differed from consensus group | ### Source code entry points - [`erpc/network_executor.go:L183-L203`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L183-L203) — executor composition: consensus / retry / hedge / sweep wiring - [`common/match.go:L18-L78`](https://github.com/erpc/erpc/blob/main/common/match.go#L18-L78) — `SelectExecutor` 4-tier failsafe entry selection by (matchMethod, matchFinality) - [`common/defaults.go:L1793-L1832`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1793-L1832) — failsafe entry merge algorithm (network scope) - [`common/defaults.go:L1621-L1672`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1621-L1672) — failsafe entry merge algorithm (upstream scope) - [`erpc/network_executor.go:L68-L73`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L68-L73) — circuit breaker network-scope rejection at startup - [`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go) — consensus upstream-scope rejection at config load (`UpstreamConfig.Validate`) - [`common/errors.go:L1573-L1584`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1573-L1584) — `ErrFailsafeConfiguration` type (startup-only) ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — rotate across upstreams with exponential backoff and jitter. - [Hedge](/config/failsafe/hedge.llms.txt) — speculative racing to cut tail latency. - [Timeout](/config/failsafe/timeout.llms.txt) — lifecycle-scoped and per-upstream time budgets. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — automatic upstream quarantine with self-healing. - [Consensus](/config/failsafe/consensus.llms.txt) — multi-upstream agreement with misbehavior punishment. - [Integrity](/config/failsafe/integrity.llms.txt) — EVM response validation to discard stale or malformed data. - [Rate limiters](/config/rate-limiters.llms.txt) — cap hedge and retry cost on expensive vendors. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — controls which upstream each failsafe attempt targets. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome this layer serves. --- --- # Circuit breaker > Source: https://docs.erpc.cloud/config/failsafe/circuit-breaker > When an upstream starts failing, eRPC stops sending it traffic automatically — and quietly brings it back once it recovers. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Circuit breaker A misbehaving upstream can drag every request down with it. The circuit breaker watches each upstream's recent outcomes and, the moment failures cross your threshold, cuts it out of rotation instantly — no wasted dials, no cascading timeouts. Traffic flows to healthy upstreams while the broken one sits on a cooldown, then eRPC probes it automatically and restores it once it proves it's back. At cache-connector scope the same machinery also covers slowness: a connector whose reads keep hitting their own failsafe timeout gets excluded and re-admitted automatically. **What you get** - Instant removal of failing upstreams — no transport dials while the breaker is open - Self-healing: automatic probe after a cooldown, automatic re-admission on success - Per-method granularity — `eth_getLogs` can trip without affecting `eth_call` - Zero user impact when other upstreams are healthy ## Quick taste Illustrative, not a tuned production config — trips after 20 failures in an 80-request window, probes after 5 minutes: **Config path:** `projects[].upstreams[].failsafe[].circuitBreaker` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: my-upstream endpoint: https://rpc.example.com failsafe: - matchMethod: "*" circuitBreaker: # trips after 20 failures in an 80-request window failureThresholdCount: 20 failureThresholdCapacity: 80 # probes after 5 minutes of cooldown halfOpenAfter: 5m successThresholdCount: 8 successThresholdCapacity: 200 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreams: [{ id: "my-upstream", endpoint: "https://rpc.example.com", failsafe: [{ matchMethod: "*", circuitBreaker: { // trips after 20 failures in an 80-request window failureThresholdCount: 20, failureThresholdCapacity: 80, // probes after 5 minutes of cooldown halfOpenAfter: "5m", successThresholdCount: 8, successThresholdCapacity: 200, }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add circuit breakers to protect against a flaky upstream** ```text One of my upstreams is intermittently returning 5xx errors and timing out, causing all my requests to slow down while eRPC waits for it. Add a circuit breaker to each upstream in my my eRPC config so the failing upstream is cut out of rotation automatically after a burst of errors and only re-admitted after a cooldown probe. Explain the failure-threshold and half-open settings you chose. Read the full reference first: https://docs.erpc.cloud/config/failsafe/circuit-breaker.llms.txt ``` **Prompt Example #2: tune existing circuit breaker thresholds** ```text Audit the circuitBreaker settings on all upstreams in my eRPC config. For each one, tell me whether the failureThresholdCapacity window is large enough to avoid false trips on transient blips, whether halfOpenAfter is longer than a typical upstream restart, and whether the successThresholdCapacity default of 200 (not 10 — there is a known dead-code bug) is appropriate for my traffic volume. Suggest concrete numbers with reasoning. Reference: https://docs.erpc.cloud/config/failsafe/circuit-breaker.llms.txt ``` **Prompt Example #3: add method-specific breaker for heavy archive queries** ```text I have an upstream that handles both lightweight eth_call requests and expensive eth_getLogs archive queries. When it gets overloaded by getLogs it returns errors, but I don't want that to trip the breaker for all methods. Configure separate circuit breaker entries in my eRPC config: a tighter one for eth_getLogs and a more conservative catch-all for everything else. Reference: https://docs.erpc.cloud/config/failsafe/circuit-breaker.llms.txt ``` **Prompt Example #4: debug why an upstream keeps flapping open/closed** ```text My eRPC logs show repeated circuit breaker transitions: closed_to_open followed immediately by half_open_to_open on the same upstream, cycling every minute or two. Explain what causes this flapping pattern and what I should change in the circuitBreaker config in my eRPC config to stop it without making the breaker too slow to trip. Reference: https://docs.erpc.cloud/config/failsafe/circuit-breaker.llms.txt ``` **Prompt Example #5: fan out one circuit breaker config across all upstream failsafe entries** ```text My upstreams have multiple method-specific failsafe blocks (different timeouts per method). I want to apply the same circuit breaker config to every one of those blocks so CB protection is uniform regardless of which method trips a failure. Show me how to do this cleanly in TypeScript config format for my eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/circuit-breaker.llms.txt ``` --- ### Circuit breaker — full agent reference ### How it works **State machine.** The breaker is a per-upstream in-process state machine with three states: ``` Closed --[ failures >= failureThresholdCount, after window fills ]--> Open Open --[ time.Since(openedAt) >= halfOpenAfter, on TryAcquirePermit ]--> HalfOpen HalfOpen --[ halfOpenSuccess >= successThresholdCount, after trial fills ]--> Closed HalfOpen --[ any failure OR trial fills but successCount < threshold ]--> Open (openedAt reset) ``` **Closed state — ring-buffer window.** The breaker maintains a circular ring buffer of the last `failureThresholdCapacity` outcomes (success or failure). The buffer is pre-allocated at construction with capacity `max(failureThresholdCapacity, failureThresholdCount, 1)`. [`failsafe/breaker.go:L107-125`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L107-L125) The open condition is evaluated only once the buffer is full: if `failures >= failureThresholdCount`, the breaker trips to Open and records `openedAt = time.Now()`. [`failsafe/breaker.go:L292-312`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L292-L312) **Open state.** While Open, every call to `TryAcquirePermit()` returns false immediately — no transport dial occurs, no timeout ticks. The upstream returns `ErrFailsafeCircuitBreakerOpen` instantly. After `halfOpenAfter` has elapsed, the next incoming request transitions the breaker to HalfOpen and is allowed through as a probe. [`failsafe/breaker.go:L158-176`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L158-L176) **HalfOpen state.** Up to `max(successThresholdCapacity, successThresholdCount, 1)` concurrent trial permits are issued (tracked via `halfOpenInflight`). When `halfOpenSuccess + halfOpenFailure >= successThresholdCapacity` (trial window full), the breaker closes if `successThresholdCount` successes were recorded; otherwise it re-opens and `openedAt` resets. A single failure in HalfOpen re-opens immediately without waiting for the window to fill. Ignored outcomes (`OutcomeIgnore`) move neither trial counter but still release the permit the attempt consumed — see `Record` below. [`failsafe/breaker.go:L233-250`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L233-L250) **`TryAcquirePermit()` per-state logic.** [`failsafe/breaker.go:L139-176`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L139-L176) - **StateClosed**: always returns `true` immediately (atomic load, no lock needed). - **StateHalfOpen**: acquires `mu`, re-checks state (race guard), computes `cap = max(successThresholdCapacity, successThresholdCount, 1)`, returns `halfOpenInflight < cap`; if permitted, increments `halfOpenInflight`. - **StateOpen**: acquires `mu`, re-checks state (race guard with one level of recursive re-evaluation if another goroutine races to HalfOpen first), checks `time.Since(openedAt) >= halfOpenAfter`; if elapsed → transitions to HalfOpen, sets `halfOpenInflight = 1`, returns `true`; otherwise returns `false`. **`Record(outcome)` per-state logic.** [`failsafe/breaker.go:L178-260`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L178-L260) - **OutcomeIgnore**: moves no thresholds and no lifetime counters, but in HalfOpen it releases the trial permit the attempt consumed in `TryAcquirePermit` (decrements `halfOpenInflight`). Without the release, a run of ignored outcomes (cache misses, canceled attempts) would pin `halfOpenInflight` at capacity — wedging the breaker in HalfOpen forever with no path back to Closed. [`failsafe/breaker.go:L178-195`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L178-L195) - **StateClosed**: calls `pushLocked(isFailure)`, increments lifetime counters, calls `checkOpenLocked()` which opens if `b.count >= failCap && b.failures >= failCount`. - **StateHalfOpen**: decrements `halfOpenInflight`, increments trial success/failure counter. Two paths: (a) if `halfOpenSuccess + halfOpenFailure >= successCap` (trial window full), sufficient successes → `resetWindowLocked(); transitionLocked(Closed)`, insufficient → re-opens; (b) if `OutcomeFailure` and `halfOpenFailure > 0` → immediately re-opens even if the window is not yet full. - **StateOpen**: only increments lifetime counters (should not normally be reached because the caller should not have bypassed `TryAcquirePermit`). **What counts as a failure.** The `upstreamBreakerOutcome` function classifies each completed attempt from its (response, error) pair: [`upstream/upstream_executor.go:L391-421`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L391-L421) - **OutcomeFailure**: `ErrCodeEndpointServerSideException` (5xx), `ErrCodeEndpointTransportFailure`, `ErrCodeEndpointUnauthorized`, `ErrCodeEndpointBillingIssue`, and a syncing upstream that returns an empty/null response (`EvmSyncingStateSyncing && resp.IsResultEmptyish()`). - **OutcomeIgnore**: request-canceled, request-skipped, rate-limit errors, timeout errors, client-side errors, hedge cancellations — these do not affect the window. - **OutcomeSuccess**: all non-error, non-syncing-empty responses. **What bypasses the breaker entirely.** Hedge attempts (`isHedge == true`), internal state-poller, chain-id and state probes and subscription calls (`req.UpstreamPolicies()` is `TimeoutOnly` or `HeadAsk`), and composite batch fan-out sub-requests (`req.IsCompositeRequest()`) all skip `TryAcquirePermit` and `Record`. **Chain tracker fetches.** The headers, receipts and logs the chain tracker fetches skip upstreams whose breaker is open, and their outcomes never feed any breaker: a tracker fetch neither probes a half-open upstream nor opens a breaker on a failure. [`upstream/upstream_executor.go:L368-385`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L368-L385) **Interaction with routing.** When the breaker refuses a permit, it returns `ErrFailsafeCircuitBreakerOpen`. This error is not retryable towards the same upstream (`IsRetryableTowardsUpstream = false`) but is retryable at the network level — the routing loop tries the next upstream transparently. [`common/errors.go:L2458-2459`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2458-L2459) **Relationship with selection policy.** The circuit breaker and the [selection policy](/config/projects/selection-policies.llms.txt) are complementary, not redundant. The selection policy excludes upstreams based on rolling health metrics computed across all requests. The circuit breaker acts at the individual-request level: it blocks transport dials when it already knows the upstream is failing, based on its own ring buffer. An upstream can be simultaneously excluded by the selection policy AND have an open circuit breaker; both independently prevent traffic. Cordoning is a third orthogonal mechanism: an operator-driven sticky flag that keeps an upstream out of rotation regardless of metrics or breaker state. **Cache connector breaker.** Cache connectors have their own circuit breaker via `FailsafeConnector`. The outcome classifier (`breakerOutcome`) is different: attempts interrupted by the parent context (hedge sibling won, client disconnect, parent deadline) are `OutcomeIgnore` — they carry no signal about the connector. The executor's **own timeout expiry is `OutcomeFailure`**: on a best-effort layer a read the timeout had to kill is pure tax (the caller pays the wait AND falls through to upstreams anyway), so sustained timeouts open the breaker and exclude the connector — cache reads fail fast — until a half-open probe completes in time again. The timeout policy is the sole definition of "too slow"; there is no separate slowness threshold, and with a [quantile timeout](/config/failsafe/timeout.llms.txt) the slow-line adapts to the connector's own recent latency. Otherwise transport errors are `OutcomeFailure`; cache misses (`RecordNotFound`) are `OutcomeIgnore`; success is `OutcomeSuccess`. The error produced uses scope `"connector"` rather than `"upstream"`. [`data/cache_executor.go:L279-309`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L279-L309) The `isTransportError` helper (used by the cache breaker outcome classifier) matches: `ErrCodeEndpointTransportFailure`; `net.Error` with `Timeout()`; `io.EOF`, `io.ErrUnexpectedEOF`, `syscall.ECONNREFUSED`, `syscall.ECONNRESET`, `syscall.EPIPE`, `syscall.ETIMEDOUT`; gRPC codes `Unavailable`, `DeadlineExceeded`, `Aborted`; and string substrings: `"connection refused"`, `"connection reset"`, `"broken pipe"`, `"no such host"`, `"network is unreachable"`, `"tls handshake"`, `"i/o timeout"`, `"operation timed out"`, `"use of closed network connection"`, `"client is closed"`, `"unexpectedly closed"`, `"goaway"`, `"clusterdown"`, `"masterdown"`, `"tryagain"`, `"redis is loading"`. [`data/failsafe.go:L21-92`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L21-L92) **Window reset.** Both Closed→Open tripping and HalfOpen→Closed recovery call `resetWindowLocked()` — every cycle starts with a fresh ring buffer. [`failsafe/breaker.go:L314-322`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L314-L322) **Scope.** The circuit breaker is valid at upstream `failsafe` scope and at cache-connector `failsafeForGets` / `failsafeForSets` scope. Setting `circuitBreaker` inside a **network-level** `failsafe` block causes `NewNetworkExecutor` to return `ErrFailsafeConfiguration` and eRPC will not start. [`erpc/network_executor.go:L71-76`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L71-L76) ### Config schema All fields live under `upstreams[*].failsafe[*].circuitBreaker` — or, for cache connectors, `database.*.connectors[*].failsafeForGets[*].circuitBreaker` / `failsafeForSets[*].circuitBreaker`. Config struct: [`common/config.go:L1594-1600`](https://github.com/erpc/erpc/blob/main/common/config.go#L1594-L1600). Defaults: [`common/defaults.go:L2833-2877`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2833-L2877). | Field | Type | Default | Footguns | |---|---|---|---| | `failureThresholdCount` | `uint` | `20` ([`common/defaults.go:L2834-L2840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2834-L2840)) | Must be `<= failureThresholdCapacity`; validated at [`common/validation.go:L1044-L1048`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1044-L1048). The window must fill to `failureThresholdCapacity` before this count is checked. | | `failureThresholdCapacity` | `uint` | `80` ([`common/defaults.go:L2841-L2847`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2841-L2847)) | Ring buffer size. The breaker does not evaluate the open condition until exactly this many outcomes are recorded since last reset. | | `halfOpenAfter` | `Duration` | `5m` ([`common/defaults.go:L2855-L2861`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2855-L2861)) | Required at validation (`common/validation.go:L1038-L1040`). Time the breaker stays Open before permitting a probe. Resets to `time.Now()` on every HalfOpen failure. | | `successThresholdCount` | `uint` | `8` ([`common/defaults.go:L2862-L2868`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2862-L2868)) | Must be `<= successThresholdCapacity`. Successes required in the HalfOpen trial window to re-close. | | `successThresholdCapacity` | `uint` | **`200`** ([`common/defaults.go:L2848-L2854`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2848-L2854)) — **known dead-code bug**: a second identical `if c.SuccessThresholdCapacity == 0` guard at L2869-L2875 would set `10` but is unreachable because the first guard already assigned `200`. Effective default is `200`, not `10`. | HalfOpen trial window size; also caps concurrent permits in HalfOpen. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Fast-trip breaker for a chain with hot-baseline upstreams (production pattern).** On chains where upstreams sit at high baseline load and even 50% error rate for 30 requests signals something is genuinely broken, trip fast and probe quickly. This is the pattern deployed for Cronos upstreams after a 5.77M upstream call spiral caused by a single user burst — cut broken upstreams out of rotation in under a second of traffic, probe after 30s: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" circuitBreaker: # trip at 50% error rate: 15 failures in a 30-request window # window is small so a stuck upstream pegs within ~1s of traffic failureThresholdCount: 15 failureThresholdCapacity: 30 # 30s: long enough to avoid thrashing, short enough to restore # the upstream quickly during a transient vendor outage halfOpenAfter: 30s # require 60% success in half-open before re-closing (3 of 5) successThresholdCount: 3 # keep trial window small so re-admission decision is fast successThresholdCapacity: 5 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", circuitBreaker: { // trip at 50% error rate: 15 failures in a 30-request window // window is small so a stuck upstream pegs within ~1s of traffic failureThresholdCount: 15, failureThresholdCapacity: 30, // 30s: long enough to avoid thrashing, short enough to restore // the upstream quickly during a transient vendor outage halfOpenAfter: "30s", // require 60% success in half-open before re-closing (3 of 5) successThresholdCount: 3, // keep trial window small so re-admission decision is fast successThresholdCapacity: 5, }, }] ``` **2. Fan out one circuit breaker config across all method-specific upstream failsafe blocks (TypeScript pattern).** When an upstream has per-method failsafe entries (different timeouts per method), each entry needs the circuit breaker attached independently — the upstream-level `SetDefaults` rule only preserves blocks explicitly listed. Spreading a shared breaker object across all entries is the clean way to ensure coverage without repeating the block manually: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml # YAML: repeat the circuitBreaker block on every method-specific entry failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" timeout: { duration: 15s } circuitBreaker: failureThresholdCount: 15 failureThresholdCapacity: 30 halfOpenAfter: 30s successThresholdCount: 3 successThresholdCapacity: 5 - matchMethod: "*" circuitBreaker: failureThresholdCount: 15 failureThresholdCapacity: 30 halfOpenAfter: 30s successThresholdCount: 3 successThresholdCapacity: 5 ``` **TypeScript — `erpc.ts`:** ```typescript // TypeScript: define the breaker once, spread it across all entries const sharedBreaker = { failureThresholdCount: 15, failureThresholdCapacity: 30, halfOpenAfter: "30s", successThresholdCount: 3, successThresholdCapacity: 5, }; // sharedUpstreamFailsafe is your array of method-specific timeout blocks const upstreamFailsafe = sharedUpstreamFailsafe.map((fs) => ({ ...fs, circuitBreaker: sharedBreaker, })); ``` **3. Conservative production config — tolerates transient blips.** For stable chains where upstreams have rare failures, a larger window prevents false trips while still protecting against hard outages. Use this as the starting point for any chain that does not show the hot-baseline pattern: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" circuitBreaker: # window must fill to 80 before the trip condition is evaluated at all failureThresholdCount: 20 failureThresholdCapacity: 80 # 5 min: upstream needs time to restart cleanly halfOpenAfter: 5m # 8 successes out of 200 trial slots — loose, but default of 200 is # intentional (the successThresholdCapacity=10 block in SetDefaults is # unreachable dead code; effective default is 200) successThresholdCount: 8 successThresholdCapacity: 200 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", circuitBreaker: { // window must fill to 80 before the trip condition is evaluated at all failureThresholdCount: 20, failureThresholdCapacity: 80, // 5 min: upstream needs time to restart cleanly halfOpenAfter: "5m", // 8 successes out of 200 trial slots — loose, but default of 200 is // intentional (successThresholdCapacity=10 block in SetDefaults is dead code) successThresholdCount: 8, successThresholdCapacity: 200, }, }] ``` **4. Method-specific breaker for heavy archive queries.** `eth_getLogs` and `eth_getBlockReceipts` fail sooner on overloaded nodes than lightweight calls. A tighter breaker on these methods cuts them off quickly without affecting `eth_call` or block getters, which may still be healthy on the same node: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" circuitBreaker: # small window: heavy queries fail fast when the node is overloaded failureThresholdCount: 5 failureThresholdCapacity: 20 halfOpenAfter: 2m successThresholdCount: 3 successThresholdCapacity: 10 # catch-all: conservative for lightweight methods that are usually healthy - matchMethod: "*" circuitBreaker: failureThresholdCount: 20 failureThresholdCapacity: 80 halfOpenAfter: 5m successThresholdCount: 8 successThresholdCapacity: 200 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", circuitBreaker: { // small window: heavy queries fail fast when the node is overloaded failureThresholdCount: 5, failureThresholdCapacity: 20, halfOpenAfter: "2m", successThresholdCount: 3, successThresholdCapacity: 10, }, }, { matchMethod: "*", circuitBreaker: { failureThresholdCount: 20, failureThresholdCapacity: 80, halfOpenAfter: "5m", successThresholdCount: 8, successThresholdCapacity: 200, }, }, ] ``` **5. Tight HalfOpen trial — recover quickly or re-open fast.** When you have many upstream options and want to minimize time spent probing a still-sick upstream, shrink the trial window and require a high success ratio. This pairs well with the fast-trip breaker above: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" circuitBreaker: failureThresholdCount: 10 failureThresholdCapacity: 40 halfOpenAfter: 1m # 5 of 6 = 83% success required: re-open immediately if not healthy successThresholdCount: 5 successThresholdCapacity: 6 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", circuitBreaker: { failureThresholdCount: 10, failureThresholdCapacity: 40, halfOpenAfter: "1m", // 5 of 6 = 83% success required: re-open immediately if not healthy successThresholdCount: 5, successThresholdCapacity: 6, }, }] ``` ### Request/response behavior - While Open, `TryAcquirePermit()` returns false immediately — the upstream returns `ErrFailsafeCircuitBreakerOpen` with scope `"upstream"` without dialing the transport. [`common/errors.go:L1665-1692`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1665-L1692) - The error code `ErrCodeFailsafeCircuitBreakerOpen` is non-retryable towards the same upstream (`IsRetryableTowardsUpstream = false`) but IS retryable at the network level (`IsRetryableTowardNetwork = true` — the default, since the error does not set the `retryableTowardNetwork=false` detail field). The network routing loop therefore tries the next upstream; if all upstreams are open the aggregated error includes the count `"N upstream circuit breaker open"`. [`common/errors.go:L1054-1055`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1054-L1055) - `erpc_upstream_attempt_outcome_total` records `outcome="breaker_open"` for each refused permit. The client sees the upstream failure only if ALL upstreams are exhausted. - The `CircuitBreakerState()` accessor on `Upstream` surfaces only the catch-all (`matchMethod: "*"`, no finality filter) breaker for the admin UI and simulator panel. [`upstream/upstream.go:L320-333`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L320-L333) ### Best practices - **Let the window fill before worrying.** The breaker cannot trip until `failureThresholdCapacity` outcomes are recorded. With the default capacity of 80, a freshly restarted upstream takes at least 80 requests before any trip can occur. Reduce capacity if you need faster detection. - **Set `halfOpenAfter` longer than the upstream's actual restart time.** If the cooldown is shorter than the upstream's recovery, the HalfOpen probe will fail immediately, re-open the breaker, and start another 5-minute wait — flapping. Monitor `erpc_upstream_breaker_state_change_total{transition="half_open_to_open"}` to detect this. - **Use method-specific breakers for heavy queries.** Archive calls like `eth_getLogs` fail sooner on overloaded nodes than lightweight calls. Separate breakers prevent a log-heavy spike from taking your whole upstream out of rotation for everything else. - **The circuit breaker does not replace the selection policy.** The selection policy removes upstreams from the ordered list proactively (before they fail); the circuit breaker blocks in-progress requests reactively. Use both: selection policy removes degraded upstreams before they accumulate failures; circuit breaker handles sudden hard failures. - **Do not put `circuitBreaker` at network scope.** It will cause a startup error. The breaker is upstream-scoped by design — tripping it at the network level would block all upstreams simultaneously. - **Hedge attempts are invisible to the breaker.** A hedge that gets a 5xx does not increment the failure window. Only primary (non-hedge) attempts count. This is intentional to avoid penalizing upstreams for aggressive hedging behavior. - **Watch the `successThresholdCapacity` default (200, not 10).** Due to a known dead-code bug in `SetDefaults`, the effective default is 200 — the HalfOpen trial window accepts up to 200 concurrent probes before evaluating. If you need faster re-close decisions, set it explicitly. ### Edge cases & gotchas 1. **Window must be full before tripping.** `failureThresholdCapacity: 80, failureThresholdCount: 1` will NOT trip until 80 outcomes are in the buffer — even if the first 79 were failures. `checkOpenLocked` short-circuits with `if b.count < failCap { return }`. [`failsafe/breaker.go:L304-306`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L304-L306) 2. **`successThresholdCapacity` effective default is `200`, not `10` — the second defaults block is unreachable dead code.** `SetDefaults` at [`common/defaults.go:L2848-L2875`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2848-L2875) contains two `if c.SuccessThresholdCapacity == 0` guards. The first (L2848-L2854) sets `200`; the second (L2869-L2875, which would set `10`) is never reached. Effective default is `200`. 3. **Single HalfOpen failure re-opens immediately.** Even before the trial window is full, any `OutcomeFailure` in HalfOpen re-opens and resets `openedAt`. Ensure `halfOpenAfter` is long enough for the upstream to actually recover or flapping will occur. [`failsafe/breaker.go:L244-250`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L244-L250) 4. **Hedge attempts are invisible to the breaker.** A hedge attempt that gets a 500 from the upstream does not count as a failure. Only the primary (non-hedge) attempt counts. This is intentional to avoid penalizing upstreams for aggressive hedging. 5. **Internal probe calls bypass the breaker in both directions.** State-poller probes (`req.UpstreamPolicies()` is `TimeoutOnly` or `HeadAsk`) neither block on an open breaker nor record outcomes. An Open upstream will receive internal probes but no user traffic and no chain tracker fetches. 6. **`circuitBreaker` at network scope causes startup failure.** Even `circuitBreaker: {}` in a network `failsafe` block causes `NewNetworkExecutor` to return an error and eRPC will not start. [`erpc/network_executor.go:L68-73`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L68-L73) 7. **Per-method breakers are independent.** `CircuitBreakerState()` on `Upstream` only exposes the `matchMethod: "*"` catch-all breaker. An `eth_getLogs` breaker tripping does not affect the `*` catch-all breaker. 8. **EVM syncing state triggers a failure.** A syncing upstream that returns an empty/null response is classified as `OutcomeFailure` — a syncing node can trip the breaker even without an error code. [`upstream/upstream_executor.go:L436-444`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L436-L444) 9. **Window reset on every open/close.** Both tripping Closed→Open and closing HalfOpen→Closed call `resetWindowLocked()` — a flapping upstream starts each cycle with a clean slate. 10. **Cordon and circuit breaker are orthogonal.** A cordoned upstream also has its circuit breaker checked (if configured). An uncordon does not reset the breaker. 11. **`OnTransition` fires in a goroutine.** The metric increment is async. Under extremely high test parallelism this can appear as a missing metric increment immediately after a transition. [`failsafe/breaker.go:L324-346`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L324-L346) 12. **Cache connector breakers do not emit the state-change metric.** The `OnTransition` hook is not wired for cache executors — `erpc_upstream_breaker_state_change_total` only fires for upstream breakers. 13. **Race safety in Open→HalfOpen.** When two goroutines race to call `TryAcquirePermit` while the breaker is Open and `halfOpenAfter` has just elapsed, the second goroutine re-checks state after acquiring `mu` and, seeing HalfOpen, recursively re-evaluates — bounded to one extra call. No double-transition is possible. [`failsafe/breaker.go:L160-166`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L160-L166) 14. **`halfOpenAfter` is required at validation, but `SetDefaults` fills it.** `Validate()` errors with `"failsafe.circuitBreaker.halfOpenAfter is required"` if the field is zero. In practice eRPC's config loading calls `SetDefaults` (which fills `5m`) before `Validate`, so omitting the field from YAML is safe. If you call `Validate` before `SetDefaults` in custom tooling, the zero value will be rejected. [`common/validation.go:L1038-L1040`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1038-L1040) 15. **Own-timeouts are failures at connector scope only.** A cache read the executor's own failsafe timeout had to kill is classified `OutcomeFailure` — on a best-effort layer it is pure tax (the caller pays the wait and falls through to upstreams anyway). Sustained timeouts open the breaker: the connector is excluded — cache reads fail fast — until a half-open probe completes in time and re-admits it. The timeout policy is the sole definition of "too slow"; there is no separate slowness threshold. At upstream scope timeout errors remain `OutcomeIgnore`: benching capacity is the selection policy's job, and upstream slowness already feeds scoring. Attempts that did not complete on their own never count at either scope: interrupted / canceled / skipped attempts are ignored — their duration reflects the canceller, not the target. [`data/cache_executor.go:L292-309`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L292-L309), [`upstream/upstream_executor.go:L399-414`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L399-L414) 16. **Ignored outcomes release HalfOpen trial permits.** `Record(OutcomeIgnore)` moves no thresholds but decrements `halfOpenInflight` when the breaker is HalfOpen. Without the release, a run of ignored outcomes (e.g. cache misses during a probe window) would pin the trial budget at capacity and wedge the breaker in HalfOpen forever — rejecting all traffic with no path back to Closed. [`failsafe/breaker.go:L178-195`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L178-L195) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_breaker_state_change_total` | Counter | `project`, `upstream`, `transition` | Every upstream breaker state transition. `transition` values: `closed_to_open`, `open_to_half_open`, `half_open_to_closed`, `half_open_to_open`. Not emitted for cache connector breakers. Defined at [`telemetry/metrics.go:L485-L489`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L485-L489); wired at [`upstream/upstream.go:L91-L99`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L91-L99). | | `erpc_upstream_attempt_outcome_total` | Counter | `project`, `network`, `upstream`, `category`, `outcome`, `is_hedge`, `is_retry`, `finality` | Every attempt terminal. `outcome="breaker_open"` when the breaker refused a permit. Defined at [`telemetry/metrics.go:L457-L462`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L457-L462); incremented at [`upstream/upstream.go:L551-L560`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L551-L560). | **Programmatic access.** The breaker exposes a `Metrics()` method that returns `(failures, successes, executions uint64)` as lifetime atomic counters. [`failsafe/breaker.go:L357-361`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L357-L361) These are not surfaced as Prometheus gauges — use the counters above for dashboards. **Log messages.** On every state transition, `transitionLocked` emits a `WARN`-level log: ``` {"level":"warn","from":"closed","to":"open","reason":"failure_threshold","executions":N,"successes":N,"failures":N,"message":"circuit breaker state changed"} ``` Reason strings: `"failure_threshold"` (Closed→Open), `"half_open_delay_elapsed"` (Open→HalfOpen), `"half_open_success_threshold"` (HalfOpen→Closed), `"half_open_failure"` (HalfOpen→Open). ### Source code entry points - [`failsafe/breaker.go`](https://github.com/erpc/erpc/blob/main/failsafe/breaker.go#L107) — self-contained circuit breaker state machine: ring buffer, `TryAcquirePermit`, `Record`, `transitionLocked`, `OnTransition` hook, `State`/`Metrics` accessors - [`upstream/upstream_executor.go:L352-L429`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L352-L429) — `callBreakerWithTimeout` wrapper; `upstreamBreakerEligible` and `upstreamBreakerOutcome` classifiers - [`upstream/upstream.go:L87-L99`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L87-L99) — `makeBreakerTransitionHook` wires `OnTransition` to the Prometheus counter; `classifyUpstreamOutcome` maps `ErrCodeFailsafeCircuitBreakerOpen` to `UpstreamOutcomeBreakerOpen` - [`data/cache_executor.go:L279-L309`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L279-L309) — `breakerOutcome` classifier for cache connector breakers: interrupted/own-timeout/transport/miss classification - [`data/failsafe.go:L21-L160`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L21-L160) — `FailsafeConnector` wrapper for cache connectors; `isTransportError` helper - [`common/config.go:L1594-L1609`](https://github.com/erpc/erpc/blob/main/common/config.go#L1594-L1609) — `CircuitBreakerPolicyConfig` struct and `Copy()` - [`common/defaults.go:L2833-L2877`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2833-L2877) — `CircuitBreakerPolicyConfig.SetDefaults()` including the double-assignment dead-code bug at L2869-L2875 - [`common/validation.go:L1209-L1232`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1209-L1232) — `CircuitBreakerPolicyConfig.Validate()` with all field constraints - [`common/errors.go:L1665-L1703`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1665-L1703) — `ErrFailsafeCircuitBreakerOpen` type, constructor, and `DeepestMessage` - [`common/errors.go:L2455-L2459`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2455-L2459) — `IsRetryableTowardsUpstream`: `ErrCodeFailsafeCircuitBreakerOpen` → not upstream-retryable - [`telemetry/metrics.go:L482-L489`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L482-L489) — `MetricUpstreamBreakerStateChange` counter definition - [`erpc/network_executor.go:L71-L76`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L71-L76) — enforces network-scope restriction (all circuit breakers rejected at network level) - [`erpc/networks_skip_test.go:L174-L262`](https://github.com/erpc/erpc/blob/main/erpc/networks_skip_test.go#L174-L262) — integration test confirming breaker-open causes rotation to next upstream without dialing the failing one - [`erpc/networks_test.go:L6088-L6521`](https://github.com/erpc/erpc/blob/main/erpc/networks_test.go#L6088-L6521) — integration tests for threshold tripping, half-open recovery, and full open/close cycle ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — retry attempts are not blocked by an open breaker; the routing loop tries the next upstream instead. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds individual request attempts from outside the breaker. - [Hedge](/config/failsafe/hedge.llms.txt) — hedge attempts bypass the breaker and do not record outcomes. - [Selection policies](/config/projects/selection-policies.llms.txt) — proactively removes degraded upstreams before they accumulate breaker failures. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the end-to-end outcome this feature serves. --- --- # Consensus policies > Source: https://docs.erpc.cloud/config/failsafe/consensus-policies > Pick a named consensus rule-set per request with a pre-round JS selector — strategy-gated historical serving, availability fallback, and MissingData waivers — always failing closed to the strictest policy. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Consensus policies A single consensus rule-set can't fit every request. A tx-hash lookup, a ten-million-block-old `eth_getBalance`, and a live `eth_getLogs` all want different quorums — but you don't want to fork your routing to get there, and you never want a looser rule-set to slip in by accident. Consensus policies let you name several `ConsensusPolicyConfig` blocks and pick one **per request** with a small JS function that runs before fan-out. Every failure — a throw, a timeout, an unknown name, a null return — falls **closed** to the strictest policy you designate. **What you get** - Named consensus policies, each a full consensus config, selected per request - A pre-round `customPolicy.evalFunction` with the verified caller, the request, and live upstream health/availability in scope - Strategy-gated integrity grades (e.g. historical serving only for callers on a named auth strategy) — never client headers - Automatic availability fallback that an attacker cannot force: punishment and operator cordons pin the request to the strictest policy - A `MissingData` waiver that releases an internal quota when at least `minAgreement` matching participants abstained with MissingData (sibling empties/unrelated errors do not block) - Fail-closed by construction: eval error, timeout, or unknown name → the default policy, always - An `X-ERPC-Consensus-Policy` response header and a `consensus_policy` metric label so you can see which grade served each round ## Quick taste Illustrative, not a tuned production config — two named policies and a selector that upgrades authorized callers to a MissingData-waiving policy for tx-hash lookups, and fails closed to `standard` for everyone else: **Config path:** `projects[].networks[].failsafe[].consensus` **YAML — `erpc.yaml`:** ```yaml consensus: # the inline block IS the strict default policy — the round falls back to it # whenever the selector returns null/unknown, or the eval errors or times out. # It must be a complete, valid consensus config on its own. maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1 } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } # each value under policies is a full consensus config policies: standard: # default / fail-closed — no waiver maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1 } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } standard-waive-missing: # same composition; waiver on internals only maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1, waiveAgreementOnMissingData: true } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } customPolicy: evalTimeout: 50ms evalFunction: | (ctx) => { if (ctx.upstreams.anyPunished()) return "standard" if (ctx.user?.auth === "consensus-waive" && ctx.request.blockNumber === null) return "standard-waive-missing" return "standard" } ``` **TypeScript — `erpc.ts`:** ```typescript consensus: { // the inline block IS the strict default policy — the round falls back to it // whenever the selector returns null/unknown, or the eval errors or times out. // It must be a complete, valid consensus config on its own. maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1 }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], // each value under policies is a full consensus config policies: { standard: { // default / fail-closed — no waiver maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1 }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], }, "standard-waive-missing": { // same composition; waiver on internals only maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1, waiveAgreementOnMissingData: true }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], }, }, customPolicy: { evalTimeout: "50ms", evalFunction: \`(ctx) => { if (ctx.upstreams.anyPunished()) return "standard" if (ctx.user?.auth === "consensus-waive" && ctx.request.blockNumber === null) return "standard-waive-missing" return "standard" }\`, }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add strategy-gated historical serving** ```text I want authorized callers (JWT role "brp:historical") to be able to read very old blocks that our internal archive nodes have pruned, while everyone else stays on our strict internal+external consensus. Set up eRPC named consensus policies with a pre-round customPolicy selector, failing closed to the strictest policy for everyone else. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/failsafe/consensus-policies.llms.txt ``` **Prompt Example #2: fall back to externals when internals are down (but not when punished)** ```text When our preferred upstreams are genuinely unavailable (unhealthy or availability-cordoned), I want requests to fall back to a looser consensus policy — but ONLY for an authorized role, and NEVER when a node was cordoned for misbehavior or by an operator. Set this up with eRPC consensus policies + a customPolicy selector. Reference: https://docs.erpc.cloud/config/failsafe/consensus-policies.llms.txt ``` **Prompt Example #3: waive the internal quota on missing-data** ```text Our internal archive nodes sometimes return a missing-data error for pruned state, which currently causes a consensus composition dispute even though the external nodes agree. Add a MissingData waiver so the internal quota is released when at least minAgreement internals returned missing-data (aligned with that quota), kept honest by a never-waivable external floor. Reference: https://docs.erpc.cloud/config/failsafe/consensus-policies.llms.txt ``` --- ### Consensus policies — full agent reference ### How it works **One round, one policy, chosen before fan-out.** A request's consensus round runs under exactly one named `ConsensusPolicyConfig`. Before the round starts, a pre-round selector answers a single question — *which named policy should govern this round?* — from the verified caller, the request, and the candidate upstreams' live health. The selector never sees round outcomes and never grades a round; that stays in the declarative consensus config and the executor. **Request flow.** (1) Auth resolves the user and stamps the authenticating strategy's name. (2) An `EvalContext` is built from the request, user, and candidate upstreams. (3) `selector.Evaluate(ctx, evalTimeout)` returns a policy name. (4) The name resolves to a `ConsensusPolicyConfig` — an unknown name resolves to the default policy; an empty/null return is a selector failure that also fails closed to the default. (5) The existing executor runs the round under that config, unchanged. (6) The chosen name is emitted as the `X-ERPC-Consensus-Policy` response header and the `consensus_policy` metric label. **Backward compatible.** An inline `consensus:` block with no `policies` map and no `customPolicy` is exactly one anonymous default policy — zero migration, every existing field keeps working. `customPolicy` and `policies` are purely additive. **Fail closed, always.** The default policy is the fail-closed target and **must be configured as the strictest policy** (the design assumes `standard`). Every selector failure resolves to it and is counted (and rate-limit-logged): a JS throw, a non-string return, a null/undefined return, an eval that overruns `evalTimeout`, or an unknown returned name. A null return is **not** an intentional default pick — return the string `"default"` to select the default deliberately. At pool capacity the selector waits for a free VM and that wait is charged to the same timeout — there is no separate `pool_exhausted` bypass. The selector can never fall *open* to a more permissive policy. **Selector engine.** The engine is a standalone package that imports nothing from `consensus/`, `health/`, or `auth/` — the caller builds an `EvalContext` from those subsystems and passes plain values in, and the vocabulary those callers populate (cordon classes, health states) is owned by the engine so the two sides cannot drift. `customPolicy.evalFunction` is compiled once at load; each eval borrows a pre-warmed sobek VM from a small bounded pool (8) and binds the per-request context. ### Behavior changes (upgrade note) - **Consensus config `Validate()` now runs at boot.** A config that boots on `main` but fails consensus validation (broken named policy, missing waiver floor, S3-path collision, bad `evalFunction`) now fails startup instead of the first request. - **Misbehavior export keys changed.** The default `filePattern` adds `{instanceId}`, and S3 keys gain a `-f` suffix, to stop concurrent pods overwriting each other's objects. Readers of the old key shape must update. - **Selector fail-closed reasons are explicit.** A null/undefined eval return is a selector failure (counted `reason="null"` and logged), **not** an intentional default pick; return the string `"default"` to select the default deliberately. **Eval runs once, before fan-out.** It does not extend consensus wait windows. A clean eval returns its VM to the pool, so steady-state cost is the eval itself (tens to low-hundreds of µs) — only a throw, non-string return, null return, or timeout discards and rebuilds. There is no decision cache in v1. **Reuse note:** because the VM is reused, an eval that closes over mutable JS state (a counter, a cached array) keeps it across requests on the same VM. Write evals as pure functions of `ctx` — do not depend on fresh-realm isolation. **`evalTimeout` is a hard wall-clock cap.** On overrun the borrowed VM is interrupted and **discarded** (never returned to the pool, since an interrupt is the only state that poisons a VM); the request fails closed to the default. Omit the field or set `0` to get the `50ms` default — negative values are rejected at load. **Caller identity is the auth strategy name.** `ctx.user.auth` is the `name` field of the strategy that authenticated the caller, stamped by the auth registry onto the request's exec state. Unnamed strategies stamp `""`. The name is **never** accepted from client-controlled headers, query params, or body fields — only from the strategy config that verified the caller. ### Config schema All fields under `networks[].failsafe[].consensus.` (or project-level `failsafe[].consensus.`). Duration fields accept Go duration strings. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `policies` | `map[string]ConsensusPolicyConfig` | `nil` (inline block is the single default) | Named policies. Each value is a **complete** consensus config — the same fields as the inline `consensus:` block (`maxParticipants`, `agreementThreshold`, `disputeBehavior`, `requiredParticipants`, `punishMisbehavior`, `misbehaviorsDestination`, …). A named policy must **not** itself define `customPolicy` or `policies` — nesting is a startup validation error. Each named policy is validated independently, so a broken one fails startup with a `policies[""]` prefix. | | `cacheableResponses` | `*bool` | inline/`default` omit → `true`; named `policies.*` omit → `false` | Stamped onto the winning response in `Consensus.Run` (`SetCacheable`). Cache.Set combines this mark with `database.*.cachingStrategy` — the cache never sees policy names. Named omit→`false` is stamped **before** `extends` resolve, so it wins over a base's `true` for both `extends: default` and named→named inheritance (fail-safe: weaker/derived grades stay uncacheable unless that named entry opts in). Recommended posture: leave cache at `defaultAllow`, set `cacheableResponses: false` on weaker grades like `fallback`. When any failsafe entry on the network has `customPolicy`, Forward also skips Set for unmarked (`nil`) responses so no-consensus sibling routes cannot poison the shared store. Source: [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go), [`consensus/consensus.go`](https://github.com/erpc/erpc/blob/main/consensus/consensus.go), [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) | | `policies..extends` | `string` | `""` (no inheritance) | One-level inheritance only. Values: another named policy key, or `default` (the inline `consensus:` block). The child overlays the base: non-nil child fields win, including an explicit `requiredParticipants: []` which **clears** inherited quotas. Nested extends (base itself sets `extends`) and unknown bases fail startup. After resolve, `extends` is cleared on the runtime policy. Selection surface (`customPolicy` / nested `policies`) is never inherited and is rejected on the child even when combined with `extends`. | | `customPolicy` | `*ConsensusCustomPolicyConfig` | `nil` (default policy for every request) | Optional pre-round selector. When omitted, the default/inline policy applies to every request. | | `customPolicy.evalFunction` | `string` | **Required when `customPolicy` set** | JS. Signature `(ctx) => string \| null`. Compiled at load (a smoke-compile runs during validation, so a syntax error fails startup, not the first request). Returns a policy name, or `null`/empty for the default. A non-string return fails closed. | | `customPolicy.evalTimeout` | `Duration` | `50ms` | Hard wall-clock cap per eval. On overrun the VM is discarded and the request fails closed to the default. Omit or `0` → default `50ms`; negative values fail startup validation. | | `requiredParticipants[].waiveAgreementOnMissingData` | `bool` | `false` | Opt-in per quota entry. Releases this entry's `minAgreement` quota for a round when **at least `minAgreement`** distinct upstreams matching its `tag` returned `ErrEndpointMissingData` and no matching upstream returned data. See *MissingData waiver* below. Put it on a permissive policy (`standard-waive-missing`), never on the fail-closed `standard`. | | `requiredParticipants[].waiveAgreementOnEmptyOutsideRetention` | `bool` | `false` | Opt-in per quota entry (v1.1). Releases this entry's `minAgreement` quota when **at least `minAgreement`** distinct tag-matching upstreams returned an **empty** result, no matching upstream returned non-empty data, AND the block is proven outside retention — prefer each empty upstream's finite `blockAvailability` lower bound, else `head - block > retentionBlocks`. The block is the one the **client's request** names; for a hash lookup it is the block the answer names, once an upstream outside the agreeing set confirms it. Tag requests never waive. See *Empty-outside-retention waiver* below. Requires `retentionBlocks > 0`. Same placement rule — permissive policy only. | | `requiredParticipants[].retentionBlocks` | `int64` | `0` | Retained depth behind the chain head for the **chain-head fallback** proof (outside iff `head - requestedBlock > retentionBlocks`). Prefer aligning with internal `blockAvailability.lower.latestBlockMinus` so the avail-bound proof path can fire without a network tip. Must be `> 0` when `waiveAgreementOnEmptyOutsideRetention` is set. | | `blockEvidenceFields` | `map[string][]string` | `nil` | **Unsafe opt-in.** Per-method response paths holding the winning answer's own block number (same shape as `preferHighestValueFor`, plus `"*.field"` for array results). When no upstream outside the agreeing set confirms a hash lookup's block, the empty-outside-retention waiver trusts this one. Two colluding upstreams can then get a fabricated old tx or receipt served. See *Empty-outside-retention waiver* below. | **Validation guardrails (startup):** - **Waiver floor.** A policy that opts any entry into `waiveAgreementOnMissingData` **or** `waiveAgreementOnEmptyOutsideRetention` must also keep at least one **never-waivable** entry with `minAgreement > 0`. Without a floor, a unanimous abstention could waive the *only* quota and let a single unverified value win — the floor keeps at least one hard quorum. (A waiver-free config needs no floor.) - **Empty-waiver needs a retention boundary.** Opting any entry into `waiveAgreementOnEmptyOutsideRetention` requires `retentionBlocks > 0` on that entry — without it, the waiver could never prove a block is outside retention and would silently never fire, so it's a startup error rather than a dropped intent. - **Nesting.** A `policies[""]` value that defines `customPolicy` or `policies` is rejected — policies are a flat map, selected by the top-level selector only. - **Shared S3 export path.** The misbehavior rate limiter is global per upstream, but the exporter is per-policy. Two policies must not share a `misbehaviorsDestination.path` unless **every** sharing policy's `filePattern` contains both `{timestampMs}` and `{policy}` — otherwise two exporters can resolve the same S3 key in the same millisecond and a `PutObject` overwrites rather than appends. `{policy}` is hex-encoded (injective) so names that collide under filename sanitization (`a/b` vs `a_b`) still get distinct keys. - **Shared punishMisbehavior.** When `policies` is non-empty, the inline default and every named policy must carry identical `punishMisbehavior` (including all unset). The misbehavior limiter/sitout map is shared across policies, so differing `disputeThreshold` / `disputeWindow` / `sitOutPenalty` would silently first-touch-win. ### Eval interface ```js (ctx) => string | null // ctx.request { method, blockNumber: number|null, network } // ctx.user { auth: string } | null // auth strategy name (§4.3) // ctx.upstreams chainable collection of // { id, tags, health, blockAvailability: { lower, upper } | null } // health = { state: "healthy" | "unhealthy" | "cordoned", // cordonClasses: ("punishment"|"availability"|"operator")[], // cordonReason?: string } // diagnostic only — never matched // // return "name" → run policies[name] (unknown name → fail closed to default + warn) // return "default" → deliberately run the inline default policy // return null → selector failure: fails closed to the default (counted reason="null") ``` `ctx.user` is `null` for unauthenticated requests; guard with `ctx.user?.auth === "…"`. `blockNumber` is `null` for methods with no numeric block (tx-hash / block-hash lookups) — the "unknown block" case. An upstream can hold several cordons at once, so `cordonClasses` is a **set**; `state` is `"cordoned"` whenever that set is non-empty, taking precedence over `"unhealthy"`. **Sandbox.** The eval runs in a bare VM that exposes only `ctx` and the helper API above — no `env`, `process.env`, or `console`. Since `evalFunction` is operator-writable config, it deliberately has no host-process env-var access. **Stdlib helpers** (chainable, mirrors the selection-policy engine): | Helper | Behavior | |---|---| | `upstreams.withTag(t)` | Filter to upstreams whose `tags` include `t` (exact match). | | `upstreams.healthy()` | Keep only `state == "healthy"` — cordoned upstreams of any class are excluded. | | `upstreams.anyPunished()` | True if any network upstream holds a `punishment` cordon (consensus misbehavior sit-out), **including nodes already excluded from `ctx.upstreams` by selection**. A fail-closed gate: never downgrade while any node is punished. | | `upstreams.anyOperatorCordon()` | True if any network upstream holds an `operator` (admin) cordon, **including nodes already excluded from `ctx.upstreams` by selection**. Also a fail-closed gate — admin action is undifferentiated, so treat it as distrust. | | `upstreams.allUnavailable()` | True only if the set is **non-empty** and every member is unhealthy-but-uncordoned **or** holds `availability` cordons and nothing else. **False on an empty set** (a tag matching nothing is a config error, not an outage) and **false** if any member holds a `punishment`/`operator`/future class. | | `upstreams.allOperatorCordoned()` | True only if the set is **non-empty** and every member holds an `operator` (admin) cordon. **False on an empty set.** Use with `withTag` for a deliberate full-tag drain (e.g. `upstreams.withTag("tier:primary").allOperatorCordoned()` → allow a named looser policy); do not confuse with `anyOperatorCordon()` which pins fail-closed on a single admin cordon. | | `upstreams.noneSelected()` | True only if the set is **non-empty** and **none** of those members appear in the post-selection candidate list for this request (lag / diversity / `ensureMin` exclusion). **False on an empty set.** Use with `withTag` when a healthy tag side was fully excluded from the round (e.g. `upstreams.withTag("tier:primary").noneSelected()` → allow a named looser policy). Orthogonal to `allUnavailable()`, which inspects registry health rather than round membership. | | `upstreams.canServeBlock(n)` | Filter to upstreams whose configured `blockAvailability` range can serve block `n`. A non-numeric `n` or an upstream with no configured range is kept (attempt allowed). | | `user.auth` | Name of the authenticating auth strategy (plain string compare). | ### Worked examples **Reference selector — integrity grades + availability fallback.** This is the canonical shape: fail-closed gates first (punishment / operator cordons pin the request to `standard`), then a strategy-gated availability fallback, then strategy-gated historical grades, then the strict default. Note the ordering — the gates come *before* any downgrade so an attacker who gets one node punished, or an admin who cordons a node, can never force a looser policy. For an opt-in full-tag admin drain via `allOperatorCordoned()`, see edge cases below (ordering matters): **Config path:** `projects[].networks[].failsafe[].consensus` **YAML — `erpc.yaml`:** ```yaml consensus: # the inline block IS the strict default policy the round falls back to # (null/unknown selection, eval error, or timeout). It must be a complete, # valid consensus config on its own — here identical to the "standard" policy. maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1 } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } policies: standard: # default / fail-closed maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1 } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } standard-waive-missing: # same composition; waiver for pruned/MissingData maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError requiredParticipants: - { tag: "type:internal", minParticipants: 1, minAgreement: 1, waiveAgreementOnMissingData: true } - { tag: "type:external", minParticipants: 2, minAgreement: 2 } historical: # known-old block — external-only, skip internals maxParticipants: 3 agreementThreshold: 2 requiredParticipants: - { tag: "type:external", minParticipants: 2, minAgreement: 2 } fallback: # internals genuinely down — healthy externals only maxParticipants: 3 agreementThreshold: 2 customPolicy: evalTimeout: 50ms evalFunction: | (ctx) => { // Punishment or admin cordon anywhere → never downgrade. if (ctx.upstreams.anyPunished()) return "standard" if (ctx.upstreams.anyOperatorCordon()) return "standard" const internals = ctx.upstreams.withTag("type:internal") // Genuine outage (unhealthy or availability-cordoned only) → fallback (strategy-gated). if (internals.allUnavailable()) return ctx.user?.auth === "consensus-fallback" ? "fallback" : "standard" // Historical access is strategy-gated — unauthorized stay on standard (dispute on miss). if (ctx.user?.auth === "consensus-waive") { const n = ctx.request.blockNumber if (n !== null && internals.canServeBlock(n).length === 0) return "historical" // known-old: external-only, no internal call if (n === null) return "standard-waive-missing" // tx-hash etc.: try internals, waive MissingData } return "standard" } ``` **TypeScript — `erpc.ts`:** ```typescript consensus: { // the inline block IS the strict default policy the round falls back to // (null/unknown selection, eval error, or timeout). It must be a complete, // valid consensus config on its own — here identical to the "standard" policy. maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1 }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], policies: { standard: { maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1 }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], }, "standard-waive-missing": { maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", requiredParticipants: [ { tag: "type:internal", minParticipants: 1, minAgreement: 1, waiveAgreementOnMissingData: true }, { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], }, historical: { maxParticipants: 3, agreementThreshold: 2, requiredParticipants: [ { tag: "type:external", minParticipants: 2, minAgreement: 2 }, ], }, fallback: { maxParticipants: 3, agreementThreshold: 2 }, }, customPolicy: { evalTimeout: "50ms", evalFunction: \`(ctx) => { // Punishment or admin cordon anywhere → never downgrade. if (ctx.upstreams.anyPunished()) return "standard" if (ctx.upstreams.anyOperatorCordon()) return "standard" const internals = ctx.upstreams.withTag("type:internal") // Genuine outage (unhealthy or availability-cordoned only) → fallback (strategy-gated). if (internals.allUnavailable()) return ctx.user?.auth === "consensus-fallback" ? "fallback" : "standard" // Historical access is strategy-gated — unauthorized stay on standard. if (ctx.user?.auth === "consensus-waive") { const n = ctx.request.blockNumber if (n !== null && internals.canServeBlock(n).length === 0) return "historical" if (n === null) return "standard-waive-missing" } return "standard" }\`, }, } ``` The three integrity grades this selector chooses between: | Policy | Composition | MissingData waiver | When selected | |---|---|---|---| | `standard` | internal + external | No | Default / fail-closed; unauthorized callers; any node punished or operator-cordoned | | `standard-waive-missing` | same as `standard` | Yes (internals) | Authorized role + unknown block (`blockNumber == null`, e.g. tx-hash) | | `historical` | external only | n/a | Authorized role + known-old block (internals can't serve it) | **MissingData waiver.** On a round running a waiving policy, an entry with `waiveAgreementOnMissingData: true` has its `minAgreement` quota released when **at least `minAgreement` distinct upstreams matching its tag returned `ErrEndpointMissingData`**. Sibling transport/infra errors do not block the count; a matching participant that returned data holds the quota. The waiver is safe by construction: - **Threshold = `minAgreement`.** Enough matching MissingData answers release the quota; fewer hold it strict → composition dispute. - **Round-complete only.** While any response can still arrive, a slower tagged upstream might return data, so the waiver holds off and the dispute stays provisional. Wait-cap cancel alone does **not** seal the bag — a result may already be buffered or the upstream call may ignore cancellation — so waivers stay fail-closed on a partial wait-capped collection. - **Never-decisive-masking.** The waiver only changes the outcome when releasing the entry makes the winner decisive; it can't hide a real disagreement. - **Floor enforced.** The `standard-waive-missing` policy keeps a never-waivable external floor (`minAgreement: 2`) — even with the internal quota waived, two externals must still agree. **Empty-outside-retention waiver (v1.1).** Some upstreams answer with an *empty* result (JSON `null`, `[]`, `{}`) rather than a missing-data error when asked for history they have legitimately pruned (e.g. post-EIP-4444 nodes drop old blocks). An entry with `waiveAgreementOnEmptyOutsideRetention: true` has its `minAgreement` quota released when **at least `minAgreement` distinct tag-matching upstreams returned an empty result, no matching upstream returned a non-empty result, AND the block is proven outside retention**. The block is the one the client's request names, or — for a hash lookup — the one the answer names once an upstream outside the agreeing set confirms it, so upstreams that agree on a fabricated block cannot supply their own proof. Sibling errors do not block the empty count; a matching non-empty result holds the quota. Proof order: 1. **Availability lower bound (preferred).** Each matching empty upstream must expose a finite `EvmBlockAvailabilityBounds` lower bound (typically `poller.latest − latestBlockMinus` from `blockAvailability.lower`) and `requestedBlock < lower` for every such upstream. No network `servedTip` needed — this is the reliable `head − retention` signal when internals declare retention via availability bounds. Align `latestBlockMinus` with `retentionBlocks`. 2. **Chain-head fallback.** Else `head - requestedBlock > retentionBlocks`, where `head` is the request's head `Latest` when `evm.servedTip.quorum` is `"majority"`, otherwise the min corroborated poller latest among this round's EVM participants (≥2 positive latests; a single poller fails closed). A head under the default quorum is not trusted. It shares the MissingData waiver's safety properties (`minAgreement` threshold, round-complete, never-decisive-masking, floor enforced) and adds a **block proof** as its anti-fabrication guard: - **Recent nulls never waive.** An empty result on a block *inside* retention / bounds fails the proof and holds the quota → dispute. So correlated externals returning `null` on recent data an internal should still serve cannot outvote that internal — the waiver only tolerates emptiness the retention model *predicts*. - **Hash lookups need a confirmer outside the winners.** `eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockByHash` and other hash lookups name no block, so the waiver reads the block number and hash the agreeing answer names. The agreeing upstreams cannot vouch for that claim themselves: eRPC fetches `eth_getBlockByNumber(, false)` from the round's other upstreams (abstainers first, then the rest, straight to the upstream with no retry or hedge). The first one that returns the block decides: its hash must match the answer's and the requested hash must be that block or one of its transactions. A mismatch fails closed at once; a `null` or an error moves on to the next. A node that pruned only its tx index still serves the block, so a geth internal can confirm its own pruned tx. When no other upstream holds the block, the quota holds → dispute. Requests that name a tag (`latest`) carry no proof → dispute. - **`blockEvidenceFields` trusts the winners (unsafe opt-in).** When every other upstream pruned the block too, nothing can confirm it. A policy that lists the method in `blockEvidenceFields` then judges retention against the block the agreeing answer names at those paths. The waiver no longer checks that claim: two agreeing upstreams can invent a tx or receipt in an old block and get it served. Use it only where those upstreams are already trusted to answer old data on their own. A non-winner that returns a different block still fails the round closed. - **Fail-closed without proof.** If neither avail-bound nor chain-head proof can be evaluated (no block; matching empties lack finite lower bounds and no majority tip or fewer than two participant pollers), the quota holds — the round disputes rather than waiving on faith. That case logs at info (warn for `block_contradicted`) and increments `erpc_consensus_composition_waiver_unproven_total{reason}` (`no_request_block`, `block_unconfirmed`, `block_contradicted`, `no_avail_bound`, or `no_head`). Mid-round deferral (responses still outstanding, collection not sealed) logs at debug only — it is not a metric. - **Config-forced proof.** `retentionBlocks > 0` is mandatory when opting in (startup-enforced), so an operator cannot enable the waiver in a shape where it silently never fires. Both waivers can coexist on one entry; when a round qualifies for both, the `missing_data` reason is reported. Each firing increments `erpc_consensus_composition_waived_total{tag,reason}` — `reason` is `missing_data` or `empty_outside_retention`. Alert on step changes: a waiver is a deliberate relaxation of a hard quorum. ### Edge cases & gotchas 1. **The default policy must be the strictest.** Everything fails closed to it — a throw, timeout, unknown name, or null return. If your default is permissive, every failure mode silently downgrades. Make it your tightest quorum. 2. **`anyPunished` first; partial operator cordons still pin.** Put `anyPunished()` before any downgrade — a misbehavior sit-out must never tip a looser policy. `anyOperatorCordon()` still pins partial admin cordons to `standard` (one cordoned peer is undifferentiated distrust). Both helpers observe the **network** `punishment` / `operator` cordons, including upstreams already excluded from `ctx.upstreams` by selection (`.removeCordoned()`); they do not scan the candidate `items` list. 3. **`allOperatorCordoned` must run before `anyOperatorCordon`.** A deliberate full-tag admin drain (e.g. `upstreams.withTag("tier:primary").allOperatorCordoned()`) is the opt-in exception that may select a looser named policy. If `anyOperatorCordon()` runs first, that drain branch is unreachable — when every member of the tag is operator-cordoned, `anyOperatorCordon()` is already true. Order: `anyPunished` → `allOperatorCordoned` (tag-scoped) → `anyOperatorCordon` → `allUnavailable` / other grades. 4. **Mixed drain fails closed.** One member of the tag operator-cordoned and another only availability-cordoned / unhealthy: neither `allUnavailable()` (operator blocks the whitelist) nor `allOperatorCordoned()` (not every member has `operator`) is true, so the request stays on the fail-closed policy. Cordoning the remaining members (or waiting for a pure availability outage) is required to unlock the drain/fallback path. 5. **`allUnavailable()` is a whitelist of `availability` only.** It is false on an empty set (a tag matching nothing is a config error, not an outage) and false if any member holds a `punishment`/`operator`/future cordon class. Only `availability`-cordoned or unhealthy-uncordoned members count as "unavailable". 6. **No mid-round switching.** The policy is fixed before fan-out. If internals fail *during* a round, that round disputes under the policy it started with; the *next* request's eval sees the new health and can pick `fallback`. Recovery is automatic both ways. 7. **Never put the waiver on the fail-closed policy.** `waiveAgreementOnMissingData` on `standard` defeats the point — the strict grade must dispute on missing internal data. Startup validation also requires a never-waivable `minAgreement > 0` floor in any waiving policy. 8. **Strategy name never comes from headers.** Only the authenticating strategy's configured `name` populates `ctx.user.auth`. Grant a grade by issuing credentials under a named strategy — consensus never parses tokens. 9. **Unknown returned name fails closed with a warn log.** A typo in a returned policy name doesn't error the request — it silently resolves to the default and logs at warn. Watch `consensus_policy_eval_failed_total{reason="unknown_name"}`. 10. **`evalTimeout` discards the VM.** A timeout interrupts and discards the borrowed VM (not returned to the pool); a replacement is rebuilt asynchronously. Sustained timeouts are an eval-complexity alarm — watch `consensus_policy_eval_failed_total{reason="timeout"}`. The pool grows on demand so capacity never bypasses eval. 11. **Two policies, one S3 path.** Sharing a `misbehaviorsDestination.path` without both `{timestampMs}` and `{policy}` in every `filePattern` is a startup error — otherwise the per-policy exporters can overwrite each other's S3 objects even in the same millisecond. 12. **Named policies can't nest.** A `policies[]` value that sets `customPolicy` or `policies` is rejected at startup. Selection happens once, at the top level. 13. **`default` is reserved.** `policies["default"]` is rejected at startup — that name labels the fail-closed inline default in the `consensus_policy` metric and the `X-ERPC-Consensus-Policy` header, so a named policy can't reuse it. 14. **Wait-cap does not seal for waivers.** Composition disputes do not short-circuit while slots remain. When `maxWaitOnResult` / `maxWaitOnEmpty` fires, remaining slots are cancelled for latency but MissingData / empty-outside-retention waivers stay fail-closed on that partial bag — cancellation is not a round-completion barrier (buffered or cancel-ignoring results can still arrive with data that would dispute the waiver). 15. **Selector + shared cache: flush on first enable.** Keys omit policy/auth and stored values carry no mark. Pre-selector warm entries remain Get-able until TTL after you add `customPolicy`. Flush/rotate the connector (or wait out max TTL). After enable, Forward refuses unmarked Sets on that network so sibling no-consensus routes cannot re-poison under `defaultAllow`. Source: [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_consensus_policy_selected_total` | Counter | `project`, `network`, `consensus_policy` | Per served round — the named policy the selector chose. Cardinality bounded by policy count (expected ≤ 10). Sustained non-default selection (e.g. `fallback`) is an alerting signal. | | `erpc_consensus_policy_eval_failed_total` | Counter | `project`, `network`, `reason` | Per fail-closed selection where the eval **ran** and failed. `reason`: `timeout`, `throw`, `unknown_name`. Each falls back to the strictest default. | | `erpc_consensus_policy_eval_duration_seconds` | Histogram | `project`, `network` | Per-eval wall-clock duration. Watch the tail against `evalTimeout`. | | `erpc_consensus_composition_waived_total` | Counter | `project`, `network`, `tag`, `reason` | Quota waived (`missing_data` / `empty_outside_retention`). Alert on step changes. | | `erpc_consensus_composition_waiver_unproven_total` | Counter | `project`, `network`, `reason` | Empty-outside-retention fail-closed for missing proof. `reason`: `no_request_block` (no block in the request or the answer), `block_unconfirmed` (no upstream outside the winners returned the answer's block), `block_contradicted` (one did, and it disagrees — alert on it), `no_avail_bound`, `no_head`. Mid-round deferral is debug-only, not counted. | **Response header.** `X-ERPC-Consensus-Policy: ` carries the chosen policy name so callers can detect a degraded grade (e.g. `fallback`) directly. It is emitted only when a selector is configured (`consensus.customPolicy` is set); plain inline-consensus setups never emit it. ### Source code entry points - [`internal/consensus/policy/policy.go`](https://github.com/erpc/erpc/blob/main/internal/consensus/policy/policy.go) — `EvalContext`, `Request`/`User`/`Upstream`/`Health`/`BlockRange`, cordon-class and health-state vocabulary, typed fail-closed errors (`ErrEvalTimeout`, `ErrEvalThrew`) - [`internal/consensus/policy/selector.go`](https://github.com/erpc/erpc/blob/main/internal/consensus/policy/selector.go) — `Compile`, `Selector.Evaluate` (VM pool borrow, timeout/interrupt, result interpretation) - [`internal/consensus/policy/pool.go`](https://github.com/erpc/erpc/blob/main/internal/consensus/policy/pool.go) — bounded pre-warmed VM pool - [`internal/consensus/policy/stdlib.js`](https://github.com/erpc/erpc/blob/main/internal/consensus/policy/stdlib.js) — chainable `upstreams`/`user` helpers bound into each VM - [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go) — `ConsensusCustomPolicyConfig`, `ConsensusPolicyConfig.Policies` / `.Extends`, `ConsensusRequiredParticipant.WaiveAgreementOnMissingData` / `.WaiveAgreementOnEmptyOutsideRetention` / `.RetentionBlocks`, `AuthStrategyConfig.Name` - [`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go) — waiver-floor, nesting-rejection, S3-path-collision, and evalFunction smoke-compile checks - [`auth/registry.go`](https://github.com/erpc/erpc/blob/main/auth/registry.go) — stamps the authenticating strategy's `name` onto the request's exec state (the consensus selector reads `ctx.user.auth` from there; `User` carries no auth name) ### Related pages - [Consensus](/config/failsafe/consensus.llms.txt) — the rule-set each named policy configures (quorums, dispute behavior, `requiredParticipants`, misbehavior punishment and export). Read this first. - [Authentication](/config/auth.llms.txt) — auth strategies; set `name` on each strategy that should gate a consensus grade via `ctx.user.auth`. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — the sibling freeform-JS engine that decides which upstreams are drawn for participant slots. --- --- # Consensus > Source: https://docs.erpc.cloud/config/failsafe/consensus > Fan out every request to multiple providers simultaneously, agree on a single canonical answer, and automatically flag — or silence — the ones that lie. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Consensus Stale data, silent bugs, and misconfigured nodes all look like valid responses — until you compare them. eRPC fans out every request to multiple providers simultaneously, groups identical answers by hash, and declares a winner only when enough agree. Providers that consistently disagree get flagged, cordoned, and forensically logged. One config field turns on multi-provider truth. **What you get** - Majority-agreed responses instead of trusting a single provider - Automatic misbehavior detection with configurable cordon punishment - Block-head leader preference and highest-value preference for chain-tip reads - Full dispute forensics exported to file or S3 for offline analysis - First-class `eth_sendRawTransaction` broadcast mode with fire-and-forget delivery ## Quick taste Illustrative, not a tuned production config — fan out to 3, require 2 to agree: **Config path:** `projects[].networks[].failsafe[].consensus` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } failsafe: - matchMethod: "*" consensus: # fan out to 3 upstreams, require 2 to agree maxParticipants: 3 agreementThreshold: 2 # on dispute, pick the most common valid result instead of erroring disputeBehavior: acceptMostCommonValidResult ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, failsafe: [{ matchMethod: "*", consensus: { // fan out to 3 upstreams, require 2 to agree maxParticipants: 3, agreementThreshold: 2, // on dispute, pick the most common valid result instead of erroring disputeBehavior: "acceptMostCommonValidResult", }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up consensus from scratch** ```text I want to verify that my RPC responses are correct by checking agreement across multiple providers, using eRPC's Consensus feature. Fan out to 3 upstreams and require 2 to agree, with sensible ignoreFields so blockTimestamp differences don't cause false disputes. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/failsafe/consensus.llms.txt ``` **Prompt Example #2: add highest-value consensus for fee and nonce reads** ```text My app sends transactions and sometimes gets stuck because eth_gasPrice or eth_getTransactionCount return stale low values from a lagging node. Add preferHighestValueFor consensus for these two methods so eRPC fans out to 4 upstreams and picks the highest value. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/consensus.llms.txt ``` **Prompt Example #3: broadcast eth_sendRawTransaction to multiple nodes** ```text I want my eth_sendRawTransaction submissions to propagate faster by broadcasting to all available upstreams simultaneously and returning the first accepted hash (fire- and-forget mode). The consensus threshold should be 1 since any accepted tx hash is valid. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/consensus.llms.txt ``` **Prompt Example #4: debug spurious consensus disputes on log queries** ```text My eRPC instance is logging consensus disputes for eth_getLogs and eth_getBlockReceipts calls even though the data looks correct. I suspect the nodes are returning different blockTimestamp or L2-specific fields (gasUsedForL1, l1Fee, etc.). Show me how to extend ignoreFields to suppress these false disputes without removing the built-in defaults. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/consensus.llms.txt ``` **Prompt Example #5: add misbehavior tracking and automatic cordon** ```text I want eRPC to automatically detect and temporarily remove providers that consistently return wrong data. After 3 disputes within 5 minutes, cordon the offending upstream for 10 minutes. Export all dispute rounds as JSONL to S3 for offline analysis. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/consensus.llms.txt ``` --- ### Consensus — full agent reference ### How it works **Integration point.** Consensus sits at `networkExecutor.Run`. When a `ConsensusPolicyConfig` is present and the `SkipConsensus` directive is false, the executor calls `consensus.Run(ctx, req, slotInner)` where `slotInner` is `retry(hedge(tryOneUpstream))`. Without consensus the path is `retry(hedge(runUpstreamSweep))`. Composition order: `consensus(retry(hedge(tryOneUpstream)))`. ([`erpc/network_executor.go:L183-188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L183-L188)) **Selecting which requests get consensus.** Network failsafe entries are first-match-wins on `matchMethod` + `matchFinality` + `matchCommitment`; only client requests go through them. For SVM, `matchCommitment` (`none`|`processed`|`confirmed`|`finalized`) compares the commitment erpc pins on the wire: the caller's value, else the `svm.commitment` default that injection writes; write methods are `none`. It is separate from `matchFinality`, which classifies cacheability and moving-head reads. Put specific commitment rules before a catch-all. See [Matchers](/config/matcher.llms.txt) and [SVM commitment](/reference/svm/commitment.llms.txt). **How hashing / quorum work** is unchanged by `matchCommitment` — it only gates which failsafe entry (and therefore which consensus policy) applies. **Participant selection.** Before spawning goroutines, if `requiredParticipants` is configured, `reorderForParticipantQuota` front-loads tag-matching upstreams so the first `maxParticipants` drawn satisfy every `{tag, minParticipants}` entry. Tag matching uses exact equality first, then glob wildcards (`*`, `?`). This is best-effort: quota shortfalls are handled by `lowParticipantsBehavior`. The executor then spawns exactly `maxParticipants` goroutines, each calling `slotInner` independently. ([`consensus/quota.go:L27-79`](https://github.com/erpc/erpc/blob/main/consensus/quota.go#L27-L79)) **Collection and analysis loop.** The `runAnalyzer` goroutine reads responses from a buffered channel. After each response it calls `newConsensusAnalysis` (classify, hash, deduplicate by upstream, group) and `determineWinner` (apply 24 priority-ordered rules). Responses are deduplicated by upstream ID before grouping — hedge/retry can reselect an upstream that already answered for another slot, and one node must not vote twice toward `agreementThreshold`; the best-ranked response per upstream keeps the vote (valid result > consensus-valid error > infrastructure error). If `shouldShortCircuit` returns true, the outcome is sent immediately and remaining requests are cancelled (or left running in fire-and-forget mode). Composition disputes never short-circuit while slots remain. After all participants respond — or a wait-cap deadline fires and cancels stragglers — the analyzer rebuilds analysis and sends the final outcome to the caller's select. Wait-cap cancel alone does **not** seal the bag for MissingData / empty-outside-retention waivers (a buffered or cancel-ignoring result can still arrive); waivers stay fail-closed until every slot has produced a terminal acknowledgement. **Response classification.** Each response is classified into one of four types: `ResponseTypeNonEmpty` (successful non-null result), `ResponseTypeEmpty` (successful but null/empty result), `ResponseTypeConsensusError` (JSON-RPC execution exception, client exception, unsupported, or missing-data), `ResponseTypeInfrastructureError` (all other errors including `ErrUpstreamsExhausted`). Infrastructure errors are excluded from `validParticipants`. `ErrUpstreamsExhausted` is always infra even when it wraps execution exceptions via the shared `ErrorsByUpstream` map. ([`consensus/analysis.go:L333-344`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L333-L344)) Specific error-code mappings: `ErrCodeEndpointExecutionException` (EVM revert, code 3) → `ConsensusError`; `ErrCodeEndpointClientSideException`, `ErrCodeEndpointUnsupported`, `ErrCodeEndpointMissingData` → `ConsensusError`; all other errors (timeout, network, server 500) → `InfrastructureError`; nil JSON-RPC response on a successful response object → `InfrastructureError` with hash `"error:generic"`. A successful response where `IsResultEmptyish` returns true → `ResponseTypeEmpty`. **Hashing.** Non-error responses are hashed via `JsonRpcResponse.CanonicalHash()` or `CanonicalHashWithIgnoredFields(fields)` when `ignoreFields` is configured for the method. Errors are hashed via `errorToConsensusHash`: missing-data errors hash as `"missingdata"` (plus `":permanent"` when the verdict is permanent); other JSON-RPC exceptions hash as `"jsonrpc:"`; standard errors hash as their code; unknown errors hash as `"error:generic"`. Missing-data is grouped by verdict rather than by code because a provider's number for "I do not have this" describes its own storage layout, not the chain — agave answers a permanently absent slot `-32007` from its local blockstore and `-32009` from long-term storage, and an unservable block `-32001` when its ledger was pruned below the slot and `-32004` when the slot is above its rooted tip. Permanence stays in the key so "skipped for good" still disputes against "not indexed yet": they disagree on whether asking again can help, and one group would return whichever arrived first. The client-facing `error.code` is unaffected. Within each hash group, `LargestResult` tracks the member with the highest `CachedResponseSize`; the winner returns `group.LargestResult`, not the first response. For an error group the winner returns `group.RepresentativeError`, the member with the lowest upstream id (ties broken by attempt index), not the first to arrive — a group's members can carry different codes or messages, so selecting by arrival made the client-visible `error.code` and `error.message` depend on which upstream answered first. ([`consensus/analysis.go:L102-117`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L102-L117)) **Rule evaluation.** `determineWinner` walks `consensusRules` in priority order ([`consensus/rules.go:L24`](https://github.com/erpc/erpc/blob/main/consensus/rules.go#L24)). Full 24-rule ordering: | Priority | Rule | Triggers when | Action | |---|---|---|---| | 1 | `eth_sendRawTransaction` special | Method is `eth_sendRawTransaction` AND any non-empty response exists | Return first non-empty; threshold ignored | | 2 | `preferHighestValueFor` | Method configured AND extractable numeric values exist | Group by numeric value; highest ≥ threshold wins; else dispute | | 3 | `onlyBlockHeadLeader` on dispute | `disputeBehavior == onlyBlockHeadLeader` AND no group meets threshold | Leader non-error → leader error (incl. infra) → dispute | | 4 | `onlyBlockHeadLeader` on low participants | `lowParticipantsBehavior == onlyBlockHeadLeader` AND low participants | Leader non-error → leader non-infra error → low-participants error | | 5 | `preferBlockHeadLeader` on dispute/low | `preferBlockHeadLeader` AND no group meets threshold AND leader non-error exists | Return leader non-error; else dispute | | 6 | `preferLarger + acceptMostCommon` below threshold | `preferLargerResponses` AND `acceptMostCommon` AND below threshold | Return largest non-empty by size | | 7 | `acceptMostCommon + preferNonEmpty` above threshold (empty/error at threshold) | `preferNonEmpty` AND `acceptMostCommon` AND any empty or consensus-error group ≥ threshold AND non-empty exists | Return best non-empty (count, then size). Does not gate on which group `getBestByCount` returns — equal counts would otherwise let the generic threshold winner pick empty via map iteration order. | | 8 | Tie at/above threshold (no preference) | Multiple non-error groups share best count ≥ threshold | Dispute | | 9 | `acceptMostCommon` below threshold: non-empty over empty | `preferNonEmpty` AND `acceptMostCommon` AND below threshold AND exactly 1 non-empty AND ≥1 empty | Return single non-empty | | 10 | `acceptMostCommon` below threshold: non-empty over error | `preferNonEmpty` AND `acceptMostCommon` AND below threshold AND leader is error AND non-empty exists | Return best non-empty | | 11 | `returnError + preferNonEmpty` (empty threshold winner) | `disputeBehavior == returnError` AND empty meets threshold AND non-empty minority exists | Dispute (escalate from empty winner) | | 12 | `acceptMostCommon + preferNonEmpty` above threshold (both qualify) | Both non-empty and consensus-error ≥ threshold | Return best non-empty | | 13 | Tie above threshold (general, no preference) | Multiple valid groups share best count ≥ threshold | Dispute | | 14 | `preferLarger`: above threshold, multiple groups | `preferLargerResponses` AND best meets threshold AND >1 group ≥ threshold | Return largest non-empty by size | | 15 | `preferLarger + acceptMostCommon`: larger exists below threshold | `preferLargerResponses` AND `acceptMostCommon` AND best meets threshold AND non-empty AND larger exists below | Return largest non-empty by size | | 16 | `returnError + preferLarger`: smaller wins but larger exists | `disputeBehavior == returnError` AND `preferLargerResponses` AND threshold met AND larger below threshold | Dispute | | 17 | `acceptMostCommon` below threshold: unique leader | `acceptMostCommon` AND best count < threshold AND best > second-best | Return best valid group | | 18 | `lowParticipants + acceptMostCommon` | `lowParticipantsBehavior == acceptMostCommon` AND low participants | Non-empty (if untied) → empty → error → low-participants error | | 19 | Threshold winner (generic) | Any valid group meets threshold | Return result or consensus-error | | 20 | Dispute (multiple groups, none at threshold) | Best count < threshold AND >1 valid group | Dispute error | | 21 | All infra errors meet threshold | `validParticipants == 0` AND infra group meets threshold | Return agreed infra error | | 22 | `lowParticipants + returnError` | `lowParticipantsBehavior == returnError` AND low participants | Low-participants error | | 23 | No responses | `len(groups) == 0` | Low-participants error | | 24 | Fallback | Catch-all | Low-participants error | **Short-circuit rules.** `shouldShortCircuit` evaluates 3 rules after each response. (1) `sendrawtx_first_success`: fires on any single non-empty for `eth_sendRawTransaction`, never blocked. (2) `consensus_error_threshold`: best group is consensus-error ≥ threshold; blocked when `preferHighestValueFor` configured, or `acceptMostCommon` active AND (`preferNonEmpty` OR `preferLargerResponses`). (3) `unassailable_lead`: best non-empty ≥ threshold with unassailable lead; blocked when `preferLargerResponses` active, `preferHighestValueFor` configured, or `preferNonEmpty` active and leader is empty. **Misbehavior tracking and punishment.** After all responses, `trackAndPunishMisbehavingUpstreams` compares each group against the consensus group. Data disagreements count as misbehavior; error disagreements are tracked separately via `erpc_consensus_upstream_errors_total` and are NOT misbehavior. For each misbehaving upstream: `MetricConsensusMisbehaviorDetected` fires and `tracker.RecordUpstreamMisbehavior` is called. Punishment requires strict majority (`consensusGroup.Count > validParticipants / 2`) plus token-bucket denial (`disputeThreshold` tokens per `disputeWindow`); when both hold, the upstream is cordoned and `AfterFunc` calls `Uncordon` after `sitOutPenalty`. ([`consensus/executor.go:L784-1229`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L784-L1229)) **`eth_sendRawTransaction` broadcast mode.** Rule 1 fires as soon as any single non-empty response exists — threshold is ignored entirely. Combined with `fireAndForget: true`, eRPC returns the first accepted tx hash immediately while remaining participant goroutines continue broadcasting using `context.WithoutCancel(ctx)` as their base, surviving HTTP client disconnection. They are bounded by upstream call completion, wait-cap timers, or process exit — not by graceful shutdown signals. **Wait caps.** `maxWaitOnResult` (adaptive p50, default min=5ms, max=1s) arms when the first non-empty response arrives. `maxWaitOnEmpty` (adaptive p90, default min=50ms, max=2s) arms on the very first response of any kind. When a cap fires, the analyzer resolves with what it has collected, applying `disputeBehavior` or `lowParticipantsBehavior` as appropriate. `erpc_consensus_wait_capped_total{trigger}` tracks firings. **SkipConsensus directive.** Any request can bypass consensus via `X-ERPC-Skip-Consensus: true` header, `?skip-consensus=true` query param, or `directiveDefaults.skipConsensus: true` in network/project config. When set, the executor falls through to `retry(hedge(runUpstreamSweep))`. Only `"true"` activates bypass; any other value keeps consensus active. **Misbehavior export.** When `misbehaviorsDestination` is configured, every round with at least one misbehaving upstream is serialized as a JSONL record containing timestamp, project/network/method/finality, full policy snapshot, request, winner snapshot, analysis snapshot (groups, counts, hashes), and per-participant snapshot. For `type: file`: records are written immediately to `path/`. For `type: s3`: records are buffered and flushed asynchronously when `maxRecords`, `maxSize`, or `flushInterval` fires; S3 uses `PutObject` — each flush replaces the object. JSONL record top-level fields: `ts` (int64, Unix ms), `projectId` (string), `networkId` (string), `method` (string), `finality` (string), `policy` (object: `maxParticipants`, `agreementThreshold`, `disputeBehavior`, `lowParticipantsBehavior`, `preferNonEmpty`, `preferLargerResponses`, `ignoreFields`), `request` (`{jsonrpc, id, method, params}`), `winner` (`{responseType, hash, size, upstreamId}`), `analysis` (`{totalParticipants, validParticipants, bestByCount, groups[]}` — each group has `{hash, count, isTie, responseType, responseSize}`), `participants` (array — per upstream: `{upstreamId, vendor, responseType, responseHash, responseSize, response, error}`). **Caller-abandoned handling.** If the HTTP client disconnects before consensus completes, a drain goroutine waits for `analyzerDone`, drains `outcomeCh`, and releases the winner's response buffer to prevent memory leaks. Metrics record `caller_abandoned` outcome. ([`consensus/executor.go:L287-338`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L287-L338)) **Panic safety.** Both `executeParticipant` and `runAnalyzer` have `recover()` defers. Panics send `errPanicInConsensus` on the relevant channel so the caller's select never deadlocks. `MetricConsensusPanics` is incremented on any recovery. ### Config schema All fields under `networks[].failsafe[].consensus.` (or project-level `failsafe[].consensus.`). Duration fields accept Go duration strings. `*bool` fields: unset means `SetDefaults` applies the documented default. Struct at [`common/config.go:L1591-1658`](https://github.com/erpc/erpc/blob/main/common/config.go#L1591-L1658). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `maxParticipants` | int | `5` ([`common/defaults.go:L2390-2392`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2390-L2392)) | Number of upstreams to fan-out to. If ≤ 0, clamped to 1. | | `agreementThreshold` | int | `2` ([`common/defaults.go:L2393-2395`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2393-L2395)) | Minimum participants that must agree on the same response hash. Also used by `isLowParticipants` (`validParticipants < threshold`). | | `disputeBehavior` | string enum | `"returnError"` ([`common/defaults.go:L2396-2398`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2396-L2398)) | Action when `validParticipants >= agreementThreshold` but no group meets threshold. Values: `returnError`, `acceptMostCommonValidResult`, `preferBlockHeadLeader`, `onlyBlockHeadLeader`. | | `lowParticipantsBehavior` | string enum | `"acceptMostCommonValidResult"` ([`common/defaults.go:L2399-2401`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2399-L2401)) | Action when `validParticipants < agreementThreshold` (fewer upstreams produced non-infrastructure-error responses than the threshold, typically because too few upstreams were reachable before wait caps fired). Same four values as `disputeBehavior`. Distinction: `disputeBehavior` fires when `validParticipants >= agreementThreshold` but no group meets threshold (participants disagree); `lowParticipantsBehavior` fires when there are not enough valid participants to even reach threshold. Under `acceptMostCommon`: non-empty > empty > error; ties among non-empty groups → dispute. | | `disputeLogLevel` | string | `"warn"` ([`common/defaults.go:L2402-2404`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2402-L2404)) | Zerolog level for misbehavior events. Values: `trace`, `debug`, `info`, `warn`, `error`. **Footgun**: zerolog zero value is `TraceLevel`; builder coerces unset to `WarnLevel`. Set `"trace"` explicitly for trace-level logging. | | `ignoreFields` | `map[string][]string` | `{"eth_getLogs":["*.blockTimestamp"],"eth_getTransactionReceipt":["blockTimestamp","logs.*.blockTimestamp"],"eth_getBlockReceipts":["*.blockTimestamp","*.logs.*.blockTimestamp"]}` ([`common/defaults.go:L2405-2419`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2405-L2419)) | Per-method dot-path field patterns excluded from canonical hash. **Set replacement, not merge**: setting ANY entry replaces the ENTIRE default map. To add a method, re-include all three defaults. Setting `{}` disables all defaults. | | `preferNonEmpty` | \*bool | `true` ([`common/defaults.go:L2420-2422`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2420-L2422)) | Prefer non-empty over empty or consensus-error in dispute resolution. Disables short-circuit when empty would lead. | | `preferLargerResponses` | \*bool | `true` ([`common/defaults.go:L2423-2425`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2423-L2425)) | Prefer larger response bodies. **Disables ALL short-circuit** when active — every request must wait for all participants. Increases latency for the common case. Disable in latency-sensitive scenarios. | | `preferHighestValueFor` | `map[string][]string` | `nil` (disabled) | Per-method ordered field paths. Responses grouped by numeric value; highest ≥ threshold wins. Bypasses all other rules. Disables short-circuit for that method. Field path `"result"` extracts the direct scalar result; any other path extracts `resultObj[fieldName]`. Multiple fields act as ordered tie-breakers: first field is primary, subsequent fields are tie-breakers. Numeric parsing handles hex strings (`0x...`), decimal strings, `json.Number`, `float64`, `int64`. If any configured field returns nil, the entire response is excluded from value grouping. Responses are regrouped by value (not hash), so differently-formatted representations of the same number match. ([`consensus/utils.go:L13-168`](https://github.com/erpc/erpc/blob/main/consensus/utils.go#L13-L168)) | | `fireAndForget` | bool | `false` (Go zero value; no `SetDefaults` entry) | When `true`, remaining in-flight requests are NOT cancelled after short-circuit. Goroutines use `context.WithoutCancel(ctx)` and survive HTTP disconnection. **Footgun**: process shutdown signals do not reach these goroutines; budget shutdown timeouts accordingly. | | `maxWaitOnResult` | \*AdaptiveDuration | `{quantile:0.5, min:"5ms", max:"1s"}` ([`common/defaults.go:L2432-2438`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2432-L2438)) | Cap after first non-empty response. Cold-start fallback is `min` (5ms). If you configure without a `min`, cold start returns 0 — no cap until data accumulates. | | `maxWaitOnEmpty` | \*AdaptiveDuration | `{quantile:0.9, min:"50ms", max:"2s"}` ([`common/defaults.go:L2439-2445`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2439-L2445)) | Cap after first response of any kind. Same cold-start behavior: fallback to `min` (50ms). | | `requiredParticipants` | `[]*ConsensusRequiredParticipant` | `[]` (disabled) | List of `{tag, minParticipants}` entries. Front-loads tag-matching upstreams. Best-effort: shortfall falls through to `lowParticipantsBehavior`. | | `requiredParticipants[].tag` | string | **Required** | Glob pattern matched against `upstream.tags[]`. Empty tag is a startup validation error. | | `requiredParticipants[].minParticipants` | int | **Required; no default** | Must be > 0 and ≤ `maxParticipants`. Omitting or setting 0 is a startup validation error — not a silent no-op. | | `requiredParticipants[].minAgreement` | int | `0` (disabled) | Minimum matching upstreams that must be in the **winning** group. Unlike `minParticipants` (best-effort pool quota), this is hard-enforced: a count-winner that fails it becomes `ErrConsensusCompositionDispute` (`dispute_composition` outcome), regardless of `disputeBehavior`. Must be ≤ `minParticipants`. While responses are outstanding the dispute is provisional — short-circuit is suppressed so a late response can still complete the quota. `eth_sendRawTransaction` is exempt. The wait caps (`maxWaitOnResult`/`maxWaitOnEmpty`) are quota-aware: they start counting down only once collected responses cover every `minAgreement` tag (a tagged upstream's error counts as coverage), so fast correlated upstreams cannot time out a slower quota-tagged upstream; until coverage the round is bounded by per-upstream and request timeouts. A quota tag matching zero participants in a round logs at Warn — check for a typo'd tag or unavailable tagged upstreams. | | `requiredParticipants[].waiveAgreementOnMissingData` | bool | `false` | Opt-in per entry. Releases this entry's `minAgreement` quota for a round when **at least `minAgreement`** distinct tag-matching upstreams returned `ErrEndpointMissingData`, evaluated only once the round is complete. Sibling transport/infra errors do not block the count; a matching participant that returned data holds the quota. A policy that opts any entry in must keep at least one never-waivable `minAgreement > 0` floor (startup-enforced). Selected per request via a consensus-policy selector — see [Consensus policies](/config/failsafe/consensus-policies.llms.txt). | | `requiredParticipants[].waiveAgreementOnEmptyOutsideRetention` | bool | `false` | Opt-in per entry (v1.1 empty-waiver). Releases this entry's `minAgreement` quota for a round when **at least `minAgreement`** distinct tag-matching upstreams returned an **empty** result AND the block is proven outside retention. The block is the one the **client's request** names. A hash lookup (`eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockByHash`) names none, so the waiver takes the block number and hash the agreeing answer names, but only once an upstream outside the agreeing set returns that block for `eth_getBlockByNumber(, false)` with the same hash and the requested hash in it; the first upstream that returns the block decides, so agreeing upstreams cannot fabricate the proof. Tags such as `latest` never waive. Sibling errors do not block the empty count; a matching non-empty result holds the quota. Proof prefers each empty upstream's finite `blockAvailability` lower bound (`block < lower`, typically `poller.latest − latestBlockMinus`); if that is unavailable, falls back to `head - block > retentionBlocks` where head is the majority network served tip when `evm.servedTip.enabledFor` includes `"latest"`, otherwise the min corroborated poller latest among this round's EVM participants (≥2 positive latests; a single poller fails closed). Default max-mode served tip is not trusted. A null on a **recent** block (inside bounds / retention) still holds the quota and disputes. Round-complete like the MissingData waiver. Requires `retentionBlocks > 0` (startup-enforced). Align internal `latestBlockMinus` with `retentionBlocks` so the preferred avail-bound proof matches the fallback depth. Must sit alongside a never-waivable floor. | | `requiredParticipants[].retentionBlocks` | int64 | `0` (disabled) | Depth in blocks behind the observed chain head for the **chain-head fallback** proof (outside iff `head - requestedBlock > retentionBlocks`). Preferred proof uses each abstainer's `blockAvailability` lower bound when finite. Must be `> 0` when `waiveAgreementOnEmptyOutsideRetention` is set. Negative is a startup error. | | `blockEvidenceFields` | `map[string][]string` | `nil` (disabled) | **Unsafe opt-in.** Per-method response paths holding the winning answer's own block number (e.g. `{ "eth_getTransactionReceipt": ["blockNumber"] }`): `"result"`, a flat field, or `"*.field"` (max across an array result). When the request names no block and no upstream outside the agreeing set confirms the answer's block, the empty-outside-retention waiver trusts this one. The agreeing upstreams then vouch for their own claim, so two that collude can get a fabricated old tx or receipt served. A non-winner that returns a different block still fails the round closed. A path also listed in `ignoreFields`, or a nested path, is a startup error. | | `punishMisbehavior` | \*PunishMisbehaviorConfig | `nil` (disabled) | Enables cordon punishment for persistent misbehavior. | | `punishMisbehavior.disputeThreshold` | uint | **Required** >0 | Token bucket capacity per `disputeWindow`. No `SetDefaults` entry — must be explicitly set; omitting is a startup validation error. | | `punishMisbehavior.disputeWindow` | Duration | **Required** >0 | Token bucket window. Validated at startup AND guarded at runtime: `<= 0` silently disables punishment with a debug log. | | `punishMisbehavior.sitOutPenalty` | Duration | — | Cordon duration. `upstream.Uncordon` is called automatically after expiry. | | `misbehaviorsDestination` | \*MisbehaviorsDestinationConfig | `nil` (disabled) | Export target for misbehavior JSONL records. | | `misbehaviorsDestination.type` | string | `"file"` ([`common/defaults.go:L2460-2462`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2460-L2462)) | `"file"` or `"s3"`. When `type: "s3"` is set, `SetDefaults` auto-creates the `s3` sub-block as `&S3FlushConfig{}` if it is nil — you do not need to provide an empty `s3:` block. ([`common/defaults.go:L2468-2471`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2468-L2471)) | | `misbehaviorsDestination.path` | string | — | For `file`: absolute directory path (created with `0o750`; must be absolute). For `s3`: `s3://bucket/prefix/`. | | `misbehaviorsDestination.filePattern` | string | `"{timestampMs}-{instanceId}-{method}-{networkId}"` ([`common/defaults.go:L3184-3188`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L3184-L3188)) | Filename template. Tokens: `{dateByHour}` (UTC `2006-01-02-15`), `{dateByDay}`, `{method}`, `{networkId}`, `{instanceId}`, `{timestampMs}`, `{policy}` (hex-encoded consensus policy name — injective so `a/b` and `a_b` cannot collide; required with `{timestampMs}` when multiple policies share an S3 path). Always appends `.jsonl` if no recognized extension. `{instanceId}` derived from `INSTANCE_ID` → `POD_NAME` → `HOSTNAME` → SHA256 hash of `now+pid`. | | `misbehaviorsDestination.s3.maxRecords` | int | `100` ([`common/defaults.go:L2472-2474`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2472-L2474)) | Flush when any per-key buffer has ≥ this many records. | | `misbehaviorsDestination.s3.maxSize` | int64 | `1048576` (1 MiB) ([`common/defaults.go:L2475-2477`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2475-L2477)) | Flush when any per-key buffer reaches this byte count. | | `misbehaviorsDestination.s3.flushInterval` | Duration | `"60s"` ([`common/defaults.go:L2478-2480`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2478-L2480)) | Periodic flush regardless of thresholds. | | `misbehaviorsDestination.s3.region` | string | `""` → SDK default chain | AWS region. | | `misbehaviorsDestination.s3.contentType` | string | `"application/jsonl"` ([`common/defaults.go:L2481-2483`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2481-L2483)) | `Content-Type` for S3 `PutObject`. | | `misbehaviorsDestination.s3.credentials.mode` | string | `""` → SDK default chain | `"secret"` (static key+secret), `"file"` (credentials file+profile), `"env"` (env vars), `""` (full SDK chain: env → `~/.aws/credentials` → IMDS). | | `misbehaviorsDestination.s3.credentials.accessKeyID` | string | — | **YAML key is `accessKeyID` (capital D)**. Using `accessKeyId` (lowercase d) silently falls back to SDK chain. | | `misbehaviorsDestination.s3.credentials.secretAccessKey` | string | — | Used when `mode: "secret"`. | | `misbehaviorsDestination.s3.credentials.credentialsFile` | string | — | Used when `mode: "file"`. | | `misbehaviorsDestination.s3.credentials.profile` | string | — | Used when `mode: "file"`. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Standard 3-of-2 agreement for unfinalized log and receipt reads.** The most common production shape: fan out to 3 upstreams, require 2 to agree, accept the majority on disputes. Used on Base, Ethereum mainnet, Blast, and Sonic for `eth_getLogs` and `eth_getBlockReceipts` on recent (unfinalized) blocks where reorg-detection matters. `preferLargerResponses: false` is deliberate — keeping it `false` preserves the `unassailable_lead` short-circuit (returns as soon as 2 agree, without waiting for the 3rd), cutting worst-case latency significantly: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: "unfinalized" consensus: maxParticipants: 3 agreementThreshold: 2 disputeBehavior: acceptMostCommonValidResult lowParticipantsBehavior: acceptMostCommonValidResult # false keeps the unassailable_lead short-circuit active: # once 2 of 3 agree, eRPC returns immediately without # waiting for the third upstream to finish preferLargerResponses: false preferNonEmpty: true ignoreFields: eth_getLogs: - "*.blockTimestamp" eth_getTransactionReceipt: - "blockTimestamp" - "logs.*.blockTimestamp" - "l1Fee" - "l1GasUsed" eth_getBlockReceipts: - "*.blockTimestamp" - "*.l1Fee" - "*.l1GasUsed" ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: "unfinalized", consensus: { maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "acceptMostCommonValidResult", lowParticipantsBehavior: "acceptMostCommonValidResult", // false keeps the unassailable_lead short-circuit active: // once 2 of 3 agree, eRPC returns immediately without // waiting for the third upstream to finish preferLargerResponses: false, preferNonEmpty: true, ignoreFields: { eth_getLogs: ["*.blockTimestamp"], eth_getTransactionReceipt: [ "blockTimestamp", "logs.*.blockTimestamp", "l1Fee", "l1GasUsed", ], eth_getBlockReceipts: ["*.blockTimestamp", "*.l1Fee", "*.l1GasUsed"], }, }, }] ``` **2. Highest-value consensus for fee and nonce reads.** The standard production pattern for preventing stale-low fee estimates and stuck nonces: fan out to 4 upstreams and return whichever reports the highest value. The `noBehaviors` pattern (omitting `disputeBehavior`/`lowParticipantsBehavior`) is intentional — with `preferHighestValueFor` active, dispute/low-participant rules never fire because the numeric-value rule evaluates first. Used in production for every EVM chain that accepts writes: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_gasPrice|eth_maxPriorityFeePerGas" consensus: maxParticipants: 4 agreementThreshold: 1 # ignoreFields: null — hash-based grouping is irrelevant when # preferHighestValueFor regrouping by numeric value is active preferHighestValueFor: eth_gasPrice: - result eth_maxPriorityFeePerGas: - result - matchMethod: "eth_getTransactionCount" hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s retry: maxAttempts: 6 delay: 0 consensus: maxParticipants: 4 agreementThreshold: 1 preferHighestValueFor: eth_getTransactionCount: - result ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_gasPrice|eth_maxPriorityFeePerGas", consensus: { maxParticipants: 4, agreementThreshold: 1, // ignoreFields not set — hash-based grouping is irrelevant when // preferHighestValueFor regrouping by numeric value is active preferHighestValueFor: { eth_gasPrice: ["result"], eth_maxPriorityFeePerGas: ["result"], }, }, }, { matchMethod: "eth_getTransactionCount", hedge: { quantile: 0.95, maxCount: 1, minDelay: "500ms", maxDelay: "10s" }, retry: { maxAttempts: 6, delay: 0 }, consensus: { maxParticipants: 4, agreementThreshold: 1, preferHighestValueFor: { eth_getTransactionCount: ["result"] }, }, }, ] ``` **3. `eth_sendRawTransaction` broadcast with fire-and-forget.** Return the first accepted tx hash immediately while the remaining upstream goroutines continue broadcasting in background using `context.WithoutCancel`. Rule 1 fires as soon as any single non-empty response exists — the threshold is bypassed entirely. In production, `maxParticipants: 10` is paired with `hedge.maxCount: 2` so the hedge races 3 upstreams simultaneously, with remaining slots filling in asynchronously. Account for these goroutines in graceful shutdown timeout budgets — process shutdown signals do not reach them: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_sendRawTransaction" hedge: quantile: 0.95 maxCount: 2 minDelay: 50ms maxDelay: 1s retry: maxAttempts: 6 delay: 0 consensus: maxParticipants: 10 # threshold 1: Rule 1 fires on first non-empty anyway, # but setting 1 makes the intent explicit agreementThreshold: 1 # goroutines continue after first hash is returned to client fireAndForget: true ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_sendRawTransaction", hedge: { quantile: 0.95, maxCount: 2, minDelay: "50ms", maxDelay: "1s" }, retry: { maxAttempts: 6, delay: 0 }, consensus: { maxParticipants: 10, // threshold 1: Rule 1 fires on first non-empty anyway, // but setting 1 makes the intent explicit agreementThreshold: 1, // goroutines continue after first hash is returned to client fireAndForget: true, }, }] ``` **4. State-trie integrity checks for high-value reads.** For Ethereum mainnet balance and call reads, production uses a strict 2-of-2 check: both participants must agree or the result is disputed. A tighter quorum (2/2 vs 2/3) makes it easier to detect a single rogue node, and `disputeLogLevel: "error"` escalates disagreements for alerting. `ignoreFields: null` is intentional — balance and call results have no metadata variance, so the default timestamp exclusions would only mask real bugs: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getBalance|eth_call" matchFinality: "unfinalized" timeout: duration: 60s hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s retry: maxAttempts: 6 delay: 0 consensus: maxParticipants: 2 agreementThreshold: 2 # error-level so a PagerDuty alert fires on any balance/call mismatch disputeLogLevel: "error" # null: no ignoreFields — balance and call results have no timestamp # variance; omitting fields would only mask genuine disagreements ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getBalance|eth_call", matchFinality: "unfinalized", timeout: { duration: "60s" }, hedge: { quantile: 0.95, maxCount: 1, minDelay: "500ms", maxDelay: "10s" }, retry: { maxAttempts: 6, delay: 0 }, consensus: { maxParticipants: 2, agreementThreshold: 2, // error-level so a PagerDuty alert fires on any balance/call mismatch disputeLogLevel: "error", // no ignoreFields: balance and call results have no timestamp variance; // omitting fields here would only mask genuine disagreements }, }] ``` **5. Misbehavior tracking with S3 export and automatic cordon.** Used in production for Base `eth_getLogs` to detect and penalize upstreams that consistently return bad data. After 3 disputes within 5 minutes the offender is cordoned for 10 minutes. `{dateByHour}` in `filePattern` groups disputes by hour — each hourly flush overwrites the S3 object for that key, so use `{timestampMs}` if per-flush objects are preferred. The 100 MiB `maxSize` guard prevents unbounded memory use during high-dispute periods: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: "unfinalized" consensus: maxParticipants: 3 agreementThreshold: 2 disputeBehavior: acceptMostCommonValidResult punishMisbehavior: # 3 disputes within 5 minutes triggers a cordon disputeThreshold: 3 disputeWindow: 5m # cordon for 10 minutes then auto-uncordon sitOutPenalty: 10m misbehaviorsDestination: type: s3 path: "s3://\${S3_BUCKET}/misbehaviors/mainnet/" filePattern: "{dateByHour}-{method}" s3: region: "\${AWS_REGION}" # flush at 100 records, 100 MiB, or every hour maxRecords: 100 maxSize: 104857600 flushInterval: 1h ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: "unfinalized", consensus: { maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "acceptMostCommonValidResult", punishMisbehavior: { // 3 disputes within 5 minutes triggers a cordon disputeThreshold: 3, disputeWindow: "5m", // cordon for 10 minutes then auto-uncordon sitOutPenalty: "10m", }, misbehaviorsDestination: { type: "s3", path: \`s3://\${S3_BUCKET}/misbehaviors/mainnet/\`, filePattern: "{dateByHour}-{method}", s3: { region: process.env.AWS_REGION, // flush at 100 records, 100 MiB, or every hour maxRecords: 100, maxSize: 104857600, flushInterval: "1h", }, }, }, }] ``` ### Request/response behavior - Consensus wraps the composed `retry(hedge(tryOneUpstream))` inner function. Retry and hedge still fire per participant slot; the consensus layer sees only the final result from each slot. - A dispute produces `ErrConsensusDispute`: JSON-RPC wire code `-32603`, HTTP method-level status `409 Conflict` (wire status `200` for POST JSON-RPC). The `Cause` is `errors.Join(per-participant errors)`. Retryability: if ANY child error is retryable, the whole dispute error is retryable toward the network. - A low-participants outcome produces `ErrConsensusLowParticipants`: JSON-RPC wire code `-32603`, HTTP method-level status `412 Precondition Failed` (wire status `200`). Same multi-error retryability rule. - The `SkipConsensus` directive (`X-ERPC-Skip-Consensus: true` or `?skip-consensus=true`) causes the executor to skip the consensus branch entirely. Retry, hedge, circuit breaker, and timeout still apply. Only the string `"true"` activates bypass. - Within a consensus group, `group.LargestResult` is returned as the winner — not the first response received. This ensures the most complete representation is selected when multiple upstreams agree on the same canonical hash. - When `preferHighestValueFor` is configured for a method, responses are regrouped by extracted numeric value (not hash), allowing differently-formatted representations of the same value to match. ### Best practices - Start with `maxParticipants: 3` and `agreementThreshold: 2`. Adding more participants increases coverage but raises cost and worst-case latency. - Disable `preferLargerResponses` in latency-sensitive scenarios — it disables all short-circuit and forces every request to wait for all participants. - When extending `ignoreFields`, always re-include all three default entries (`eth_getLogs`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`). Setting any entry replaces the entire map; omitting defaults causes spurious disputes on `blockTimestamp` fields. - Set `disputeLogLevel: "warn"` (it is the default, but set it explicitly). Zerolog's zero value is `TraceLevel`; an unset field gets coerced to `WarnLevel` by the builder, which may mask trace-level intent. - Use `fireAndForget: true` only for `eth_sendRawTransaction` broadcast. For read methods it wastes upstream capacity after the winner is known. Account for these goroutines in graceful shutdown timeout budgets — process shutdown signals do not reach them. - For `punishMisbehavior`, set `disputeWindow` conservatively (e.g., `5m`) and `disputeThreshold` to at least 3. A too-tight window with threshold 1 will cordon flapping nodes on the first transient disagreement. - Monitor `erpc_consensus_wait_capped_total{trigger}` — frequent `"result"` firings mean your `maxWaitOnResult` is too short for the slowest participants; frequent `"empty"` firings indicate slow cold paths. ### Edge cases & gotchas 1. **`ignoreFields` is full set replacement.** Adding one method removes all three built-in entries. Spurious disputes on `blockTimestamp` fields result. Always re-include all default entries when extending the map. ([`consensus/analysis.go:L442-453`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L442-L453)) 2. **`preferLargerResponses` disables all short-circuit.** Even a clear majority above threshold does not short-circuit because a larger response may still arrive. Disable in latency-sensitive scenarios. 3. **`eth_sendRawTransaction` bypasses threshold entirely.** Rule 1 fires on any single non-empty response regardless of how many others errored. Intentional for tx broadcasting. 4. **`preferNonEmpty` + `returnError` escalates empty threshold winner to dispute.** When empty meets threshold, non-empty minority exists, and `preferNonEmpty: true` under `disputeBehavior: returnError`, the result is a dispute — not the empty winner and not the minority non-empty. (Rule 11). Under `acceptMostCommon`, the same empty-vs-non-empty above-threshold setup always returns the non-empty: Rule 7 keys off "any empty/error group ≥ threshold + any non-empty exists", not `getBestByCount()`, so equal counts cannot fall through to the generic threshold winner and pick empty via map iteration order. ([`consensus/rules.go:L290-330`](https://github.com/erpc/erpc/blob/main/consensus/rules.go#L290-L330)) 5. **Tie among non-empty at/above threshold without preference → dispute.** Rule 8 fires before the generic threshold-winner rule 19. Enable `preferLargerResponses` to resolve ties by size. 6. **`requiredParticipants` shortfall is silent.** No warning, no metric, no error. Operators cannot distinguish tag-quota shortfall from general upstream unavailability in current observability output. 7. **`fireAndForget` goroutines survive graceful shutdown.** `context.WithoutCancel` strips shutdown signals. Shutdown waits for in-flight analyzers only until the shutdown budget (35s plus `waitBeforeShutdown` and `waitAfterShutdown`). If they are still running when that budget expires, exporters are left open and process exit is the fallback — closing them earlier would race the analyzer. Budget shutdown timeouts to account for in-flight fire-and-forget participants. ([`consensus/consensus.go:L151-190`](https://github.com/erpc/erpc/blob/main/consensus/consensus.go#L151-L190)) 8. **S3 uses `PutObject`, not append.** With `{dateByHour}` in `filePattern`, flushes within the same hour overwrite the previous S3 object. Use `{timestampMs}` if each flush should create a new object. 9. **S3 `accessKeyID` casing is load-bearing.** YAML key must be `accessKeyID` (capital D). Lowercase `accessKeyId` silently falls back to the SDK credential chain. 10. **File export requires absolute path.** Relative paths are rejected at startup. ([`consensus/export.go:L37-41`](https://github.com/erpc/erpc/blob/main/consensus/export.go#L37-L41)) 11. **`disputeLogLevel` zero value coerces to warn.** Set `"trace"` explicitly if trace-level dispute logging is required. 12. **`ErrConsensusDispute` is retryable when any child error is retryable.** A dispute caused partly by a retryable upstream error propagates retryability to the caller. 13. **Misbehavior punishment only when majority consensus.** `shouldPunishUpstream` requires `consensusGroup.Count > validParticipants / 2`. With 2 of 5 agreeing (2 > 2 fails), punishment is blocked. ([`consensus/executor.go:L1196`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L1196)) 14. **`ErrUpstreamsExhausted` wrapping foreign consensus errors.** Without a guard, `HasErrorCode` traversal would misclassify exhausted errors as `ResponseTypeConsensusError`, creating phantom voting groups. The explicit check at [`consensus/analysis.go:L376-386`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L376-L386) prevents this. 15. **Context cancellation after all executions does NOT produce LowParticipants.** When the parent context is cancelled after every participant has completed but before outcome delivery, the non-blocking try-receive picks up the computed outcome rather than treating it as abandonment. ([`consensus/executor.go:L271-279`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L271-L279)) 16. **Cold start for wait caps.** `AdaptiveDuration.Resolve` falls back to `min` when no latency data exists. If you configure `maxWaitOnResult: {quantile: 0.5, max: 1s}` without a `min`, cold start returns 0 — no cap until data accumulates. 17. **S3 startup validation.** `newS3MisbehaviorExporter` calls `HeadBucket` synchronously. If the bucket is unreachable, S3 export is disabled and an error is logged — consensus continues normally. 18. **`omitting minParticipants` in `requiredParticipants` is a startup error.** Go leaves unset `int` at 0, which immediately fails the `> 0` validation. The server will not start. 19. **`IsTie` flag on response groups is per-type, per-count.** `responseGroup.IsTie` is `true` when at least two groups of the same `ResponseType` share the same `Count`. Infrastructure error groups always have `IsTie = false`. This flag is used by the `lowParticipants + acceptMostCommon` rule to escalate non-empty ties to dispute instead of returning an arbitrary winner. ([`consensus/analysis.go:L121-138`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L121-L138)) 20. **Race-free analysis struct.** `newConsensusAnalysis` pre-populates all cached accessor fields before returning. After the analyzer sends the outcome to the caller, both goroutines may read the analysis concurrently (caller for metrics; analyzer for misbehavior tracking). Lazy-init under concurrent reads would be a data race. ([`consensus/analysis.go:L141-153`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L141-L153)) 21. **`preferHighestValueFor` can be combined per-method with hash-based consensus.** The map allows different handling per method — `eth_getTransactionCount: ["result"]` uses highest-value while `eth_call` falls through to normal hash-based consensus on the same failsafe entry. The rule only matches when at least one valid group has extractable numeric values; if extraction fails for all responses it falls through to subsequent rules. 22. **`ErrConsensusDispute` and `ErrConsensusLowParticipants` error contracts.** `ErrConsensusDispute` has HTTP method-level status `409 Conflict` and JSON-RPC wire code `-32603`; `ErrConsensusLowParticipants` has HTTP method-level status `412 Precondition Failed` and the same wire code. Wire HTTP status for POST JSON-RPC is `200` in both cases (errors are translated to JSON-RPC at the transport layer). Both errors carry `errors.Join(per-participant errors)` as their `Cause`; retryability propagates from children — if ANY child error is retryable, the whole dispute or low-participants error is retryable toward the network. `ErrConsensusLowParticipants.DeepestMessage()` includes per-participant info. 23. **Consensus-slot hedge keeps an empty vote only when the empty-outside-retention waiver can fire.** Each participant is `retry(hedge(tryOneUpstream))`. Hedge `keep` rejects `{"result": null}` on tx/block lookups so a lagging node does not cancel a sibling with data — correct for a sweep, wrong for a consensus slot when the empty must count toward waiver proof. The recovery leg then returns `n/a` `ErrUpstreamsExhausted` (other slots already consumed the remaining upstreams). `X-ERPC-Upstreams` can still show `consensus_slot:empty:won` from the discarded primary, while `analysis.groups` has no tagged empty and `erpc_consensus_composition_waived_total{reason=empty_outside_retention}` stays at zero. Empty is retained as the slot vote **only when** the selected policy opts into `requiredParticipants[].waiveAgreementOnEmptyOutsideRetention` **and** the waiver can get a block: the request names a concrete block number, it is a hash lookup whose answer names a block (`eth_getTransactionByHash`, `eth_getTransactionReceipt`, `eth_getBlockByHash`), or the policy lists the method in `blockEvidenceFields`. Otherwise prior empty-reject behavior remains. Skip-consensus never keeps that empty. Source: [`erpc/network_executor.go:L765`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L765) / `erpc/networks_hedge_cancel_test.go` (`TestHedgeConsensus_EmptyOldBlockIsKeptAsSlotVote`). 24. **Empty-outside-retention prefers abstainer availability bounds.** When internals declare `blockAvailability.lower.latestBlockMinus`, the waiver can prove `requestedBlock < lower` without a network `servedTip`. Align that minus with `retentionBlocks`. If bounds are unbounded and `chainHead` is 0, the round fail-closes and increments `erpc_consensus_composition_waiver_unproven_total` (info log). Source: [`consensus/executor.go:L1413`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L1413). 25. **Hash-lookup confirmer probe is skipped when the answer cannot prove outside retention.** Before `eth_getBlockByNumber` to a non-winner, the waiver checks whether the answer's claimed block number — even if trusted — fails both availability-bound and chain-head proofs for every opted-in abstaining quota (the common just-mined / inside-retention dispute). That skip never feeds the claimed number into the waiver; it only avoids I/O. It also skips the `blockEvidenceFields` fallback so a divergent evidence path cannot waive an older number without a confirmer. Source: [`consensus/waiver_block.go:L32`](https://github.com/erpc/erpc/blob/main/consensus/waiver_block.go#L32) / `consensus/composition_waiver_e2e_test.go` (`inside-retention hash lookup skips the confirmer probe`, `inside-retention skip does not trust divergent evidence`). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_consensus_total` | Counter | `project`, `network`, `category`, `outcome`, `finality` | Every `Run` completion. `outcome`: `success`, `consensus_on_error`, `dispute`, `low_participants`, `generic_error`, `caller_abandoned`. | | `erpc_consensus_duration_seconds` | Histogram | same as total | Duration of each `Run`. Buckets: `[0.05, 0.5, 5, 30]`. | | `erpc_consensus_errors_total` | Counter | `project`, `network`, `category`, `error`, `finality` | When result is an error. | | `erpc_consensus_agreement_count` | Histogram | `project`, `network`, `category`, `finality` | Best group count per round. Buckets: linear 1–10. | | `erpc_consensus_responses_collected` | Histogram | `project`, `network`, `category`, `vendors`, `short_circuited`, `finality` | After all responses collected. `vendors` is comma-joined sorted vendor names. Buckets: linear 1–10. | | `erpc_consensus_short_circuit_total` | Counter | `project`, `network`, `category`, `reason`, `finality` | When short-circuit fires. `reason`: `sendrawtx_first_success`, `consensus_error_threshold`, `unassailable_lead`. | | `erpc_consensus_wait_capped_total` | Counter | `project`, `network`, `category`, `trigger`, `finality` | When `maxWaitOnResult` or `maxWaitOnEmpty` fires. `trigger`: `"result"` or `"empty"`. | | `erpc_consensus_misbehavior_detected_total` | Counter | `project`, `network`, `upstream`, `category`, `finality`, `response_type`, `larger_than_consensus` | Per misbehaving upstream per round. | | `erpc_consensus_upstream_punished_total` | Counter | `project`, `network`, `upstream` | When an upstream is cordoned for misbehavior. | | `erpc_consensus_upstream_errors_total` | Counter | `project`, `network`, `upstream`, `category`, `finality`, `response_type`, `error_code` | Per upstream per round when upstream has a consensus or infra error disagreeing with the consensus group. | | `erpc_consensus_composition_waived_total` | Counter | `project`, `network`, `tag`, `reason` | A `requiredParticipants[].minAgreement` quota was waived because at least `minAgreement` tag-matching participants returned the waived signal. `reason`: `missing_data` (v1) or `empty_outside_retention` (v1.1). A step change is a security signal, not only availability — alert on it. | | `erpc_consensus_composition_waiver_unproven_total` | Counter | `project`, `network`, `reason` | Empty-outside-retention waiver held the quota because proof was unavailable (fail closed). `reason`: `no_request_block` (no block in the request or the answer), `block_unconfirmed` (no upstream outside the winners returned the answer's block), `block_contradicted` (one did and it disagrees with the winners — a security signal), `no_avail_bound`, or `no_head`. Hash lookups whose answer already names a block that cannot prove outside retention (head depth and availability bounds) skip the confirmer probe and do **not** increment this counter — that is an evaluated inside-retention hold, not missing proof. | | `erpc_consensus_cancellations_total` | Counter | `project`, `network`, `category`, `phase`, `finality` | `phase`: `before_execution`, `after_execution`, `caller_abandoned`. | | `erpc_consensus_panics_total` | Counter | `project`, `network`, `category`, `finality` | Per panic recovery in participant or analyzer goroutine. | **OTel trace spans:** | Span | Attributes | Notes | |---|---|---| | `Consensus.Run` | `network.id`, `request.method`, `consensus.outcome`, `consensus.achieved`, `participants.total`, `participants.valid` | Top-level span for the entire consensus operation. | | `Consensus.CollectResponses` | `short_circuited` (bool), `wait_capped` (bool), `responses.collected` (int) | Child span from first goroutine spawn to all-responses-collected. | **Notable log messages:** `"consensus rule matched"` (debug, per rule match), `"consensus misbehavior detected - upstreams differ from consensus"` (at `disputeLogLevel`, when `misbehavingCount > 0`; includes full participant breakdown with numbered keys `upstream1`, `responseType1`, `agreesWithConsensus1`, etc.), `"fire-and-forget mode: remaining requests complete in background"` (debug, on short-circuit when `fireAndForget: true`), `"misbehaviour limit exhausted, punishing upstream"` (warn), `"upstream already in sitout, skipping"` (debug, when punishment attempted but upstream already cordoned), `"consensus caller abandoned; analysis continues in background"` (warn), `"panic in consensus analyzer"` / `"Panic in consensus participant"` (error), `"failed to append misbehavior record"` (warn, when exporter errors), `"failed to initialize S3 misbehavior exporter; export disabled"` (error, S3 setup failure at init time — consensus continues normally), `"uploaded misbehavior records to S3"` (info, after each successful S3 PutObject), `"failed to upload misbehavior records to S3"` (error, on S3 PutObject failure). ### Source code entry points - [`consensus/consensus.go`](https://github.com/erpc/erpc/blob/main/consensus/consensus.go) — `Consensus` struct, `NewConsensus`, entry-point `Run` - [`consensus/executor.go`](https://github.com/erpc/erpc/blob/main/consensus/executor.go) — `executeConsensus` (fan-out, wait caps, context racing), `runAnalyzer` (collection loop, short-circuit, misbehavior tracking), `executeParticipant`, `trackAndPunishMisbehavingUpstreams` - [`consensus/analysis.go`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go) — `newConsensusAnalysis` (classify, hash, group), `classifyAndHashResponse`, `errorToConsensusHash`, `LargestResult` tracking - [`consensus/rules.go`](https://github.com/erpc/erpc/blob/main/consensus/rules.go) — `consensusRules` (24 rules) and `shortCircuitRules` (3 rules); all decision logic - [`consensus/quota.go`](https://github.com/erpc/erpc/blob/main/consensus/quota.go) — `reorderForParticipantQuota`, `upstreamMatchesTag` (glob matching) - [`consensus/export.go`](https://github.com/erpc/erpc/blob/main/consensus/export.go) — `misbehaviorExporter` interface, `fileMisbehaviorExporter`, JSONL record structs - [`consensus/export_s3.go`](https://github.com/erpc/erpc/blob/main/consensus/export_s3.go) — `s3MisbehaviorExporter`, buffered per-key S3 uploads with background flush worker - [`consensus/export_utils.go`](https://github.com/erpc/erpc/blob/main/consensus/export_utils.go) — `resolveFilePattern`/`resolveFilePatternWithDefaults`, `getInstanceID` (cached singleton using `INSTANCE_ID` → `POD_NAME` → `HOSTNAME` → SHA256 hash of now+pid), `sanitizeForFilename`, `parseS3Path` - [`consensus/utils.go`](https://github.com/erpc/erpc/blob/main/consensus/utils.go) — `extractFieldValues`, `parseNumericValue`, `valuesToKey`, `compareValueChains` for `preferHighestValueFor` logic - [`erpc/network_executor.go#L183-L188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L183-L188) — Integration point: routing to `consensus.Run` vs. `retry(hedge(runUpstreamSweep))` - [`common/config.go#L1591-L1658`](https://github.com/erpc/erpc/blob/main/common/config.go#L1591-L1658) — `ConsensusPolicyConfig`, `ConsensusRequiredParticipant`, `MisbehaviorsDestinationConfig`, `S3FlushConfig`, `PunishMisbehaviorConfig` - [`common/defaults.go#L2389-L2487`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2389-L2487) — `ConsensusPolicyConfig.SetDefaults` and `MisbehaviorsDestinationConfig.SetDefaults` - [`consensus/executor_test.go`](https://github.com/erpc/erpc/blob/main/consensus/executor_test.go) — behavior-locking tests incl. context-cancel-after-execution and misbehavior tracking ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — wraps each consensus participant slot; each retry attempt is a fresh hedge race inside consensus. - [Hedge](/config/failsafe/hedge.llms.txt) — also wraps each participant slot; hedges individual upstream attempts within a slot. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds the whole consensus race from outside. - [Consensus policies](/config/failsafe/consensus-policies.llms.txt) — pick a named consensus rule-set per request with a pre-round JS selector (strategy-gated grades, availability fallback, MissingData waivers), failing closed to the strictest policy. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — decides which upstreams are drawn for participant slots. - [Rate limiters](/config/rate-limiters.llms.txt) — caps per-upstream cost from the extra fan-out requests. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the reliability outcome consensus reinforces. --- --- # Hedge > Source: https://docs.erpc.cloud/config/failsafe/hedge > When a provider is having a slow moment, eRPC quietly races a backup request — your slowest responses simply disappear. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Hedge Every provider is occasionally slow — and your users feel it as that one spinning page. Hedging fixes the tail: if an answer hasn't arrived quickly, eRPC silently starts a backup request on another provider and returns whichever finishes first. Median cost stays the same; the slow tail collapses. ![Hedge effectiveness diagram showing tail latency reduction](./images/hedged-requests-effectiveness.png) ## Quick taste Illustrative, not a tuned production config — hedge after 200ms of silence: **Config path:** `projects[].networks[].failsafe[].hedge` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } failsafe: - matchMethod: "*" # race a backup request once the primary is 200ms silent hedge: delay: 200ms maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, failsafe: [{ matchMethod: "*", // race a backup request once the primary is 200ms silent hedge: { delay: "200ms", maxCount: 1 }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: cut tail latency on reads** ```text Reduce p99 latency of my eth_call and eth_getLogs requests even if it creates more upstream requests, using eRPC's Hedge feature. Use a quantile-based delay so fast methods don't get needlessly hedged, with sane min/max clamps. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/failsafe/hedge.llms.txt ``` **Prompt Example #2: audit my hedge cost vs benefit** ```text Audit the hedging setup in my eRPC config: for each failsafe entry tell me how often hedges are expected to fire and whether maxCount/min/max make sense, and which Prometheus metrics to check to measure the hedge win-rate vs the extra upstream cost (watch out: one registered hedge metric is dormant). Reference: https://docs.erpc.cloud/config/failsafe/hedge.llms.txt ``` **Prompt Example #3: faster transaction propagation** ```text I want my eth_sendRawTransaction submissions to propagate to the network faster. Configure eRPC to broadcast the raw transaction to multiple upstreams in parallel using Hedge (sendRawTransaction is idempotent so this is safe). Keep other write methods un-hedged. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/hedge.llms.txt ``` **Prompt Example #4: stop wasteful hedges on tx lookups** ```text My eRPC instance fans out a lot of duplicate eth_getTransactionReceipt / eth_getTransactionByHash calls when a transaction isn't indexed yet — hedging a not-found tx just multiplies load. Add a failsafe entry that disables hedging for these two methods while keeping the catch-all hedge for everything else. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/hedge.llms.txt ``` **Prompt Example #5: explain hedge behavior I'm seeing** ```text Many of my eRPC responses have X-ERPC-Hedges: 1 right after deploys, then it calms down. Explain why (cold-start quantile behavior), and adjust my config so hedges don't fire immediately on fresh pods. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/hedge.llms.txt ``` --- ### Hedge — full agent reference ### How it works The hedge implementation lives in `failsafe/hedge.go` as a generic `RunHedged[R]` function. At network scope, `networkExecutor.runHedge` wraps the upstream-sweep function and calls `RunHedged`. The executor composition for non-consensus requests is `retry(hedge(runUpstreamSweep))`: each retry attempt fires a fresh hedge race. For consensus requests it is `consensus(retry(hedge(tryOneUpstream)))` where the hedge races individual upstream slots. The primary attempt fires immediately (goroutine 0). A pooled timer arms to `delayFn(1)`. If the primary has not produced a kept result by the time the timer fires, a second goroutine starts (hedge 1). This repeats until `fired-1 >= maxCount`. All goroutines share a `siblingCtx` derived from `context.WithCancel(parentCtx)`; when a winner is selected `cancelAll()` propagates cancellation to every still-running sibling. The result channel is pre-allocated at `maxCount+1` capacity so goroutine sends never block. The `keep` predicate decides whether a result ends the race. It returns `false` for `ErrNoUpstreamsLeftToSelect` (leg exhausted its upstreams — siblings may still win), `false` for an empty `ErrUpstreamsExhausted`, and `false` for null/empty responses on methods that are not in the `emptyResultAccept` set (preventing a fast `{"result": null}` from cancelling siblings with real data). **Consensus slots keep that empty only when the selected policy opts into `waiveAgreementOnEmptyOutsideRetention`:** `tryOneUpstream` already picked one upstream, and the empty-outside-retention waiver keys on that node's empty vote — otherwise the recovery leg replaces it with `n/a` `ErrUpstreamsExhausted` and tagged empties never reach consensus analysis. Waiver-free consensus+hedge configs keep prior empty-reject recovery (fast null may lose to a hedge). Skip-consensus and non-consensus paths still reject those empties, with one exception: a null `eth_getTransactionReceipt` outside a consensus slot ends the race when **every routed upstream** answered it null (or cannot serve the method) and the request's head is **settled** until the last hedge would fire, `H = delay × maxCount` — the head block was first seen at least `H` ago, the next block's earliest time (head first seen plus the shorter of half a block and the shortest recent block-to-block step) is more than `H` away, no new block landed since the request started, and no by-hash answer showed a block above the head. A null receipt means "not mined yet", so a hedge within `H` could only find a receipt that a new block brought. So chains with blocks every 2 s or faster never settle at a 500 ms hedge (preconfirming flashblocks upstreams live there), and Ethereum settles only in the first half of its slot. An upstream still in flight in a sibling leg, or one that failed transiently (timeout, 429, 5xx), keeps the race. Non-retryable errors — execution reverts, client errors — are kept immediately as definitive. Any non-null success is kept and `MetricNetworkHedgeWinnerTotal` fires. **Delay modes.** Static mode: set `delay` to a plain duration string (`"200ms"`); the hedge fires exactly that long after the primary starts, and `min`/`max` are ignored when `quantile == 0`. Adaptive (quantile) mode: set `delay.quantile` between 0 and 1; the effective delay is `clamp(quantile_value + base, min, max)` using per-method latency data tracked by the network's `QuantileTracker`. As upstreams warm and cool the delay self-adjusts. Cold-start (no data yet) falls back to `min` — which `SetDefaults` auto-populates to `100ms` unless you override it. **Write-method exclusion.** `runHedge` short-circuits to a plain inner call (no hedging) for write methods, checking both architectures' guards. `evm.IsNonRetryableWriteMethod`: `eth_sendTransaction`, `eth_createAccessList`, `eth_submitTransaction`, `eth_submitWork`, `eth_newFilter`, `eth_newBlockFilter`, `eth_newPendingTransactionFilter`. `eth_sendRawTransaction` is intentionally NOT excluded — it supports idempotent broadcast under hedge. `svm.IsNonRetryableWriteMethod`: `sendTransaction`, `sendRawTransaction`, `requestAirdrop`. **Note the asymmetry** — the SVM raw-transaction path *is* excluded, so the hedged-broadcast pattern below is EVM-only. Solana broadcasts are same-signature idempotent on-chain, but hedging them burns vendor quota on duplicate submissions and breaks the documented single-broadcast guarantee; `requestAirdrop` mints per call and is genuinely non-idempotent. `simulateTransaction` is read-only and stays hedgeable. Method names cannot collide across the two sets (EVM is `eth_*`-prefixed, SVM is bare). Composite batch requests also skip hedging entirely. **Interaction with retry.** Retry wraps hedge: each retry attempt fires a fresh hedge race. If the primary fails before the first hedge delay fires, retry acts immediately without waiting for the timer. If a hedge is already in-flight when the primary fails, retry waits for the hedge race to complete before deciding whether to retry. ### Config schema All fields are under `networks[].failsafe[].hedge` (or `upstreams[].failsafe[].hedge`). Struct at [`common/config.go:L1489-1492`](https://github.com/erpc/erpc/blob/main/common/config.go#L1489-L1492). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `hedge.delay` | `Duration \| AdaptiveDuration` | — (no hedge if absent) | Scalar sets `base` only (static mode). Object `{base, quantile, min, max}` enables adaptive mode. After `SetDefaults`, if `min==0` it becomes `100ms`; if `max==0` it becomes `999s`. Source: [`common/config.go:L1490`](https://github.com/erpc/erpc/blob/main/common/config.go#L1490) | | `hedge.delay.base` | `Duration` | `0` | Static addend. When `quantile==0`, this is the entire delay. When `quantile>0`, added to the quantile value before clamping. A scalar shorthand sets this field exclusively. | | `hedge.delay.quantile` | `float64` | `0` (static mode) | Percentile queried from the per-method `QuantileTracker`. Valid range `[0, 1]`. When `> 0`, `base` or `max` must also be set (enforced by `AdaptiveDuration.validate` at [`common/adaptive_duration.go:L129`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L129)). At cache-connector scope (`failsafeForGets` / `failsafeForSets`) the quantile resolves against the connector's own per-(method, finality) latency window instead of network metrics — [`data/cache_executor.go:L204-207`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L204-L207). System template default: `0.7`. Source: [`common/adaptive_duration.go:L83-109`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L83-L109) | | `hedge.delay.min` | `Duration` | `100ms` (auto-set by `SetDefaults` when `0`) | Floor applied when `quantile>0`. Cold-start fallback when no latency data exists. **Footgun:** manually setting `min: 0` on a quantile-mode spec causes hedges to fire immediately on cold start. Source: [`common/defaults.go:L2324-2326`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2324-L2326) | | `hedge.delay.max` | `Duration` | `999s` (auto-set by `SetDefaults` when `0`) | Ceiling applied when `quantile>0`. Prevents a runaway quantile from deferring the hedge indefinitely. Source: [`common/defaults.go:L2327-2329`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2327-L2329) | | `hedge.maxCount` | `int` | `1` (from `SetDefaults`); system auto-template uses `2` | Max *additional* attempts beyond the primary. `maxCount=1` means 2 total concurrent requests. `maxCount=0` disables hedging silently (`HasHedge()` returns false). Negative values are treated as `0` inside `RunHedged`. **Footgun:** the system template (applied when no `projects` block exists) defaults to `2`; manual configs get `1`. Source: [`common/defaults.go:L2331-2337`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2331-L2337) | **Legacy sibling fields** (backward-compatible, folded into `delay.*` at parse time by [`common/config.go:L1555-1571`](https://github.com/erpc/erpc/blob/main/common/config.go#L1555-L1571)): | Legacy key | Maps to | Notes | |---|---|---| | `hedge.quantile` | `hedge.delay.quantile` | Only applied when `delay.quantile == 0` | | `hedge.minDelay` | `hedge.delay.min` | Only applied when `delay.min == 0` | | `hedge.maxDelay` | `hedge.delay.max` | Only applied when `delay.max == 0` | ```yaml # Legacy form — still valid, folded into delay.* at parse time hedge: quantile: 0.7 minDelay: 100ms maxDelay: 2s maxCount: 1 ``` **Mixed use (object + legacy siblings).** When `delay` is given as an object AND a legacy sibling is present, legacy siblings only fill sub-fields left at zero by the object form. The `delay` object always takes precedence for any sub-field it sets: ```yaml # delay.base and delay.quantile come from the object; # minDelay fills delay.min because the object left it at zero; # the bare quantile: 0.50 is IGNORED because delay.quantile is already 0.95 hedge: delay: base: 100ms quantile: 0.95 minDelay: 50ms # → delay.min = 50ms (object did not set min) quantile: 0.50 # → IGNORED (delay.quantile already 0.95 from object) maxCount: 1 ``` Source: [`common/config.go:L1507-1571`](https://github.com/erpc/erpc/blob/main/common/config.go#L1507-L1571) ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. The workhorse: p95 quantile hedge on all reads (recommended general shape).** Slow-tail methods hedge aggressively; consistently fast methods almost never hedge: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" hedge: delay: quantile: 0.95 # hedge only the slowest ~5% of each method's traffic min: 500ms # floor: don't race answers that normally return fast, # and don't pile on during block-availability races max: 10s # ceiling: slow methods (heavy getLogs) still get hedged maxCount: 1 # one backup is enough for tail-cutting; 2+ is for writes ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", hedge: { delay: { quantile: 0.95, min: "500ms", max: "10s" }, maxCount: 1, }, }] ``` **2. Bimodal latency (cache-hit ~5ms vs cache-miss ~1s).** A fixed delay either races every cache hit (too low) or never helps misses (too high). Quantile mode with clamps handles both populations automatically — this is the canonical case for `quantile + min + max`. **3. Aggressive clamps for hash-addressed lookups.** During live indexing, `eth_getBlockByHash` may return data on only some nodes — racing another node quickly is exactly right, so the clamps tighten by an order of magnitude: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getBlockByHash" hedge: delay: quantile: 0.95 min: 100ms # much lower floor: a null here is likely "this node doesn't # have it yet" — racing another node fast is the whole point max: 500ms maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getBlockByHash", hedge: { delay: { quantile: 0.95, min: "100ms", max: "500ms" }, maxCount: 1, }, }] ``` **4. Deliberately NO hedge for tx lookups.** A null `eth_getTransactionReceipt` / `eth_getTransactionByHash` usually means the tx isn't propagated/indexed yet — parallel-blasting more upstreams mostly repeats the same null. A hedged receipt lookup skips the hedge only while the head is settled (edge case 4): early in the slot of a chain slower than 4 × the hedge delay; `eth_getTransactionByHash` gets no such exception. Place the exclusion entry BEFORE the catch-all (first matching entry wins): **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt" retry: maxAttempts: 2 delay: 500ms # ~one block of patience instead of a hedge fan-out # no hedge key at all — hedging is off for this entry - matchMethod: "*" hedge: delay: { quantile: 0.95, min: 500ms, max: 10s } maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt", retry: { maxAttempts: 2, delay: "500ms" }, }, { matchMethod: "*", hedge: { delay: { quantile: 0.95, min: "500ms", max: "10s" }, maxCount: 1 }, }, ] ``` **5. Hedged broadcast for `eth_sendRawTransaction`.** The one write method hedging does NOT exclude — broadcasting an identical signed tx to several upstreams is idempotent and speeds up mempool propagation: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_sendRawTransaction" hedge: delay: quantile: 0.95 min: 50ms # near-immediate: goal is propagation, not tail-cutting max: 1s maxCount: 2 # 3 upstreams total receive the tx ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_sendRawTransaction", hedge: { delay: { quantile: 0.95, min: "50ms", max: "1s" }, maxCount: 2, }, }] ``` **6. Quantile hedge on cache-connector reads.** Cache connectors take their own failsafe via `failsafeForGets` / `failsafeForSets`. A quantile delay resolves against the connector's own latency — a 1-minute sliding window tracked per (method, finality) executor, fed only by completed operations ([`data/cache_executor.go:L14-20`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L14-L20)) — so the hedge tracks the shared cache's real speed (e.g. a remote gRPC cache connector). Before any samples exist the delay falls back to `base + min` ([`common/adaptive_duration.go:L96-101`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L96-L101)): **Config path:** `database.evmJsonRpcCache.connectors[].failsafeForGets[]` **YAML — `erpc.yaml`:** ```yaml connectors: - id: remote-cache driver: grpc failsafeForGets: - matchMethod: "*" timeout: duration: 400ms # a cache read must be fast or not worth it — # past this, going straight to upstreams is cheaper hedge: delay: quantile: 0.95 # p95 of this connector's own completed reads (1m window) min: 20ms # floor; also cold-start fallback (no samples → base+min) max: 200ms # a hedge later than this is pointless — timeout is 400ms maxCount: 1 retry: maxAttempts: 2 delay: "0" ``` **TypeScript — `erpc.ts`:** ```typescript connectors: [{ id: "remote-cache", driver: "grpc", failsafeForGets: [{ matchMethod: "*", timeout: { duration: "400ms" }, // p95 of this connector's own completed reads (1m window); // cold start (no samples) falls back to base+min hedge: { delay: { quantile: 0.95, min: "20ms", max: "200ms" }, maxCount: 1 }, retry: { maxAttempts: 2, delay: "0" }, }], }] ``` ### Request/response behavior - Each hedge fire (idx > 0) increments both `NetworkAttempts` and `NetworkHedges`; the final response carries `X-ERPC-Attempts` and `X-ERPC-Hedges` headers reflecting them. The primary attempt does NOT increment `NetworkHedges`. [[`erpc/network_executor.go:L631-641`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L631-L641)] - Losing legs are cancelled via context; their responses are released back to buffer pools (`r.Release()`), never surfaced to the client. [[`erpc/network_executor.go:L626-630`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L626-L630)] - A hedge race that ends with a non-retryable error (e.g. execution revert) returns that error verbatim — hedging never converts error shapes. - `MetricNetworkHedgeWinnerTotal` fires for every kept result, including when the primary wins without any hedge having fired. It identifies which upstream won the race. [[`erpc/network_executor.go:L553-570`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L553-L570)] - When all legs return unkept results, the final response is the **last** unkept result (not the first); each new unkept result replaces the previous `lastResult` until the race ends. [[`failsafe/hedge.go:L243-253`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L243-L253)] - Cancelled legs produce `ErrUpstreamHedgeCancelled` (error code #33) internally, with the message `"hedged request cancelled in favor of another upstream response"` and `upstreamId` in details. This error is retryable toward the network (U:yes N:yes); in `ErrUpstreamsExhausted.SummarizeCauses` it appears in the `cancelled` bucket, producing log summaries like `"exhausted(cancelled=2)"`. [[`common/errors.go:L1447-1462`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1447-L1462)] [[`common/errors.go:L1000-1002`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1000-L1002)] ### Best practices - Prefer **quantile mode** (`quantile: 0.7`, `min: 100ms`, `max: 2s`) over static delays — static delays go stale as providers change; quantile self-adjusts per method. - Never set `min: 0` in quantile mode: cold-start hedges would fire immediately, doubling request volume right after deploys. - Budget for hedge cost with `maxCount: 1` first; raise to 2 only when `erpc_network_hedge_winner_total` shows hedges winning often enough to matter. - Alert/dashboard on `erpc_network_hedged_request_total` vs total request rate to watch the hedge tax (each win is also a paid duplicate request). - Don't build alerts on `erpc_network_hedge_delay_seconds` — it is registered but dormant (no production Observe call). - Remember the **two different defaults**: the built-in system template uses `maxCount: 2`; manually-written failsafe blocks get `maxCount: 1` from SetDefaults. - Hedging is upstream-cost-bounded, not free: combine with [rate limiters](/config/rate-limiters.llms.txt) on expensive vendors so hedge bursts can't blow a provider budget. ### Edge cases & gotchas 1. **Static `base` ignores `min`/`max`.** When `quantile==0`, `Resolve` returns `base` unchanged regardless of `min`/`max`. A `delay: 5ms` WILL fire at 5ms even if `min=100ms` is set. Source: [`common/adaptive_duration.go:L88-89`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L88-L89) 2. **Cold start falls to `min`, not `base`.** When `quantile>0` and no latency data exists, `Resolve` returns `Min` (not `Base`). If `min==0`, hedges fire immediately. `SetDefaults` auto-sets `min=100ms` but a manually-zero `min` bypasses this guard. Source: [`common/adaptive_duration.go:L96-98`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L96-L98) 3. **`maxCount: 0` disables hedging silently.** `HasHedge()` returns `false`. A config with only `delay` and no `maxCount` gets `maxCount=1` from `SetDefaults` (enabled). Explicit `maxCount: 0` disables it. Source: [`erpc/network_executor.go:L126-131`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L126-L131) 4. **Null responses do not win for most methods — except a consensus slot under empty-waiver opt-in, and a null receipt on a settled head.** `{"result": null}` from one leg does NOT cancel siblings for `eth_getBlockByNumber`, `eth_getTransactionByHash`, `eth_getTransactionReceipt` (not in `emptyResultAccept`) on the non-consensus / skip-consensus path, and also not for waiver-free consensus+hedge. For `eth_getLogs`, `eth_call`, empty IS kept. Inside `consensus(retry(hedge(tryOneUpstream)))` **only when** the selected policy sets `waiveAgreementOnEmptyOutsideRetention`, empty **is** kept: that slot already selected one upstream, and discarding the null lets the hedge recovery leg vote `n/a` exhausted instead, so tagged internals never appear in `analysis.groups`. Outside a consensus slot, a null `eth_getTransactionReceipt` **is** kept, with no hedge fired, when every routed upstream answered it null (or cannot serve the method) and the request's head is settled until the last hedge would fire, `H = d × maxCount`, `d` the hedge delay resolved once per request: the head block was first seen at least `H` ago; the next block's earliest time, the head's first sight plus `min(blockTime/2, S)` with `S` the shortest block-to-block step of the lane's view over its last 64 blocks, is more than `H` away; the lane's block clock runs (some client read `latest` recently, so the view follows the chain) and its view still stands at the request's head (no block landed during the sweep); and no by-hash answer or cache sighting showed a block above the head (a preconfirmation or an early block). So a chain with 2 s blocks or faster never settles at a 500 ms hedge, and Ethereum (12 s) settles only in the first half of its slot. Fewer than 8 recorded steps, an unknown block time, or a head lowered below the tracker's own → the hedge fires as before. An upstream still in flight in a sibling leg (one slower than `d`), or one that failed transiently (timeout, 429, 5xx), keeps the race: hedge legs share one upstream rotation, so the hedge leg's sweep skips an upstream in flight, and either may hold an old receipt that pruned nodes lack. `eth_getTransactionByHash` gets no exception: a node's mempool can gain the pending tx between blocks. Source: [`erpc/network_executor.go:L719-794`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L719-L794), [`erpc/network_executor.go:L816-836`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L816-L836), [`erpc/network_head.go:L207-223`](https://github.com/erpc/erpc/blob/main/erpc/network_head.go#L207-L223), [`common/request.go:L1751-1779`](https://github.com/erpc/erpc/blob/main/common/request.go#L1751-L1779) 5. **Non-retryable errors win immediately.** An execution-revert from any leg is `keep=true` and cancels siblings. This mirrors upstream-sweep short-circuit behavior. 6. **Hedge fires continue after primary error.** The timer schedule is independent of primary success/failure. A fast-failing primary does not suppress subsequent hedge attempts. Source: [`failsafe/hedge.go:L216`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L216) 7. **Channel overflow protection.** Result channel is sized `maxCount+1`; the `default` branch in the goroutine's send handles the theoretically-impossible overflow by releasing the result. Source: [`failsafe/hedge.go:L127-136`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L127-L136) 8. **Composite requests skip hedging.** Batch/composite requests bypass `runHedge` entirely — batch fan-out has its own parallelism. Source: [`erpc/network_executor.go:L524`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L524) 9. **`ErrUpstreamHedgeCancelled` is retryable.** Cancelled hedge legs produce this error (U:yes N:yes). If a full hedge race fails, outer retry is not blocked because `IsRetryableTowardNetwork` returns `true`. Source: [`common/errors.go:L1447-1462`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1447-L1462) 10. **`erpc_network_hedge_delay_seconds` is dormant.** The metric is registered but has no production `Observe` call — only a test touches it. Do not alert on it. Source: [`telemetry/metrics.go:L813`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L813) 11. **System template vs. manual default.** The built-in project template (applied when `projects` is absent) sets `maxCount=2`. Manually-written `networks[].failsafe[].hedge` blocks get `maxCount=1` from `SetDefaults`. These are different defaults. Source: [`common/defaults.go:L137-141`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L137-L141) 12. **Single upstream + hedge = primary wins eventually.** The hedge leg gets `ErrNoUpstreamsLeftToSelect`, `keep` returns `false`, and the race waits for the primary; no error is surfaced. Source: `erpc/http_server_hedge_test.go` (SingleUpstreamHedgeContinuesPrimary). 13. **Timer pool stale-tick safety.** Hedge timers are drawn from a `sync.Pool` (`hedgeTimerPool`) to avoid per-request `time.NewTimer` allocations. `releaseHedgeTimer` calls `t.Stop()` and drains `t.C` with a non-blocking select before returning to the pool — without this, the next borrower could fire immediately on a stale tick from a previous lifecycle. Source: [`failsafe/hedge.go:L9-60`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L9-L60) 14. **Delay is per-method, not per-attempt-index.** `delayFn` is called with a 1-based hedge index for each fire, but in the network executor the same `AdaptiveDuration.ResolveForRequest(req)` is returned for every index — the delay is determined by observed per-method latency, not by which hedge attempt is firing. The index parameter exists for extensibility. Source: [`erpc/network_executor.go:L542-544`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L542-L544) 15. **Verified empty block traces can win immediately.** At network scope, `debug_traceBlockByNumber` accepts `[]` early only for a numeric block in the existing followed segment with matching header identity, an explicit empty transaction list, and zero gas used. The winning leg cancels siblings without waiting for the hedge delay. The acceptance check makes no auxiliary RPC request. Tags and unknown evidence retain normal retry and hedge behavior, including whitespace arrays. Setting `retry.emptyResultAccept` explicitly replaces the default: an empty list disables trace acceptance, while a list containing `debug_traceBlockByNumber` accepts all empty shapes for that method. If every leg returns an unavailable result, existing terminal behavior can still return that result. Source: [`erpc/network_executor.go:L137-171`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L137-L171) 16. **A hedge leg never re-asks an upstream that gave a permanent missing-data verdict.** An SVM skipped slot (`-32007`/`-32009`) or a history page that ends at the upstream's floor is swept across upstreams once per client request. The hedge leg skips every upstream that already answered so, so the sweep costs one call per upstream. A not-yet-available miss (`-32004`) still leaves the upstream selectable. Source: [`common/request.go:L1728-1742`](https://github.com/erpc/erpc/blob/main/common/request.go#L1728-L1742) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_hedged_request_total` | counter | project, network, upstream, category, attempt, finality, user, agent_name | Each time a hedge request fires (primary counted when `hedges > 0`) | | `erpc_network_hedge_discards_total` | counter | project, network, upstream, category, attempt, hedge, finality, user, agent_name | Hedge goroutine's context was cancelled by a sibling winner | | `erpc_network_hedge_winner_total` | counter | project, network, upstream, category, finality | Each hedge race that produced a kept result; identifies which upstream won | | `erpc_network_hedge_delay_seconds` | histogram | project, network, category, finality | **Dormant** — registered with buckets `[0.01, 0.03, 0.05, 0.2, 0.3, 0.5, 0.7, 1, 3]`, no production `Observe` call (only a test touches it) | | `erpc_upstream_selection_total{reason="hedge"}` | counter | project, network, upstream, category, reason, finality | Upstream selected for a hedge attempt | | `erpc_upstream_attempt_outcome_total{is_hedge="true"}` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | Hedge attempt terminal outcome | ### Source code entry points - [`failsafe/hedge.go:L111-L255`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L111-L255) — `RunHedged[R]`: generic race loop, timer pool, `siblingCtx`, winner selection - [`failsafe/hedge.go:L9-L60`](https://github.com/erpc/erpc/blob/main/failsafe/hedge.go#L9-L60) — `hedgeTimerPool` (`sync.Pool`): timer borrow/release with stale-tick drain - [`erpc/network_executor.go:L516-L645`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L516-L645) — `runHedge`: wires `AdaptiveDuration.ResolveForRequest` as `delayFn`, implements `keep`, `release`, `OnFire` hooks - [`erpc/network_executor.go:L141-L203`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L141-L203) — `Run` / `runRetryHedge`: composition ordering (`retry(hedge(runUpstreamSweep))`) - [`erpc/networks.go:L1284-L1306`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1284-L1306) — `MetricNetworkHedgedRequestTotal` increment + discard detection (`ErrEndpointRequestCanceled` → `recordHedgeDiscard`) - [`erpc/networks.go:L1883-L1903`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1883-L1903) — `recordHedgeDiscard`: increments `MetricNetworkHedgeDiscardsTotal`, returns `ErrUpstreamHedgeCancelled` - [`common/config.go:L1489-L1571`](https://github.com/erpc/erpc/blob/main/common/config.go#L1489-L1571) — `HedgePolicyConfig` struct, YAML/JSON unmarshal, `applyLegacySiblings` - [`common/adaptive_duration.go:L83-L109`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L83-L109) — `AdaptiveDuration.Resolve`: static/quantile/cold-start branches - [`common/defaults.go:L2307-L2340`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2307-L2340) — `HedgePolicyConfig.SetDefaults`; constants `defaultHedgeMinDelay=100ms`, `defaultHedgeMaxDelay=999s` - [`common/errors.go:L1447-L1462`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1447-L1462) — `ErrUpstreamHedgeCancelled` / `ErrCodeUpstreamHedgeCancelled` (error code #33) - [`common/errors.go:L955-L1035`](https://github.com/erpc/erpc/blob/main/common/errors.go#L955-L1035) — `ErrUpstreamsExhausted.SummarizeCauses`; `cancelled` bucket for `ErrCodeUpstreamHedgeCancelled` at L1000-L1002 - [`architecture/evm/util.go:L7-L17`](https://github.com/erpc/erpc/blob/main/architecture/evm/util.go#L7-L17) — `IsNonRetryableWriteMethod` - [`erpc/http_server_hedge_test.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server_hedge_test.go) — behavior-locking tests incl. single-upstream race semantics, retry interaction tests ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — wraps hedge; each retry attempt is a fresh hedge race. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds the whole race from outside. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — decides which upstream each leg gets. - [Rate limiters](/config/rate-limiters.llms.txt) — caps the hedge tax on expensive vendors. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome this feature serves. --- --- # Integrity checks > Source: https://docs.erpc.cloud/config/failsafe/integrity > eRPC silently discards stale or structurally broken upstream responses and retries on another provider — callers always get the correct answer. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Integrity checks Upstream providers occasionally return stale block numbers, null blocks, logs outside their available range, or structurally broken receipts. eRPC catches all of it silently — bad responses are discarded and retried against a different upstream before the caller ever sees them. eRPC has **two independent layers** of integrity, configured separately: 1. **Block-tip & availability enforcement** — always-on, configured under `networks[].directiveDefaults`. Keeps `eth_blockNumber`/`eth_getBlockByNumber` from going backward, pre-screens `eth_getLogs` ranges, and turns null tagged-block responses into retries. 2. **Data-integrity validation** — the `integrity:` module: an **opt-in** catalog of structural and cryptographic checks (schema, bloom, sender recovery, block-hash and root recompute, cross-block continuity, authoritative corroboration). **Off by default** — deploy with no `integrity:` block and nothing runs. ## Quick taste Turn on the intrinsic data-integrity checks (cheap, self-contained, no extra upstream calls): **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } integrity: level: intrinsic # off | intrinsic | corroborated | authoritative ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, integrity: { level: "intrinsic", // off | intrinsic | corroborated | authoritative }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: harden an indexer pipeline against bad upstream data** ```text I'm running an eRPC-fronted indexer that backfills historical blocks. Turn on the data-integrity module at the strongest free tier (level: intrinsic) so structurally broken or cryptographically-inconsistent upstream responses are silently retried rather than written to the database. Keep it scoped to the right networks. Read the full reference first: https://docs.erpc.cloud/config/failsafe/integrity.llms.txt ``` **Prompt Example #2: disable checks that break a non-standard chain** ```text My eRPC setup serves ZKSync Era (chainId 324). The default enforceNonNullTaggedBlocks check causes infinite retries because ZKSync legitimately returns null for some tagged blocks. Disable exactly that check, and make sure the data-integrity module is not enabled for this network (its block-hash/root recompute would reject ZKSync's non-standard encoding). Reference: https://docs.erpc.cloud/config/failsafe/integrity.llms.txt ``` **Prompt Example #3: strongest guarantees on a high-value network** ```text I want the strongest data-integrity guarantees on my mainnet network, including force-fetching the canonical block to corroborate single receipts. Set integrity level to authoritative with a sensible budget, and explain the per-finality invalidBehavior (hardReject on finalized, recordOnly on unfinalized) and autoCorrectWhenPossible. Reference: https://docs.erpc.cloud/config/failsafe/integrity.llms.txt ``` **Prompt Example #4: let callers pick an integrity profile per-request** ```text I want to define a couple of named integrity profiles (e.g. "strict", "lenient") and let specific callers select one per request via the X-ERPC-Integrity header, without letting them set arbitrary levels. Show me the profiles + headerMode config. Reference: https://docs.erpc.cloud/config/failsafe/integrity.llms.txt ``` --- ### Integrity checks — full agent reference ### How it works eRPC's integrity is two separate planes — keep them distinct when configuring: - **Block-tip & availability enforcement** lives on `RequestDirectives` (populated from `directiveDefaults` + `X-ERPC-Enforce-*` headers) and runs in method-specific hooks. It is **on by default**. - **Data-integrity validation** is the `integrity:` config block (project + network). It compiles to a set of checks the EVM post-forward hook runs through a single engine. It is **opt-in** — with no config, the engine runs nothing. Both surfaces produce the same failure mode: `ErrEndpointContentValidation` — retryable at network scope (try another upstream), not retryable at the same upstream, feeding the `validation` exhaustion bucket. On the wire, HTTP 200 with a JSON-RPC error body (`code: -32603`). [`common/errors.go:L2719-2747`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2719-L2747) --- ## Layer 1 — Block-tip & availability enforcement Configured under `networks[].directiveDefaults`. On by default; toggle per-request via `X-ERPC-Enforce-*` headers / `?enforce-*=` query params. **Highest-block enforcement — `eth_blockNumber`.** Reads `dirs.EnforceHighestBlock`. While the network's served head is known, eRPC answers `eth_blockNumber` from it without dispatching. Otherwise the request is forwarded, and every response — including cache hits — is pinned exactly to the served head once it is known: a higher value is lowered, a lower one raised, with no re-request. The head is resolved request-aware: a `use-upstream` selector scopes it to the targeted subset. See [Block tracking](/reference/evm/block-tracking.llms.txt). [`architecture/evm/eth_blockNumber.go:L13-171`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go#L13-L171) **`eth_getBlockByNumber[latest/finalized]`.** The tag is interpolated to the request's `Latest`/`Finalized`, like every method's, before the cache and every attempt; each such request takes its head after the voters' refresh, as `eth_blockNumber` does: waited for, at most W, when the head is older than W, else in the background. No answer is re-requested. A `null` for an interpolated tag follows `enforceNonNullTaggedBlocks`, which reads the tag the client sent. [`architecture/evm/eth_getBlockByNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go) **Stale-tip cache write guard.** Under `enforceHighestBlock`, a realtime-finality response already behind the network-wide tip is never written to cache (the classic symptom it prevents: `eth_blockNumber` sawtoothing backwards on `x-erpc-cache: HIT` while one upstream lags). Fails open when pollers don't yet know a tip. [`architecture/evm/json_rpc_cache.go:L1075-1098`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1075-L1098) **Block-range availability.** Before forwarding `eth_getLogs`/`trace_filter`/`arbtrace_filter` to an upstream, `CheckBlockRangeAvailability` verifies `fromBlock`/`toBlock` are within the upstream's range; otherwise `ErrUpstreamBlockUnavailable` (retryable) routes to a different upstream. [`architecture/evm/block_range.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_range.go) **Future-block empty-result guard.** `emptyResultBeyondConfidence` returns an empty result truthfully (rather than retrying) when the block is beyond the confidence head (latest or finalized, per `emptyResultConfidence`) — preventing retry storms on not-yet-produced blocks. Fail-open on unknown head or block tags. [`architecture/evm/common.go:L55-89`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L55-L89) ### Layer 1 config schema — `networks[].directiveDefaults` | Field | Type | Default | Behavior | |---|---|---|---| | `enforceHighestBlock` | `*bool` | `true` | Highest-block enforcement for `eth_blockNumber`: answered from the served head; every response pinned to it, incl. cache hits. `eth_getBlockByNumber[latest/finalized]` needs no enforcement: its tag is interpolated to the request's Head. Gates the stale-tip cache write guard. Header: `X-ERPC-Enforce-Highest-Block`. [`common/defaults.go:L1458-1460`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1458-L1460) | | `enforceGetLogsBlockRange` | `*bool` | `true` | Pre-screens `eth_getLogs`/`trace_filter` ranges against upstream availability. The actual hooks read `evm.integrity.enforceGetLogsBlockRange` directly. Header: `X-ERPC-Enforce-GetLogs-Range`. [`common/defaults.go:L1461-1463`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1461-L1463) | | `enforceNonNullTaggedBlocks` | `*bool` | `true` | Converts null tagged `eth_getBlockByNumber` responses into `ErrEndpointMissingData`. Disable for chains that legitimately return null for some tags (e.g. ZKSync Era). Header: `X-ERPC-Enforce-Non-Null-Tagged-Blocks`. [`common/defaults.go:L1464-1466`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1464-L1466) | `networks[].evm.emptyResultConfidence` (`AvailabilityConfidence`, default `"blockHead"`): `"blockHead"` retries empty results for blocks at/below the latest tip; `"finalizedBlock"` retries only at/below the finalized tip — use for archive workloads that legitimately return empty for unfinalized blocks. [`common/defaults.go:L2078`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2078) The deprecated `networks[].evm.integrity` (`EvmIntegrityConfig`: `enforceHighestBlock`/`enforceGetLogsBlockRange`/`enforceNonNullTaggedBlocks`) is auto-migrated into `directiveDefaults` during `SetDefaults` (explicit old values win; no warning). [`common/defaults.go:L1952-1964`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1952-L1964) --- ## Layer 2 — Data-integrity validation (the `integrity:` module) **Opt-in and off by default.** With no `integrity:` block, the engine runs **zero** checks — safe to deploy this version and enable nothing. The block lives at the project level (applies to all networks) and the network level (overrides); the network block is merged over the project block at startup. ### The front door: `level` One knob picks a preset over the check catalog. Each level is a superset of the previous: | Level | What runs | Upstream cost | |---|---|---| | `off` | nothing | none | | `intrinsic` | self-consistency + cryptographic recompute on the single response | none | | `corroborated` | the above + cross-block continuity vs already-observed blocks, and the logs gate | none (passive memory), except the logs gate's ask of one other upstream | | `authoritative` | the above + force-fetch the canonical block to corroborate | bounded, budgeted | **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: authoritative # off | intrinsic | corroborated | authoritative # Whether a violation hunts for a validated replacement (retry other # upstreams) BEFORE the invalidBehavior verdict applies. Default true. autoCorrectWhenPossible: true # Per-finality verdict for the reorg-sensitive checks only — what happens # when no valid answer is obtainable. At the tip you can't tell a node bug # from a reorg, so unfinalized mismatches are recorded, not rejected. invalidBehavior: finalized: hardReject # recordOnly | hardReject | off unfinalized: recordOnly # Override individual checks by id (enable / disable / params / onFailure). checks: receiptVsBlock: { enabled: false } # drop one authoritative check bloomMatch: { onFailure: recordOnly } # record instead of reject txHashUniqueness: { params: { strict: "true" } } # the one check with a param # Cost cap on the canonical force-fetches the authoritative tier issues. budget: maxPerSecond: 50 maxConcurrent: 8 ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "authoritative", autoCorrectWhenPossible: true, invalidBehavior: { finalized: "hardReject", unfinalized: "recordOnly" }, checks: { receiptVsBlock: { enabled: false }, bloomMatch: { onFailure: "recordOnly" }, txHashUniqueness: { params: { strict: "true" } }, }, budget: { maxPerSecond: 50, maxConcurrent: 8 }, } ``` ### The check catalog Every check is an independently-toggleable unit, grouped by family. A check only runs for the methods it applies to (e.g. receipt checks on `eth_getBlockReceipts`/`eth_getTransactionReceipt`, block checks on `eth_getBlockByNumber`/`eth_getBlockByHash`). All cryptographic recomputes are **chain-safe**: the known-field set is derived from the reference encoder (go-ethereum), so a chain with custom header/receipt fields, a system/deposit tx, or a hashes-only response is **skipped, never false-flagged**. Methods column: **block** = `eth_getBlockByNumber`/`eth_getBlockByHash`; **receipts** = `eth_getBlockReceipts`; **receipt** = `eth_getTransactionReceipt`; **logs** = `eth_getLogs`; **txByHash** = `eth_getTransactionByHash`. | Check id | Level | Methods | What it catches | |---|---|---|---| | `schemaConformance` | intrinsic | block, receipts | a result that doesn't decode to the expected shape | | `indexMagnitude` | intrinsic | receipt, receipts, logs | `logIndex`/`transactionIndex` int32-underflow (the Amoy incident) | | `headerFieldShapes` | intrinsic | block | header hash fields ≠ 32 bytes, `logsBloom` ≠ 256 bytes | | `logFieldShapes` | intrinsic | receipts, receipt, logs | log address ≠ 20 bytes, topic count > 4, topic ≠ 32 bytes | | `bloomEmptiness` | intrinsic | receipts | logs present but zero bloom (or non-zero bloom with no logs) | | `sameBlockHash` | intrinsic | receipts | receipts that don't all share one `blockHash` | | `txHashUniqueness` | intrinsic | receipts | duplicate `transactionHash` (param `strict: "true"` also rejects empty) | | `transactionIndexConsistency` | intrinsic | receipts | `transactionIndex` ≠ array position | | `logMetadata` | intrinsic | receipts | a log's block/tx fields ≠ its parent receipt | | `logIndexContiguity` | intrinsic | receipts | global `logIndex` not `0,1,2,…N` across all receipts | | `transactionsRootConsistency` | intrinsic | block | `transactionsRoot` ↔ tx-count (phantom-tx-aware) | | `txFieldUniqueness` | intrinsic | block | duplicate / non-32-byte tx hashes (hydrated blocks) | | `txBlockInfo` | intrinsic | block | `tx.blockHash`/`blockNumber`/`transactionIndex` ≠ header | | `bloomMatch` | intrinsic | receipts | `logsBloom` ≠ bloom recomputed from the logs | | `blockHashRecompute` | intrinsic | block | the hash the chain's header format derives from the header ≠ the claimed block hash; skipped when that format cannot encode the header (keys dropped or unknown) | | `transactionsRootRecompute` | intrinsic | block | the transactions' Merkle-Patricia root ≠ header `transactionsRoot` | | `senderRecovery` | intrinsic | txByHash | `ecrecover(signature)` ≠ the reported `from` | | `blockByHashIdentity` | intrinsic | `eth_getBlockByHash` | the returned block isn't the one whose hash was requested | | `blockByNumberIdentity` | intrinsic | `eth_getBlockByNumber` | an explicit height was requested and a different one came back (tags skip) | | `txByHashIdentity` | intrinsic | txByHash | the returned transaction isn't the one whose hash was requested | | `receiptIdentity` | intrinsic | receipt | the returned receipt isn't for the requested transaction | | `getLogsFilterSanity` | intrinsic | `eth_getLogs` | a returned log doesn't match the request's own filter/range | | `getLogsCompleteness` ※ | corroborated | `eth_getLogs` | logs missing/extra/altered vs the cached canonical receipts for that block | | `getLogsEmptyGate` | corroborated | `eth_getLogs` | an empty answer for blocks near the head that the held headers don't prove empty is served only once one other upstream that holds the block agrees, or that upstream's logs are served (the logs gate). Off, the answer is served as it came and the gate sends nothing: no probe, no header lookup, no bloom-trust receipts | | `txPinConsistency` ※ | corroborated | txByHash | a mined tx's claimed block coordinates ≠ the committed pin | | `parentHashLinkage` ※ | corroborated | `eth_getBlockByNumber` | block N's `parentHash` ≠ the hash observed for N-1 | | `hashStability` ※ | corroborated | `eth_getBlockByNumber` | a block number's hash changed from what was observed | | `receiptVsBlock` ※ | authoritative | receipt | a single receipt ≠ the force-fetched canonical block | | `receiptsRootRecompute` | authoritative | receipts | receipt MPT root ≠ the header's `receiptsRoot` (force-fetched by hash) | ※ = **reorg-sensitive** (governed by `invalidBehavior`). All others are deterministic and always reject on violation. Note the division of labour on `eth_getBlockByHash`: `blockByHashIdentity` enforces that you got **the block you asked for**, while the continuity pair (which judges *canonicality*, a question a by-hash lookup never asked) deliberately does not run there — see [Edge cases](#edge-cases--gotchas) #7. Both stateful tiers read the network's **chain tracker** — the canonical `number→hash` pins plus held headers (window [`evm.chainTracker.reorgWindow`](/config/projects/networks.llms.txt), default 32). Only upstream hash votes move the pins; blocks your own traffic pulled are held for the checks but never vote. `authoritative` additionally force-fetches a missing anchor **once** through the normal network path (cache-backed, recursion-guarded), capped by `budget`, and needs the evidence quorum for it. When the voters move to another branch, the pins follow it, so block and receipts can't disagree. ### Per-finality verdict: `invalidBehavior` Most checks are **deterministic** — a violation is corruption regardless of finality, so they always reject. A handful are **reorg-sensitive** (`parentHashLinkage`, `hashStability`, `receiptVsBlock`): they compare against another observation, and near the tip a disagreement may be a benign reorg rather than a bug. `invalidBehavior` decides what to do for those, by the block's finality (read from the upstream state poller): - `finalized` → default `hardReject` (a finalized block can't reorg; a mismatch is corruption). - `unfinalized` → default `recordOnly` (record a metric/log, still serve — it may be a reorg). `off` skips the check (and any force-fetch) on the hot tip entirely. The verdict is only half the policy. **`autoCorrectWhenPossible`** (default `true`) decides whether a violation first hunts for a **validated replacement** — the rejection routes the request to another upstream, whose response runs the same checks. The two knobs compose: | `autoCorrectWhenPossible` | verdict | on violation | |---|---|---| | `true` | `recordOnly` | seek a replacement; serve it if one validates; **exhausted → serve the flagged original** (never a client error; counted in `erpc_integrity_fallback_served_total`) | | `true` | `hardReject` | seek a replacement; exhausted → error (correct-or-die) | | `false` | `recordOnly` | serve the original immediately + record; no correction attempted | | `false` | `hardReject` | fail immediately; no alternates tried | The vocabulary is exactly `recordOnly | hardReject | off` — anything else (including the pre-release `reject`/`soft-flag` words) fails config validation loudly rather than aliasing silently. ### Rolling out safely: `observeOnly` `observeOnly: true` runs every enabled check and reports everything, but **no verdict may touch the response** — a violation that would have been rejected is served anyway and recorded with the outcome `would_reject`. This is the way to turn integrity on for a network the first time: it surfaces bad upstream data *and* the module's own gaps on that chain at zero request risk, and ``` sum(rate(erpc_integrity_check_total{outcome="would_reject"}[5m])) by (network, check, upstream) ``` is precisely the client-facing cost enforcement would incur — read it before promoting. Interpreting what you see, by how the `would_reject`s are spread: | spread across the chain's upstreams | meaning | | --- | --- | | one upstream | that node is serving bad data — enforcement would correct it via failover | | **all** upstreams | a **module gap for this chain** (a protocol quirk the check does not model). Enforcing would defeat failover and fail requests. Disable that check for the chain (or add a `chainProfile`) — never enforce through it | `observeOnly` is **absolute** and deliberately outranks everything else: a per-check `onFailure: reject`, `invalidBehavior`, and any check a *future release* adds all cannot reject while it is set. That last property is the point — `invalidBehavior: soft-flag` cannot give you this, because the ~25 deterministic checks ignore `invalidBehavior` by design and always reject. It is inherited like the rest of the block, which gives the natural rollout shape — a project-wide safety net, promoted one chain at a time: ```yaml projects: - id: main integrity: level: authoritative observeOnly: true # every network observes by default networks: - architecture: evm evm: { chainId: 8453 } integrity: observeOnly: false # base graduates to enforcement ``` `off` still means off: `observeOnly` never resurrects a check you disabled, nor its force-fetches. ### Why continuity is by-number only Continuity answers "**what is the chain at height N**", so it runs on `eth_getBlockByNumber` and not on `eth_getBlockByHash`. A by-hash lookup asks for one named block: its *canonicality* was never the question — retrieving orphaned-but-real blocks by hash is exactly how indexers unwind a reorg. Rejecting there would discard data the caller explicitly asked for, and because an orphan hash does not exist on the canonical fork, no failover can produce an alternative: the request simply fails. What a by-hash lookup *does* require is **identity** — that you got the block you named — and that is enforced by its own check, `blockByHashIdentity` (intrinsic, deterministic). Do not rely on `blockHashRecompute` for this: it proves the returned header hashes to the hash it claims, i.e. that the block is real and self-consistent, but a node answering with an entirely different valid block satisfies it. Identity is what closes that gap. Symmetrically, a by-hash response **never moves the number→hash pin** (it only populates the content-addressed header cache). If it did, one client fetching an orphan would adopt that orphan as canonical at its height and roll back the real fork's descendants, turning a private reorg-unwind into mass rejections of everyone else's by-number traffic. All deterministic checks (hash recompute, roots, field shapes, identity) still apply to by-hash responses. ### Per-request selection: profiles & headers An operator can define named profiles and let callers pick one per request, gated by `headerMode`: - `off` (default) — the `X-ERPC-Integrity` header / `?integrity=` query param is ignored. - `profiles` — a request may only select a named profile by word. - `full` — a request may also set a bare level word (`intrinsic`/`authoritative`/…). **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic headerMode: profiles profiles: strict: { level: authoritative } lenient: { level: off } ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic", headerMode: "profiles", profiles: { strict: { level: "authoritative" }, lenient: { level: "off" }, }, } ``` ``` X-ERPC-Integrity: strict # selects the "strict" profile (headerMode: profiles|full) ``` ### Backward compatibility The deprecated per-check `directiveDefaults` validation flags (`validateLogsBloomMatch`, `enforceLogIndexStrictIncrements`, `validateTransactionsRoot`, `validateHeaderFieldLengths`, `validateTransactionFields`, `validateTransactionBlockInfo`, `validateTxHashUniqueness`, `validateTransactionIndex`, `validateLogFields`, `validateLogsBloomEmptiness`) are **translated into `integrity.checks` at config-load time** — an explicit `integrity:` block wins per check. This is the only place the old flags are read; there is no legacy path at runtime. [`common/defaults.go:L2031-2075`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2031-L2075) The removed per-request `X-ERPC-Validate-*` headers, the `validateReceiptTransactionMatch` / `receiptsCount*` / `validationExpectedBlock*` directives, the `GroundTruth*` library fields, and the non-functional `upstreams[].integrity` block no longer exist — use the `integrity:` config (and `X-ERPC-Integrity` for per-request selection) instead. ### Layer 2 config schema — `integrity` | Field | Type | Default | Notes | |---|---|---|---| | `level` | enum | unset → `off` | `off`/`intrinsic`/`corroborated`/`authoritative`. The one field most users set. [`architecture/evm/integrity/levels.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/integrity/levels.go) | | `checks.` | object | per-level | Override a check by its catalog id: `{ enabled, params, onFailure }`. `enabled:false` removes it; `enabled:true` adds it above the level. [`common/config_integrity.go`](https://github.com/erpc/erpc/blob/main/common/config_integrity.go) | | `invalidBehavior.finalized` | enum | `reject` | `reject`/`soft-flag`/`off` for reorg-sensitive checks on finalized data. | | `invalidBehavior.unfinalized` | enum | `soft-flag` | …on unfinalized data. `off` skips the check (and its force-fetch). | | `observeOnly` | bool | `false` | Run every check but never reject: suppressed rejections are served and reported as `would_reject`. **Absolute** — outranks `checks..onFailure`, `invalidBehavior`, and any check added by a later release. The safe way to enable a new network; see [Rolling out safely](#rolling-out-safely-observeonly). [`architecture/evm/integrity/engine.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/integrity/engine.go) | | `budget.maxPerSecond` | int | conservative | Token-bucket cap on the authoritative tier's canonical fetches. | | `budget.maxConcurrent` | int | small | Concurrency cap on in-flight fetches. | | `follow.enabled` | bool | `false` | Opens one integrity follow tap per chain tracker at the network's first client request, and keeps it open. It reads the confirmed head like a ws subscription, so source polls run while clients are quiet, and it drives `stateProbe` on each new head. An idle network, with no client request yet, sends no follow polls and no probes. Out of range restarts it after the confirmed head. The window it follows is [`evm.chainTracker`](/config/projects/networks.llms.txt). | | `follow.interval` | Duration | `1s` | The pace the follow tap needs heads at. While it is a network's only newHeads demand (no client subscription), the tracker asks upstreams for a newer head, and catches lagging upstreams up, no more often than this; a client tap needs every block and lifts the limit. | | `stateProbe.enabled` | bool | `false` | Probes upstreams' state from the network's first client request: each upstream that gets tag requests at `latest` (the tag-state gate's evidence, which skips an upstream whose `latest` state is stale), and, with `follow.enabled`, every upstream's state trie on each followed block. Off, no probe runs and the tag-state gate skips nothing. | | `stateProbe.interval` | Duration | `2s` | Minimum time between probes of one upstream. | | `headerMode` | enum | `off` | `off`/`profiles`/`full` — whether/how `X-ERPC-Integrity` may adjust integrity per request. | | `profiles.` | object | — | Named settings (`level`/`checks`/`invalidBehavior`/`budget`) a request may select by name. | ### Worked examples — real-world scenarios **1. Free structural hardening for an indexer (the common starting point).** Catch malformed / cryptographically-inconsistent data with zero extra upstream calls — bad responses fail over to another upstream before they reach your database: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic" } ``` **2. One default for the whole project, stronger on a high-value network.** A project-wide block applies to every network; a network block overrides it field-by-field: **Config path:** `projects[]` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic # project-wide default networks: - evm: { chainId: 1 } integrity: level: authoritative # mainnet gets force-fetch corroboration ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic" }, networks: [{ evm: { chainId: 1 }, integrity: { level: "authoritative" } }] ``` **3. Strongest guarantees, cost-bounded.** `authoritative` force-fetches the canonical block to corroborate single receipts and recompute the receipts root. Cap the fetch rate, and skip corroboration on the volatile tip (where a mismatch is usually a reorg, not corruption): **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: authoritative invalidBehavior: finalized: reject unfinalized: off # don't force-fetch / corroborate the hot tip budget: maxPerSecond: 50 maxConcurrent: 8 ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "authoritative", invalidBehavior: { finalized: "reject", unfinalized: "off" }, budget: { maxPerSecond: 50, maxConcurrent: 8 }, } ``` **4. Cross-block / cache correctness.** `corroborated` adds parent-hash linkage and hash-stability over blocks you've already seen — catching a node serving a block that doesn't link to the chain you were served before. No force-fetch; only the logs gate asks one other upstream before it serves an empty `eth_getLogs` near the head that the headers don't prove empty: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: corroborated ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "corroborated" } ``` **5. Only the logs gate.** Keep every other check off and still confirm empty `eth_getLogs` answers near the head: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: checks: getLogsEmptyGate: enabled: true ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { checks: { getLogsEmptyGate: { enabled: true } } } ``` **6. Safe rollout — observe before you enforce.** Set everything to `soft-flag` first: violations are recorded (a `WARN` log + the `validation` metrics bucket) but the response is still served, so you can measure your upstreams' data quality without failing traffic. Once it's quiet, flip `finalized` back to `reject`: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic invalidBehavior: finalized: soft-flag # record, don't reject — flip to 'reject' after rollout unfinalized: soft-flag ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic", invalidBehavior: { finalized: "soft-flag", unfinalized: "soft-flag" }, } ``` `invalidBehavior` only governs the reorg-sensitive checks (the ※ rows). To soft-flag a *deterministic* check during rollout, give it `onFailure: soft-flag` — e.g. `checks: { bloomMatch: { onFailure: soft-flag } }`. **7. Non-standard chain — leave it off.** ZK-rollups and chains with custom encodings: the recompute checks already skip what they can't model, but the simplest answer is to not enable the module for that network (it's off by default — this is only needed if you turned it on project-wide): **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml networks: - evm: { chainId: 324 } # zkSync Era integrity: level: off ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ evm: { chainId: 324 }, integrity: { level: "off" } }] ``` **8. Per-tenant strictness via profiles + header.** Define named presets and let callers pick one per request (without letting them set arbitrary levels): **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic # the default for callers who send no header headerMode: profiles # off | profiles | full profiles: strict: { level: authoritative } relaxed: { level: off } ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic", headerMode: "profiles", profiles: { strict: { level: "authoritative" }, relaxed: { level: "off" } }, } ``` ``` X-ERPC-Integrity: strict # or ?integrity=strict ``` **9. Add or drop a single check around a level.** Levels are presets — fine-tune with `checks`: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml integrity: level: intrinsic checks: receiptVsBlock: { enabled: true } # pull one authoritative check up to intrinsic bloomMatch: { enabled: false } # …and drop one you don't want ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { level: "intrinsic", checks: { receiptVsBlock: { enabled: true }, bloomMatch: { enabled: false } }, } ``` Enabling an authoritative check (like `receiptVsBlock`) at a lower level turns on its force-fetch — set a `budget` too. **10. Migrating from the old `validate*` flags.** If your config still sets the deprecated `directiveDefaults.validateLogsBloomMatch: true` (etc.), they're translated into `integrity.checks` automatically at startup — nothing breaks. To make it explicit (recommended), move them into an `integrity` block: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml # old (still works, auto-translated at startup): # directiveDefaults: { validateLogsBloomMatch: true, enforceLogIndexStrictIncrements: true } # new (explicit): integrity: checks: bloomMatch: { enabled: true } logIndexContiguity: { enabled: true } ``` **TypeScript — `erpc.ts`:** ```typescript integrity: { checks: { bloomMatch: { enabled: true }, logIndexContiguity: { enabled: true } }, } ``` ### Request/response behavior - Violations produce `ErrEndpointContentValidation` — HTTP 200 with JSON-RPC error body `{"code": -32603}`. Retryable at network scope (try another upstream), not at the same upstream. [`common/errors.go:L2719-2747`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2719-L2747) - Because content-validation errors are excluded from consensus's `preferLargerResponses` logic, a corrupt-but-larger response can no longer dispute an honest agreeing majority. [`consensus/rules.go`](https://github.com/erpc/erpc/blob/main/consensus/rules.go) - A `soft-flag` verdict serves the response and emits a recorded-mismatch log; only `reject` fails the response over to another upstream. ### Best practices - **Start at `level: intrinsic`.** It's free (no extra upstream calls) and catches malformed/self-inconsistent data plus the cryptographic recompute checks. Most teams never need more. - **Roll out with `soft-flag`, then flip to `reject`.** Run `invalidBehavior: { finalized: soft-flag, unfinalized: soft-flag }` (and `onFailure: soft-flag` on any deterministic checks you're unsure about) first, watch the metrics for a few days, then enforce. This avoids failing real traffic on day one if an upstream has a quirk you didn't anticipate. - **Use `authoritative` only where data quality warrants it**, and always set a `budget` — it force-fetches the canonical block (one fetch per *cold* block, cache-amortized). Pair it with `invalidBehavior.unfinalized: off` to skip the force-fetch on the hot tip. - **Leave `invalidBehavior.unfinalized` at `soft-flag` (or `off`)** — rejecting unfinalized mismatches would reject benign reorgs. Only finalized data is safe to hard-reject on a cross-observation mismatch. - **It needs ≥2 upstreams to be useful.** A `reject` is a *failover* signal (`ErrEndpointContentValidation` is retryable toward the network) — with a single upstream it just surfaces an error. Pair integrity with a [retry](/config/failsafe/retry.llms.txt) policy. - **It's defense-in-depth with [consensus](/config/failsafe/consensus.llms.txt).** Consensus catches a *minority* bad upstream; integrity catches the case consensus can't see — when *every* serving upstream returns the same wrong value (shared client/indexer bug). High-value paths use both. - **Skip the module on non-standard chains** (ZK-rollups with custom encodings). The recompute checks are chain-safe (they skip what they can't model), but if a chain's normal data looks "custom", just leave `integrity` off for it and keep Layer-1 enforcement. - **Profiles, not free-form, for untrusted callers** — `headerMode: profiles` lets callers pick a named preset without setting arbitrary levels; `headerMode: off` (default) ignores the header entirely. - **Watch the rollout, then the steady state.** A persistent stream of recorded-mismatch `WARN` logs / `validation`-bucket metrics for one upstream means that provider's data quality is poor — down-weight or remove it. ### Edge cases & gotchas 1. **Opt-in means opt-in.** No `integrity:` block ⇒ zero data-integrity checks (Layer 1 enforcement still runs). Deploying this version changes nothing until you add the block. 2. **Recompute checks skip rather than false-flag** — *almost always*. A header/receipt with a field the reference encoder doesn't know, a system/deposit tx, or a hashes-only block response is skipped, never rejected. The one case the skip-guard can't catch is #6. 3. **Continuity never fetches.** `parentHashLinkage`/`hashStability` only compare against blocks already observed (bounded per-network `number→hash` store); an unseen parent skips the check. 4. **Tracker fetches run the checks; validation never recurses.** The chain tracker's header, receipts and logs fetches run the integrity checks like client requests, but a check on a tracker fetch reads only held data and skips when it needs more. `authoritative` force-fetches are budgeted; on budget exhaustion the corroboration check no-ops. No failsafe policy covers tracker fetches: they follow the tracker's own fetch schedule, and settles replace the quorum. `matchRequestKind: internal` is refused at load. 5. **Project⊕network precedence.** A project-wide `integrity:` applies to all networks; a network block overrides field-by-field (profiles unioned). - **Suspension.** A check no upstream passes is wrong for the network, not for one vendor, so eRPC suspends it instead of failing every request. Header checks suspend when no header at 2 heights in a row passes within 60s, from upstreams that meet the evidence quorum; they return observe-only after 100 blocks and enforce again after 2 passing heights. The bloom check suspends after 8 mismatched blocks in a row and re-arms after 8 matching ones. Each suspension counts in `erpc_integrity_check_suspended_total{check}`. On a network with one vendor, that vendor alone can suspend a check. - **Evidence quorum.** Content counts as corroborated when 2 distinct vendors agree, or 1 on a network with one vendor. Finalized anchors, suspension, the `eth_getLogs` fallback for `logs` subscriptions, and the tracker's pin freshness read this one rule. - **Kaia root compatibility.** Kaia mainnet (`8217`) and Kairos (`1001`) exclude `transactionsRootRecompute` and `receiptsRootRecompute` through their architecture profile. Kaia uses native serialization and governance-selected root derivation, so matching Ethereum transaction hashes does not prove Ethereum trie compatibility. Identity, structural, and follower checks remain enabled. These exclusions provide no native root verification; explicit per-check overrides still win. 6. **Some chains need recompute checks disabled — proven: HyperEVM (chainId 999).** A chain whose `eth_getBlock` keeps *system transactions* in the header's `transactionsRoot` but omits them from the returned `transactions` list will **systematically** fail `transactionsRootRecompute` (and, by the same mechanism, `receiptsRootRecompute`) — even though every returned tx is valid. The skip-guard in #2 can't catch it: each individual tx hash verifies, only the Merkle root differs. This is a chain representation quirk, **not corruption**. Disable the affected check(s) on that network — the level preset stays, the one check is turned off: ```yaml networks: - evm: chainId: 999 # HyperEVM integrity: level: authoritative checks: transactionsRootRecompute: { enabled: false } # confirmed in production receiptsRootRecompute: { enabled: false } # same mechanism — disable if you run authoritative receipt corroboration ``` **Diagnostic rule of thumb:** if `erpc_integrity_violation_total{check="…Recompute"}` rejects across *every* upstream of one chain, it's the check, not the data — disable that check for that chain (and consider opening an issue so it can be added to this list). 7. **Continuity does not run on `eth_getBlockByHash`** (see [Why continuity is by-number only](#why-continuity-is-by-number-only)) — and a by-hash response never moves the pin. Earlier builds checked by-hash lookups too, which produced a large stream of rejects (mostly ending as `integrity_failed` client errors) whenever one upstream kept serving settled orphaned blocks to clients unwinding reorgs: the pin correctly said "not canonical", but since the request named the orphan hash, no upstream could satisfy the pinned fork. ### Source code entry points - [`architecture/evm/integrity/`](https://github.com/erpc/erpc/blob/main/architecture/evm/integrity) — the check engine, catalog, levels, decode, resolver, history. - [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go) — `HandleUpstreamPostForward` runs the engine (opt-in via `resolveIntegrity`). - [`architecture/evm/integrity_config.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/integrity_config.go) — compiles `integrity` config → check set + reorg policy. - [`common/config_integrity.go`](https://github.com/erpc/erpc/blob/main/common/config_integrity.go) — the `IntegrityConfig` schema + merge. - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) — `migrateLegacyIntegrityChecks`: deprecated flag → `integrity.checks` translation. - [`architecture/evm/eth_blockNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go) / [`eth_getBlockByNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go) / [`block_range.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_range.go) — Layer-1 block-tip & availability enforcement. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_integrity_violation_total` | counter | project, vendor, network, upstream, category, **check**, **verdict** | A data-integrity check (Layer 2) failed. The `check` label is the rule id and `verdict` is `reject` (response failed over to another upstream) or `soft_flag` (recorded but served). This is how you see *which rule* is failing for which method/network/upstream. Only fires on a violation. | | `erpc_integrity_check_total` | counter | …, **check**, **outcome** | Every check evaluation by `outcome` (`pass`/`reject`/`soft_flag`/`off`). Sum across outcomes = total attempts (the rate denominator). | | `erpc_integrity_aux_request_total` | counter | …, **kind**, **outcome** | Aux requests the module issues that are *not* part of the user request: `kind` = `canonical_header`/`canonical_receipts` (force-fetches), and the logs gate's `logs_probe` (an `eth_getLogs` ask of another holder, or the re-ask), `logs_hash` (its header lookup of a `blockHash`) and `bloom_trust` (receipts fetched to earn or keep bloom trust). A network with integrity off counts none. | | `erpc_integrity_check_suspended_total` | counter | project, network, check | A check was suspended for the network (see Suspension above). | | `erpc_integrity_saved_total` | counter | project, network, category | Requests the module **saved**: a check rejected a bad response and a retry returned a good one — a wrong/invalid response prevented. | | `erpc_integrity_failed_total` | counter | project, network, category, **check** | Requests that **failed** toward the user due to integrity (a check rejected and no good response was found). The `check` is the why. | | `erpc_integrity_overhead_seconds` | histogram | project, network, category | Per-request latency the module added — time waited on data-checks + aux force-fetches. Same config-driven buckets as `network_request_duration_seconds`. | | `erpc_upstream_stale_latest_block_total` | counter | project, vendor, network, upstream, category | Upstream returned a block below the network-known latest head (Layer-1 highest-block enforcement). | | `erpc_upstream_stale_upper_bound_total` / `_lower_bound_total` | counter | …, confidence | Request skipped: upstream's range doesn't cover the requested `toBlock`/`fromBlock`. | | `erpc_upstream_attempt_outcome_total` | counter | …, outcome | `outcome=block_unavailable` on range failure; `missing_data` on null responses. | | `erpc_network_retry_attempt_total` | counter | …, reason | `reason=block_unavailable` / `missing_data` on the corresponding retries. | Data-integrity violations are counted by `erpc_integrity_violation_total` (labeled by the individual `check` id and `verdict`) and also surface as `ErrEndpointContentValidation` feeding the `validation` bucket of `ErrUpstreamsExhausted`; a `soft-flag` verdict additionally emits a recorded-mismatch `WARN` log rather than failing the response. The bundled Grafana dashboard ([`monitoring/grafana/dashboards/erpc.json`](https://github.com/erpc/erpc/blob/main/monitoring/grafana/dashboards/erpc.json)) ships a collapsed **Data Integrity** row that breaks these violations down by check, verdict, network, upstream, vendor and method, with a drill-down table. **Tracing.** When tracing is enabled, each validation emits an `Integrity.Validate` span — its duration is the integrity overhead and the aux force-fetches nest under it. Attributes (simple mode): `integrity.method`, `integrity.upstream`, `integrity.outcome` (`pass`/`reject`/`soft_flag`), `integrity.checks`, `integrity.rejected_check`. In **detailed tracing mode** the span additionally records, verbatim and **without redaction**, the actual-vs-expected values of every violation (as `integrity.reject` / `integrity.soft_flag` events), each check's outcome, and — for caught requests — the **response bodies** (capped at 128 KB). That makes a caught request checkable by hand: the rejected attempt's `Integrity.Validate` span carries the *original* body (`integrity.response`) and the request-level `Project.Forward` span carries the *corrected* served body (`integrity.served_response`), so you can confirm the catch was real and the correction right. Bodies are recorded only on a violation (original) or a saved request (corrected) and only under the detailed-tracing gate, so it's zero-cost when tracing is off. Sample a few requests in detailed mode to audit a specific upstream. ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — integrity violations are retryable; retry routes them to a fresh upstream. - [Consensus](/config/failsafe/consensus.llms.txt) — content-validation errors are excluded from agreement/preferLargerResponses. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds the authoritative force-fetch. - [Selection policies](/config/projects/selection-policies.llms.txt) — upstream scoring uses stale-block metrics. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the broader scenario this feature serves. --- --- # Retry > Source: https://docs.erpc.cloud/config/failsafe/retry > When a provider misbehaves, eRPC automatically rotates to the next one — and paces retries for missing data to match the chain's own block time. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Retry A single bad response no longer reaches your users. eRPC retries at two levels: rotate to a fresh upstream when a provider fails, and re-hit the same upstream for brief connectivity blips. For "block not yet available" conditions it paces retries to the chain's own block time instead of hammering upstreams pointlessly. **What you get** - Automatic failover across providers on any retryable error - Block-time-aware pacing for missing data — no hammering while waiting for the next block - A separate cap for "data not ready yet" retries so they can't crowd out hard-error failover - Per-method tuning via `matchMethod` — aggressive failover for reads, conservative for writes ## Quick taste Illustrative, not a tuned production config — rotate upstreams immediately on error, pace missing-data retries to block time: **Config path:** `projects[].networks[].failsafe[].retry` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } failsafe: - matchMethod: "*" retry: # rotate upstreams immediately on error maxAttempts: 5 delay: 0ms backoffFactor: 1.2 backoffMaxDelay: 3s # pace block-wait retries to chain block time emptyResultMaxAttempts: 2 emptyResultDelay: 1s ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, failsafe: [{ matchMethod: "*", retry: { // rotate upstreams immediately on error maxAttempts: 5, delay: "0ms", backoffFactor: 1.2, backoffMaxDelay: "3s", // pace block-wait retries to chain block time emptyResultMaxAttempts: 2, emptyResultDelay: "1s", }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure retry failover from scratch** ```text Set up eRPC retry so provider failures automatically rotate to the next upstream, with block-time-aware pacing for missing data. I'm running Ethereum mainnet and a couple of fast L2s (Base, Arbitrum). Use separate failsafe entries per finality state and set emptyResultDelay to match each chain's block cadence. My config is in my eRPC config. Read the full reference first: https://docs.erpc.cloud/config/failsafe/retry.llms.txt ``` **Prompt Example #2: tune emptyResultDelay and maxAttempts for my chains** ```text Audit the retry settings in my eRPC config: check that emptyResultDelay matches the block time of each configured chain, that emptyResultMaxAttempts won't multiply upstream calls into a fan-out, and that maxAttempts is roughly equal to my number of healthy upstreams. Flag any mismatches. Reference: https://docs.erpc.cloud/config/failsafe/retry.llms.txt ``` **Prompt Example #3: debug repeated missing-data errors on a fast L2** ```text My eRPC node on Polygon (2s blocks) keeps returning empty or missing-data responses instead of retrying. The erpc_network_retry_attempt_total metric shows reason=missing_data but I still get nulls. Diagnose whether retryEmpty is gated off, emptyResultMaxAttempts is exhausted too quickly, or emptyResultDelay is miscalibrated. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/retry.llms.txt ``` **Prompt Example #4: add pending-tx polling with block-time pacing** ```text I need eRPC to keep retrying eth_getTransactionReceipt until the tx is mined, paced to roughly one retry per block, without hammering upstreams. Enable retryPending and retryEmpty for that method only, cap emptyResultMaxAttempts sensibly, and leave other methods unaffected. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/retry.llms.txt ``` **Prompt Example #5: cap retry fan-out on large getLogs responses** ```text On Base, finalized eth_getLogs requests are producing huge responses (~100 MB) and when they retry they spike memory because up to 6 upstream calls parse the same body in parallel. Reduce maxAttempts for finalized getLogs to 2, tighten emptyResultMaxAttempts to 1, and keep the existing aggressive retry for unfinalized getLogs. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/failsafe/retry.llms.txt ``` --- ### Retry — full agent reference ### How it works **Two retry scopes, one config shape.** Both the network executor (`erpc/network_executor.go`) and the upstream executor (`upstream/upstream_executor.go`) consume the same `RetryPolicyConfig` struct, but their semantics differ: - **Network-scope retry** (`networkExecutor.runRetry`): after all upstreams have been tried within one execution round and still produced no satisfying response, the retry loop fires another full upstream sweep (all upstreams, ordered by the selection policy). This handles "every upstream is seeing the same error right now" scenarios and is the primary failover mechanism. - **Upstream-scope retry** (`upstreamExecutor.runRetry`): retries the same upstream's HTTP transport for transient connectivity blips. The default `maxAttempts: 1` disables it in practice; production configs typically set it to 2–3 only for idempotent methods where a brief TCP issue on a trusted endpoint is plausible. The two scopes compose multiplicatively: `network.maxAttempts: 3` × `upstream.maxAttempts: 3` = up to 9 physical calls per client request. Keep network attempts roughly equal to the number of healthy upstreams you want to exhaust. **Execution flow (non-consensus, non-hedge case).** `networkExecutor.Run` → `runRetryHedge` → `runRetry` calls `hedged(ctx)` which is ultimately `runUpstreamSweep`. Within one sweep, every upstream is tried in priority order until success or all return errors. After the sweep returns `(resp, err)`, `shouldRetryWithReason` classifies the outcome: 1. `err == nil` — no retry (success). 2. `ErrEndpointExecutionException` with `retryableTowardNetwork: false` — no retry. 3. `ErrUpstreamBlockUnavailable` — retry reason `"block_unavailable"` (unless `emptyResultMaxAttempts` cap reached). A verdict wrapped in `ErrUpstreamRequestSkipped` (block outside that upstream's bounds, judged non-retryable there) does not count: if every cause is one, no retry; otherwise the round falls through to the rules below. 4. `ErrEndpointMissingData` + `RetryEmpty == false` directive — no retry; otherwise reason `"missing_data"` (unless cap reached). 5. `IsRetryableTowardNetwork(err) == true` — reason `"retryable_error"`. A sweep whose every upstream answered "method unsupported" (`-32601`) or ignores the method is not retryable: neither a retry nor a hedge re-asks the upstreams, so an unknown method fails after one sweep. 6. `resp.IsResultEmptyish()` + `RetryEmpty == true` directive + result not accepted by the empty-result policy — reason `"empty_result"` (unless cap reached). 7. `RetryPending == true` + tx-lookup method — reason `"pending_tx"` (unless cap reached). Followed evidence belongs to one network instance and selector group. Networks with the same chain ID in different projects or instances do not share evidence. **Empty block traces.** At network scope, `debug_traceBlockByNumber` accepts `[]` early only when the existing followed segment proves the requested numeric block has no transactions and zero gas used. The cached header must match the requested height and canonical hash, with an explicit empty transaction list. Tags, missing transaction lists, and unfollowed heights retain normal retry and hedge behavior. The acceptance check makes no auxiliary RPC request. Whitespace inside or around the array does not change this policy. Without consensus, verified empty arrays also stop the upstream sweep. Setting `retry.emptyResultAccept` explicitly replaces the default: an empty list disables trace acceptance, while a list containing `debug_traceBlockByNumber` accepts all empty shapes for that method. Existing terminal all-empty behavior remains unchanged. Source: [`erpc/network_executor.go:L137-171`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L137-L171) **"Data not yet available" unified delay path.** When the retry reason is `block_unavailable`, `empty_result`, or `missing_data`, `computeDelay` takes a special path: it first tries `dynamicBlockUnavailableDelay()` — the per-network EMA block time × `blockUnavailableDelayMultiplier` (default 1.0). If the EMA hasn't warmed yet (returns 0), it falls back to the static `emptyResultDelay` config value. For genuine errors (`retryable_error`, `pending_tx`) it uses the standard `ComputeBackoff` formula. **`emptyResultDelay` is a static fallback, NOT a floor.** The dynamic EMA-based delay is unconditionally preferred when the EMA is warm. `emptyResultDelay` only activates before the EMA has seen enough block data (cold start). Setting `emptyResultDelay` does NOT set a floor on the dynamic path. **`emptyResultMaxAttempts` is a separate counter from `maxAttempts`.** It caps the total number of data-unavailability attempts (including the first try) via a single shared `dataUnavailableAttemptsCount` counter across ALL network retry rounds — not per round. With default value 2, only one empty-type retry fires across the entire request lifetime regardless of `maxAttempts`. **Backoff formula.** `ComputeBackoff(cfg, attempt)` where `attempt` is 0-based (first retry = 0). If `Delay == 0`: return 0 immediately. Otherwise: `d = Delay × BackoffFactor^attempt`, capped at `BackoffMaxDelay`, then additive uniform jitter in `[0, Jitter)` using `math/rand`. Because attempt is 0-indexed, the first retry always uses exactly `Delay` (exponent 0 = 1). **`retryEmpty` is the master gate.** When `false` (the default), neither scope retries empty/missing-data/block-unavailable responses — the null is passed through unchanged to the client. **Empty-as-error conversion.** The EVM post-forward hook converts `result: null` for methods in `markEmptyAsErrorMethods` into `ErrEndpointMissingData`. This fires only when `RetryEmpty == true`. The confidence guard (`emptyResultBeyondConfidence`) stops the conversion if the requested block is above the latest known head, returning the truthful null instead. **BestResponse preference.** While retrying, the loop tracks `bestResp` — the last non-nil response seen. When the final attempt fails with an error but `bestResp != nil`, the response is returned with `nil` error, preferring a result over an error. Source: [`erpc/network_executor.go:L264-267`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L264-L267) **`eth_sendRawTransaction` special-case.** If retries are exhausted and the final cause is `ErrEndpointExecutionException` for `eth_sendRawTransaction`, the raw execution error is returned unwrapped — the "execution reverted" IS the answer. Source: [`erpc/network_executor.go:L279-283`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L279-L283) **First-informative-error capture.** The network retry loop captures the first non-degenerate error in `firstInformativeErr`. Later retry rounds can degenerate into bare `ErrNoUpstreamsLeftToSelect` (all previously-tried upstreams marked consumed). On final wrap, the richer first error is surfaced rather than the degenerate one. Source: [`erpc/network_executor.go:L302-309`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L302-L309) **Upstream-scope retry differences.** The upstream executor does NOT have data-unavailability logic in `computeDelay` — it always uses `ComputeBackoff` regardless of retry reason. It does not track `bestResp` for emptyish responses. Its `shouldRetry` is simpler: only error-based, no response-based retry, no reason string. Non-retryable write methods (`evm.IsNonRetryableWriteMethod`) are also blocked at the upstream scope — `eth_sendRawTransaction` still uses network-scope retry for idempotency handling, but the upstream executor will not re-issue it. Source: [`upstream/upstream_executor.go:L243-246`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L243-L246) ### Config schema #### Envelope selector fields (`failsafe[i]` level, above `retry`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `matchMethod` | string | `"*"` | WildcardMatch pattern against JSON-RPC method. Empty string is a **validation error** after `SetDefaults` — use `"*"` explicitly. Legacy single-object YAML failsafe format forces `"*"` automatically. Source: [`common/validation.go:L985-988`](https://github.com/erpc/erpc/blob/main/common/validation.go#L985-L988) | | `matchFinality` | []string | `[]` (any) | Finality states: `finalized`, `unfinalized`, `realtime`, `unknown`. Empty = wildcard. At defaults-merge time: two arrays match if either is empty OR they share an element. At dispatch time: `slices.Contains`. No glob syntax inside the array. Numeric string values `"0"`–`"3"` are also accepted by YAML unmarshal for backward compatibility; any other string causes an unmarshal error at config load time. Source: [`common/defaults.go:L17-34`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L17-L34) | **`SelectExecutor` 4-tier priority** (first match wins within each tier): 1. Specific method + specific finality 2. Specific method, any finality 3. Wildcard method, specific finality 4. Wildcard method, any finality (catch-all) Source: [`common/match.go:L18-78`](https://github.com/erpc/erpc/blob/main/common/match.go#L18-L78) #### `RetryPolicyConfig` fields (`failsafe[i].retry`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `maxAttempts` | int | `3` (system); `5` for injected network default; `1` for upstream default | Total execution rounds including the first. `1` = no retries. Network-scope out-of-box default is `5`. Source: [`common/defaults.go:L127-157`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L127-L157) | | `delay` | Duration | `0` | Base delay before the first retry. `0` = retry immediately (does NOT disable retry — set `maxAttempts: 1` to disable). Source: [`common/defaults.go:L2247-2252`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2247-L2252) | | `backoffFactor` | float32 | `1.2` | Exponential multiplier per attempt (0-indexed). `1.0` = constant delay. Must be > 0 — validation error if explicitly set to `0`. Source: [`common/defaults.go:L2233-2238`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2233-L2238) | | `backoffMaxDelay` | Duration | `3s` | Cap on computed backoff before jitter. Must be non-zero — validation error if explicitly set to `0`. Source: [`common/defaults.go:L2240-2244`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2240-L2244) | | `jitter` | Duration | `0` | Uniform random additive jitter in `[0, jitter)` using non-crypto `math/rand`. Source: [`common/defaults.go:L2254-2259`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2254-L2259) | | `emptyResultAccept` | []string | `nil` (executor resolves built-in defaults) | Omitted or `null` uses `eth_getLogs`, `trace_filter`, `arbtrace_filter`, `eth_call`, `eth_getBalance`, `eth_getCode`, `eth_getStorageAt`, and `eth_getTransactionCount`, plus proof-gated block traces at network scope. Explicit or inherited lists replace that policy, including `[]`. Resolved config retains `null` rather than materializing the built-in list. Overrides `emptyResultIgnore` (deprecated). Source: [`common/defaults.go:L2459-2471`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2459-L2471) | | `emptyResultIgnore` | []string | `nil` | **DEPRECATED alias for `emptyResultAccept`.** Migrated to `emptyResultAccept` only when `emptyResultAccept == nil`. If both are set, `emptyResultIgnore` is silently ignored. Field is NOT cleared after migration. Source: [`common/defaults.go:L2261-2263`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2261-L2263) | | `emptyResultMaxAttempts` | int | `2` | Shared cap (including the first attempt) for ALL data-unavailability reasons: `empty_result`, `missing_data`, `block_unavailable`, `pending_tx`. A single `dataUnavailableAttemptsCount` counter is shared across all network retry rounds — not per round. Source: [`common/defaults.go:L1984`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1984) | | `emptyResultDelay` | Duration | `0` (no hardcoded fallback; inherits from parent defaults only) | Static fallback delay before data-availability retries **when EMA block time is cold (returns 0)**. When EMA is warm, dynamic delay overrides this unconditionally. `0` means "use dynamic only" — not "no delay". Set to ~1s for Ethereum cold-start safety. Source: [`common/config.go:L1355-1361`](https://github.com/erpc/erpc/blob/main/common/config.go#L1355-L1361) | | `blockUnavailableDelay` | Duration | `0` | **DEPRECATED.** `json:"-"` — never appears in TypeScript types. Merged into `emptyResultDelay` when `emptyResultDelay == 0`, then cleared to 0. Deprecation warning always logged when found. Source: [`common/config.go:L1363-1369`](https://github.com/erpc/erpc/blob/main/common/config.go#L1363-L1369) | #### Related fields outside `RetryPolicyConfig` | Field | YAML path | Type | Default | Behavior | |---|---|---|---|---| | `retryEmpty` | `networks[].directiveDefaults.retryEmpty` | \*bool | `nil` (→ false) | Master gate. When false, neither scope retries empty/missing-data/block-unavailable. Overridable per-request via `X-ERPC-Retry-Empty: true` header or `?retry-empty=true`. | | `retryPending` | `networks[].directiveDefaults.retryPending` | \*bool | `nil` | Retries tx-lookup methods until `emptyResultMaxAttempts` reached. | | `blockUnavailableDelayMultiplier` | `networks[].evm.blockUnavailableDelayMultiplier` | \*float64 | `1.0` | Scales EMA block time: `dynamicDelay = blockTime × multiplier`. Source: [`common/defaults.go:L1978`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1978) | | `emptyResultConfidence` | `networks[].evm.emptyResultConfidence` | string | `"blockHead"` | Confidence guard: `blockHead` = trust empties at chain tip; `finalizedBlock` = stricter, retry empties for non-finalized blocks. Source: [`common/defaults.go:L2075-2079`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2075-L2079) | | `markEmptyAsErrorMethods` | `networks[].evm.markEmptyAsErrorMethods` | []string | `["eth_blockNumber","eth_getBlockByNumber","eth_getTransactionByHash","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getUncleByBlockHashAndIndex","eth_getUncleByBlockNumberAndIndex","debug_traceTransaction","trace_transaction","trace_block","trace_get"]` | Methods whose `null` result is converted to `ErrEndpointMissingData`. Conversion only fires when `retryEmpty == true`. Source: [`common/defaults.go:L2044-2058`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2044-L2058) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Finality-split catch-alls (the production baseline).** Realtime/unfinalized requests race block-availability: a node may not have propagated the latest block yet. A non-zero `delay` gives the shared-state poller a few milliseconds to refresh before the next upstream is tried. On EVM, finalized requests have no such race — `delay: 0` rotates immediately: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" matchFinality: ["realtime", "unfinalized"] retry: maxAttempts: 6 # Non-zero: gives shared-state propagation time to catch up before the # next upstream sweep fires. 0ms here would retry instantly, amplifying # block-availability races across upstreams. delay: 50ms emptyResultMaxAttempts: 2 emptyResultDelay: 500ms # cold-start fallback; warm EMA overrides this - matchMethod: "*" matchFinality: ["finalized", "unknown"] retry: maxAttempts: 6 # Finalized EVM data is canonical — no block-availability race, rotate instantly. delay: 0ms emptyResultMaxAttempts: 2 emptyResultDelay: 500ms ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "*", matchFinality: ["realtime", "unfinalized"], retry: { maxAttempts: 6, // Non-zero: gives shared-state propagation time to catch up. delay: "50ms", emptyResultMaxAttempts: 2, emptyResultDelay: "500ms", }, }, { matchMethod: "*", matchFinality: ["finalized", "unknown"], retry: { maxAttempts: 6, // Finalized EVM data is canonical — no race, rotate instantly. delay: 0, emptyResultMaxAttempts: 2, emptyResultDelay: "500ms", }, }, ] ``` > **SVM networks: finalized data *does* have an availability race.** On Solana, consensus > finality and RPC indexing are separate steps: a slot can be rooted (so > `getSlot(finalized)` reports it) while the provider's indexer has not written the block > yet, and `getBlock` on it answers `-32004 BlockNotAvailable` or `-32014 > BlockStatusNotAvailableYet`. A zero `delay` on `matchFinality: ["finalized"]` therefore > volleys across every upstream while they are all equally early. Give SVM finalized > catch-alls a non-zero `delay` (~150 ms, roughly a slot) too. eRPC already caps > `getSlot(finalized)` at the pool's indexed frontier and short-circuits provably > unindexed `getBlock` calls to shrink this window — see > [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt). **2. Aggressive `eth_getBlockByHash` retry.** During indexing, `eth_getBlockByNumber` may return a hash that only a few nodes have ingested yet. Null from one node is likely "not propagated yet", not "does not exist" — so raise both caps to 6 and keep `emptyResultDelay` at 500ms to space out the rotation: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getBlockByHash" retry: maxAttempts: 6 delay: 0ms # Match maxAttempts: every attempt is an empty-result attempt here — # a null block hash means "node hasn't seen it yet", never "not found". emptyResultMaxAttempts: 6 emptyResultDelay: 500ms ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getBlockByHash", retry: { maxAttempts: 6, delay: "0ms", // Match maxAttempts: every attempt is an empty-result attempt here. emptyResultMaxAttempts: 6, emptyResultDelay: "500ms", }, }] ``` **3. Conservative tx-lookup failsafe — one retry, one block of patience.** A null `eth_getTransactionByHash` / `eth_getTransactionReceipt` means the tx is not indexed yet. Rotating through all 6 upstreams × 6 retries (18–33 calls) for a tx that simply isn't propagated yet wastes quota. Cap to 2 attempts; the EMA block-time delay drives the single retry once it warms up, so `emptyResultDelay` is only a cold-start fallback. No hedge: parallel-blasting a not-found tx just multiplies load: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt" retry: maxAttempts: 2 delay: 500ms # emptyResultMaxAttempts intentionally omitted → inherits default 2 # (one original + one retry). Explicit 1 would mean ZERO retries. emptyResultDelay: 500ms # cold-start; warm EMA drives ~one block wait ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt", retry: { maxAttempts: 2, delay: "500ms", // emptyResultMaxAttempts omitted → default 2 (one original + one retry). // Explicit 1 would mean ZERO retries — the cap is hit at attempt 0. emptyResultDelay: "500ms", }, }] ``` **4. Capping retry fan-out on large `eth_getLogs` responses.** Finalized historical scans can produce very large responses (100 MB+). With `maxAttempts: 6` and hedging, each client request can trigger up to 12 upstream calls that each parse the same large body, spiking transient heap. Tighten finalized getLogs to 2 attempts and suppress empty-result retry (`emptyResultMaxAttempts: 1`) while keeping aggressive retry for unfinalized data where reorg detection matters: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: ["unfinalized", "unknown"] retry: maxAttempts: 6 delay: 0ms emptyResultDelay: 500ms - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: ["finalized"] retry: # Cap fan-out: 100 MB responses × 6 retries × hedge = >1 GB transient heap. maxAttempts: 2 delay: 0ms emptyResultDelay: 500ms # 1 means ZERO empty-result retries (cap reached at attempt 0) — finalized # EVM data is canonical, a null here is definitive, not "not yet". emptyResultMaxAttempts: 1 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: ["unfinalized", "unknown"], retry: { maxAttempts: 6, delay: "0ms", emptyResultDelay: "500ms" }, }, { matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: ["finalized"], retry: { // Cap fan-out: large responses × retries × hedge = heap spike. maxAttempts: 2, delay: "0ms", emptyResultDelay: "500ms", // 1 = ZERO empty-result retries — a finalized EVM null is definitive. emptyResultMaxAttempts: 1, }, }, ] ``` **5. Ethereum mainnet with 1 s `emptyResultDelay` and state-read integrity.** Mainnet's ~12 s block time means the EMA quickly warms to ~12 s, making the static fallback `emptyResultDelay` mostly irrelevant in steady state — but setting it to 1000ms ensures cold-start (first few minutes after deploy) doesn't hammer upstreams with zero-delay empty-result retries. The `emptyResultDelay: 1000ms` value also surfaces in `erpc_network_data_unavailable_wait_seconds` histograms as a debug signal when the EMA is cold: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: ["unfinalized", "unknown"] retry: maxAttempts: 6 delay: 0ms # 1000ms cold-start safety: Ethereum block time ~12s, but the EMA needs # a few blocks to warm; without this, cold-start empty retries fire at 0ms. emptyResultDelay: 1000ms ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: ["unfinalized", "unknown"], retry: { maxAttempts: 6, delay: "0ms", // 1000ms cold-start safety: EMA warms in ~minutes; before that, // emptyResultDelay is the only guard against 0ms retry hammering. emptyResultDelay: "1000ms", }, }] ``` ### Request/response behavior - `retryEmpty` can be overridden per-request via `X-ERPC-Retry-Empty: true` header or `?retry-empty=true` query param, overriding the `directiveDefaults.retryEmpty` network setting. - `retryPending` can similarly be overridden per-request via `X-ERPC-Retry-Pending: true`. - When retries exhaust and a prior round produced any non-nil `bestResp`, eRPC returns that response with `nil` error rather than surfacing the final error — caller receives an emptyish result, not an error. Source: [`erpc/network_executor.go:L264-267`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L264-L267) - `ErrEndpointExecutionException` (e.g., execution reverted) is never retried at network scope. For `eth_sendRawTransaction`, the execution error is returned unwrapped — not wrapped in `ErrFailsafeRetryExceeded`. Source: [`erpc/network_executor.go:L279-283`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L279-L283) - Batch/composite requests bypass both scopes' retry logic entirely. Source: [`erpc/network_executor.go:L378-380`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L378-L380) - `SleepCtx` respects context cancellation — if the client disconnects during a delay sleep, the retry loop exits immediately. ### Best practices - **Set `emptyResultDelay: 1s` for Ethereum, ~200ms for fast L2s.** Without it, cold-start empty-result retries fire with zero delay, hammering upstreams during the first minutes after deploy. - **Enable `retryEmpty` at the network level only when clients need it.** It is `false` by default; enabling it per-request via the `X-ERPC-Retry-Empty` header is safer for mixed workloads. - **Size `maxAttempts` ≈ number of healthy upstreams.** The network scope tries a fresh sweep each round — if you have 3 upstreams, `maxAttempts: 3–5` exhausts them all. - **Keep `emptyResultMaxAttempts` small (2–3).** The counter is shared across all retry rounds; raising it to match `maxAttempts` can multiply total call volume sharply when all upstreams return missing data. - **Leave upstream-scope `maxAttempts: 1` (disabled) for most use cases.** Only raise it for trusted archival nodes on idempotent methods where TCP blips are the dominant failure mode. - **Combine with hedge for latency SLOs.** Retry covers errors; hedge cuts tail latency. They compose: each retry attempt fires a fresh hedge race. See [Hedge](/config/failsafe/hedge.llms.txt). - **Remove `emptyResultIgnore` once you've added `emptyResultAccept`.** If both are set, `emptyResultIgnore` is silently dropped — it does NOT merge with `emptyResultAccept`. ### Edge cases & gotchas 1. **`emptyResultMaxAttempts` gates ALL data-availability reasons via one shared counter.** With default `emptyResultMaxAttempts: 2`, only one empty-type retry fires across the entire request lifetime, regardless of `maxAttempts`. Confirmed by `TestNetworkExecutor_ShouldRetry_DataUnavailableSharesOneCap`. 2. **Zero EMA + zero `emptyResultDelay` → immediate empty retry.** During startup (first minutes) the EMA is cold. If `emptyResultDelay` is also `0`, missing-data retries fire with no delay, hammering upstreams. Set `emptyResultDelay: 1s` for Ethereum, `~200ms` for fast chains. Confirmed by `TestNetworkExecutor_ComputeDelay_EmptyResultFallsBackToFixed`. 3. **`emptyResultDelay` is NOT a floor; EMA overrides it unconditionally when warm.** Do not rely on `emptyResultDelay` as a minimum spacing in steady state — it only applies during cold start. See [`common/config.go:L1355-L1361`](https://github.com/erpc/erpc/blob/main/common/config.go#L1355-L1361). 4. **`emptyResultDelay` is the unified fallback for BOTH `empty_result` AND `block_unavailable` retries.** The former `blockUnavailableDelay` field was merged into `emptyResultDelay`. A config with `blockUnavailableDelay` set still loads but emits a deprecation warning, then uses the value as `emptyResultDelay`. Confirmed by `TestNetworkExecutor_ComputeDelay_BlockUnavailableUsesEmptyResultDelay`. 5. **`retryEmpty == false` gates BOTH the upstream mark-empty-as-error conversion AND network/upstream retry decisions.** When `retryEmpty: false`, `upstreamPostForward_markUnexpectedEmpty` returns the raw null without converting it to `ErrEndpointMissingData`. Even if a null is converted by some other path, `shouldRetryWithReason` and `shouldRetry` check the directive again and block the retry. Confirmed by `TestNetworkForward_RetryEmptyDisabled_BlocksMissingData`. 6. **`emptyResultAccept` silences empty-result retry but NOT `missing_data` retry.** If an upstream returns an explicit JSON-RPC error classified as `ErrEndpointMissingData` (e.g., `missing trie node`), it bypasses `emptyResultAccept` and triggers retry unless `retryEmpty == false`. Confirmed by `TestNetworkForward_TryAllUpstreams_AllEmpty_DelayBetweenRounds`. 7. **Within-round upstream fallback has no delay.** Delays fire between retry rounds, not between upstreams within a round. Upstream A fails → upstream B is tried immediately within the same sweep. Confirmed by `TestNetworkForward_TryAllUpstreams_FallbackWithinSameRound`. 8. **All-upstreams-missing-data = `maxAttempts` rounds × N upstreams calls.** With `maxAttempts: 3` and 2 upstreams both returning `ErrEndpointMissingData`, 6 total upstream calls are made. Confirmed by `AllUpstreamsMissingData_NetworkRetryHappens`. 9. **`bestResp` masks later errors.** A prior empty response (round 1) beats a subsequent hard error (round 2) — caller receives `(emptyResp, nil)`. This can hide retry-round errors behind an empty-but-valid shell. Confirmed by `TestNetworkForward_TryAllUpstreams_MixedErrorAndEmpty`. 10. **`emptyResultIgnore` + `emptyResultAccept` both set → `emptyResultIgnore` silently dropped.** The migration condition is `emptyResultAccept == nil`. If both are present, only `emptyResultAccept` takes effect. Field is not cleared. Source: [`common/defaults.go:L2262`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2262). 11. **`backoffFactor: 0` or `backoffMaxDelay: 0` are validation errors.** Since `SetDefaults` always fills `1.2` and `3s`, these only surface when explicitly set to `0` in config. Source: [`common/validation.go:L1020-L1027`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1020-L1027). 12. **Client-side errors (`ErrEndpointClientSideException`, -32600) ARE retryable at network scope.** No `retryableTowardNetwork: false` flag — another upstream might accept the request. Confirmed by `TestIsRetryableTowardNetwork_ClientError`. 13. **`ErrFailsafeConfiguration` aborts startup, never raised at request time.** Trigger: circuit breaker in a network-scope failsafe entry. Consensus in an upstream-scope failsafe entry is rejected earlier, by config validation. 14. **Backoff attempt index is 0-based.** First retry = attempt 0, so `BackoffFactor^0 = 1` — the first retry always uses exactly `Delay`. Only second retry onward grows. Differs from libraries where attempt 0 is the initial request. 15. **`blockUnavailableDelay` migration does not overwrite user-set `emptyResultDelay`.** If both are set, `blockUnavailableDelay` is discarded (deprecation warning still fires). Source: [`common/defaults.go:L2269`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2269). 16. **Wrong-empty punishment respects block availability bounds.** When an upstream returns null for a method in `markEmptyAsErrorMethods` but the block is outside its configured `blockAvailability` range, the upstream's `MisbehaviorsTotal` is NOT incremented. Confirmed by `TestNetworkForward_WrongEmpty_SkipPunishment_BlockAvailabilityBounds`. 17. **Failsafe defaults merge uses wildcard method matching.** A default entry `matchMethod: "eth_*"` provides defaults for network entry `matchMethod: "eth_getBlockByNumber"`. A catch-all `matchMethod: "*"` is required to cover all entries uniformly. Source: [`common/defaults.go:L1793-L1832`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1793-L1832). 18. **Upstreams that returned MissingData in round N are eligible again in round N+1 — unless the verdict was permanent.** A not-yet-available miss does not block re-selection in the next retry round (`TestNetworkForward_UpstreamReselection_MissingDataSucceedsOnRetry`). A permanent missing-data verdict (SVM `-32007`/`-32009`, a history page that ends at the upstream's floor) is final for that upstream within the client request: no hedge leg, network retry or upstream retry asks it again, and the request ends with the verdict once every selected upstream has given one. Confirmed by `TestSvm_PermanentMissingData_SweepsEachUpstreamOnce`. [`common/request.go:L1728-1742`](https://github.com/erpc/erpc/blob/main/common/request.go#L1728-L1742) 19. **`IsRetryableTowardNetwork` uses explicit iteration over multi-error wrappers.** The function handles `errors.Join`-style wrappers by iterating children explicitly — if ANY child is retryable, the bundle is retryable. If the wrapper doesn't implement `Unwrap() []error`, the code falls through to single-cause chain walk (only first child is seen). Source: [`common/errors.go:L2400-2410`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2400-L2410) 20. **`IsRetryableTowardsUpstream` blocklist.** The following error codes are never retried at upstream scope: `ErrCodeFailsafeCircuitBreakerOpen`, `ErrCodeUpstreamRequestSkipped`, `ErrCodeUpstreamMethodIgnored`, `ErrCodeEndpointUnsupported`, `ErrCodeEndpointBillingIssue`, `ErrCodeJsonRpcRequestUnmarshal`, `ErrCodeEndpointExecutionException`, `ErrCodeEndpointUnauthorized`, `ErrCodeEndpointRequestTooLarge`, `ErrCodeEndpointContentValidation`. Any `IsCapacityIssue` error (rate-limits) is also blocked. Source: [`common/errors.go:L2455-2497`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2455-L2497) 21. **`IsRetryableTowardNetwork` full classification by error type.** `ErrUpstreamsExhausted` with no cause → false; wrapping all `ErrEndpointExecutionException` → false; wrapping any `ErrEndpointMissingData`, `ErrEndpointServerSideException`, or mixed timeout+missing-data → true. Standalone `ErrEndpointClientSideException` (-32600) → true (no `retryableTowardNetwork: false` flag). Confirmed by `common/errors_retry_test.go`. Source: [`common/errors.go:L2379-2436`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2379-L2436) ### Observability | Metric | Type | Labels | When fired | |---|---|---|---| | `erpc_network_retry_attempt_total` | counter | project, network, category, reason, finality | Every network-scope retry that fires; `reason` ∈ {`empty_result`, `pending_tx`, `retryable_error`, `block_unavailable`, `missing_data`} | | `erpc_network_data_unavailable_wait_seconds` | histogram | project, network, category, reason, finality | Wall-clock delay slept before a data-unavailability retry (`block_unavailable`, `empty_result`, `missing_data` — NOT `pending_tx`); buckets: 0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64 | | `erpc_upstream_attempt_outcome_total` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | Per physical upstream attempt; `is_retry="true"` when upstream retries fired | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, error, severity, finality, user, agent_name | Final failed request after all retries exhausted; `attempt` label = total attempt count | **OTel span attributes** (set on the span wrapping each upstream attempt): - `execution.attempts`, `execution.retries` — aggregate totals across all scopes - `execution.hedges` — total hedge fires across all scopes - `execution.network_attempts`, `execution.network_retries`, `execution.network_hedges` — network-scope counters - `execution.upstream_attempts`, `execution.upstream_retries`, `execution.upstream_hedges` — upstream-scope counters Source: [`common/exec_state.go:L279-285`](https://github.com/erpc/erpc/blob/main/common/exec_state.go#L279-L285) **Error codes produced:** | Error | When produced | |---|---| | `ErrFailsafeConfiguration` | Startup only — circuit breaker at network scope. Server aborts before serving any request. (Consensus at upstream scope is rejected earlier, by config validation.) Source: [`common/errors.go:L1721-1732`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1721-L1732) | | `ErrFailsafeRetryExceeded` | After all retry rounds exhausted; wraps the last error with `ScopeNetwork` or `ScopeUpstream` and `durationMs`. For `eth_sendRawTransaction` with `ErrEndpointExecutionException`, the error is returned unwrapped (not inside `ErrFailsafeRetryExceeded`). Source: [`erpc/network_executor.go:L279-283`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L279-L283) | **Log messages:** - `config: retry.blockUnavailableDelay is deprecated and has been merged into retry.emptyResultDelay; please update your config` — emitted as `log.Warn` at `RetryPolicyConfig.SetDefaults` time whenever `BlockUnavailableDelay > 0` is found, even if the value was discarded. Source: [`common/defaults.go:L2272`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2272) - `config: evm.maxFutureBlockRetryDistance is deprecated and ignored; use evm.emptyResultConfidence (blockHead|finalizedBlock) instead` — emitted as `log.Warn` at `EvmNetworkConfig.SetDefaults` time. Source: [`common/defaults.go:L2081`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2081) ### Source code entry points - [`common/config.go:L1279-L1387`](https://github.com/erpc/erpc/blob/main/common/config.go#L1279-L1387) — `FailsafeConfig`, `RetryPolicyConfig` struct definitions; `emptyResultDelay` comment at L1355-L1361; `blockUnavailableDelay` deprecation at L1363-L1369 - [`common/defaults.go:L2225-L2305`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2225-L2305) — `RetryPolicyConfig.SetDefaults`: all per-field defaults, `emptyResultIgnore` migration (L2261-L2263), `blockUnavailableDelay` migration + warn (L2265-L2274) - [`erpc/network_executor.go:L227-L349`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L227-L349) — `networkExecutor.runRetry`: main network-scope retry loop, `shouldRetryWithReason`, `computeDelay`, data-unavailability delay path (L481-L513), shared empty-result cap counter (L358-L377) - [`upstream/upstream_executor.go:L186-L255`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L186-L255) — `upstreamExecutor.runRetry`: upstream-scope loop; simpler semantics, always `ComputeBackoff`, no data-availability logic - [`failsafe/backoff.go:L21-L65`](https://github.com/erpc/erpc/blob/main/failsafe/backoff.go#L21-L65) — `ComputeBackoff` (pure function) and `SleepCtx` (context-aware sleep) - [`architecture/evm/common.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go) — `upstreamPostForward_markUnexpectedEmpty`, `emptyResultBeyondConfidence`; `null` → `ErrEndpointMissingData` conversion - [`architecture/evm/hooks.go:L109-L183`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go#L109-L183) — `HandleUpstreamPostForward` dispatcher that calls `markUnexpectedEmpty` for methods in `markEmptyAsErrorMethods` - [`common/config.go:L2105-L2152`](https://github.com/erpc/erpc/blob/main/common/config.go#L2105-L2152) — `DirectiveDefaultsConfig` (`retryEmpty`, `retryPending` fields) - [`common/errors.go:L2379-L2436`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2379-L2436) — `IsRetryableTowardNetwork`: multi-error explicit iteration (L2400-L2410); `IsRetryableTowardsUpstream` blocklist (L2455-L2497) - [`erpc/networks_registry.go:L98-L137`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L98-L137) — constructs `dynamicBlockUnavailableDelay` closure (EMA × multiplier) and wires into each `networkExecutor` - [`erpc/networks_retry_missing_data_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_retry_missing_data_test.go) — integration tests covering network retry, missing data, execution exception, retry-empty directive, upstream re-selection, wrong-empty punishment ### Related pages - [Hedge](/config/failsafe/hedge.llms.txt) — wraps retry; each retry attempt fires a fresh hedge race. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds the whole retry+hedge execution from outside. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — upstream-scope only; trips fast when a single provider degrades. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — decides which upstream each sweep round picks first. - [Rate limiters](/config/rate-limiters.llms.txt) — prevents retry bursts from blowing provider budgets. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome this feature primarily serves. --- --- # Timeout > Source: https://docs.erpc.cloud/config/failsafe/timeout > Give every request a hard latency budget — three nested layers keep stalled upstreams from tying up your connections indefinitely. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Timeout A single slow upstream can monopolize connections and ripple into your application's latency. eRPC solves this with three nested timeout layers — a hard HTTP ceiling, a lifecycle bound covering every retry and hedge, and a per-upstream limit that triggers failover instead of waiting forever. Set them once and never babysit stalled providers again. **What you get** - Predictable latency budgets for callers regardless of upstream behavior - Automatic failover when a single upstream stalls — other providers still win - Adaptive timeouts that self-tune to per-method P50/P90/P99 as traffic flows - Protection against feedback loops: a built-in floor prevents fast quantiles from collapsing the budget ## Quick taste Illustrative, not a tuned production config — adaptive network timeout keyed to per-method P99: **Config path:** `projects[].networks[].failsafe[].timeout` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } failsafe: - matchMethod: "*" timeout: duration: # adaptive per-method P99: fast methods get tight budgets automatically quantile: 0.99 base: 2s # floor prevents budget from collapsing after a run of fast responses min: 500ms max: 30s ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, failsafe: [{ matchMethod: "*", timeout: { duration: { // adaptive per-method P99: fast methods get tight budgets automatically quantile: 0.99, base: "2s", // floor prevents budget from collapsing after a run of fast responses min: "500ms", max: "30s", }, }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up timeout budgets from scratch** ```text Add timeout failsafe policies to my eRPC config from scratch so every request has a hard latency budget. Use adaptive (quantile) mode at the network scope for per-method self-tuning, and a tighter upstream-scope timeout so a single stalled provider triggers failover rather than burning the whole budget. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/failsafe/timeout.llms.txt ``` **Prompt Example #2: audit existing timeouts for footguns** ```text Audit the timeout settings in my eRPC config: check that network timeouts are larger than upstream timeout × retry maxAttempts, that quantile mode always has a base or max (cold-start fail-open risk), that min is not set to 0 in quantile mode (feedback-loop collapse risk), and that all failsafe timeouts are shorter than server.maxTimeout. Show any violations with suggested fixes. Reference: https://docs.erpc.cloud/config/failsafe/timeout.llms.txt ``` **Prompt Example #3: debug requests timing out unexpectedly** ```text My eRPC instance is returning timeout errors on some requests. Help me figure out which timeout layer is firing (server.maxTimeout vs network-scope vs upstream-scope), what Prometheus metrics and response headers to check, and how to adjust the config in my eRPC config so the right layer fires at the right time. Reference: https://docs.erpc.cloud/config/failsafe/timeout.llms.txt ``` **Prompt Example #4: tune timeouts for archival / batch workloads** ```text I run both latency-sensitive realtime queries and heavy archival eth_getLogs scans through the same eRPC instance. Add per-method timeout failsafe entries in my eRPC config so archive methods get a generous ceiling while realtime reads stay tight, without raising server.maxTimeout for everyone. Reference: https://docs.erpc.cloud/config/failsafe/timeout.llms.txt ``` **Prompt Example #5: pair upstream timeouts with retry for automatic failover** ```text Configure eRPC so that when one upstream stalls it times out quickly and the network-level retry automatically routes to a different provider — without the caller ever seeing a failure unless ALL providers are down. Use a tight upstream-scope timeout and a generous network timeout in my eRPC config that covers the full retry budget. Reference: https://docs.erpc.cloud/config/failsafe/timeout.llms.txt ``` --- ### Timeout — full agent reference ### How it works **Three-layer hierarchy.** From outermost to innermost: 1. **HTTP server `maxTimeout`** (`server.maxTimeout`, default `150s`). Applied via `TimeoutHandler` wrapping the entire HTTP handler using `context.WithTimeoutCause(r.Context(), dt, ErrHandlerTimeout)`. This is an absolute ceiling — no request survives it regardless of what failsafe policies are set. Source: [`erpc/http_server.go:L65-67`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L65-L67), [`erpc/http_timeout.go:L20-143`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L20-L143). 2. **Network-scope failsafe timeout** (`networks[].failsafe[].timeout`). Applied as `context.WithTimeoutCause` wrapping the entire `networkExecutor.Run` call — it bounds ALL retries and hedges for that method match, not just a single attempt. Fires with `ErrDynamicTimeoutExceeded`, later classified as `ErrFailsafeTimeoutExceeded{scope: "network"}`. Source: [`erpc/network_executor.go:L164-171`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L164-L171). 3. **Upstream-scope failsafe timeout** (`upstreams[].failsafe[].timeout`). Applied inside the upstream's own failsafe executor, bounding one upstream's entire retry budget. Classification becomes `ErrFailsafeTimeoutExceeded{scope: "upstream"}`. When this fires, the network's retry or selection policy can still route elsewhere. **No per-attempt timeout.** There is no isolated timeout wrapping only a single RPC call. Both scopes are lifecycle-scoped. A 500ms network timeout with `maxAttempts: 3` gives a 500ms total budget shared across all three attempts — not 500ms each. This is intentional and test-locked (`erpc/networks_timeout_test.go:L378`). **`NewTimeoutFunc` construction path.** `common.NewTimeoutFunc(logger, cfg)` builds a `TimeoutFunc` from `TimeoutPolicyConfig`. The returned function is called per-request and returns `*time.Duration` (nil disables the timeout). Construction steps: 1. `cfg == nil || cfg.Duration.IsZero()` → return nil (no timeout for this scope) 2. `quantile <= 0` → pre-compute `dur = spec.Resolve(nil)` once at construction, return a constant function 3. `quantile > 0` and `min == 0` → apply the auto-floor to a local copy, then build a per-request closure 4. Per-request closure calls `ntw.GetMethodMetrics(method).GetResponseQuantiles()` then `resolved.Resolve(qt)`, and emits `MetricNetworkTimeoutDurationSeconds` on each call Source: [`common/timeout_func.go:L23-83`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L23-L83). **`ErrDynamicTimeoutExceeded` sentinel type.** Declared as `var ErrDynamicTimeoutExceeded = errors.New("dynamic timeout exceeded")` at [`common/errors.go:L1981-1984`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1981-L1984). It is a plain `*errors.errorString` — NOT a `StandardError` (has no `Code`, `Message`, or `Details` fields). This is intentional: it is a control-flow signal, not a client-facing domain error. Detection via `errors.Is(err, common.ErrDynamicTimeoutExceeded)` works through context propagation. After classification it is wrapped by `NewErrFailsafeTimeoutExceeded(scope, cause, &startTime)` into a `StandardError` with code `ErrCodeFailsafeTimeoutExceeded`. Source: [`common/errors.go:L1588-1603`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1588-L1603). **Per-method quantile tracking implementation.** The `QuantileTracker` maintained by the network's method-metrics registry uses a streaming quantile algorithm (not a fixed histogram). It accumulates actual wall-clock response durations per method and answers `GetQuantile(q)` queries. `eth_call` and `eth_getLogs` accumulate independent trackers. The `AdaptiveDuration.ResolveForRequest` utility bridges from a request context to the tracker. Source: [`common/network.go:L51-60`](https://github.com/erpc/erpc/blob/main/common/network.go#L51-L60), [`common/adaptive_duration.go:L270-290`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L270-L290). **`TimeoutHandler` response buffering.** `TimeoutHandler` buffers the entire response in a pooled `bytes.Buffer` via `timeoutWriter`. On timeout it discards the buffer and writes the fixed JSON-RPC error body. On normal completion within the deadline it copies buffered headers and body to the wire. Source: [`erpc/http_timeout.go:L36-143`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L36-L143). **Static mode.** Set `duration` to a scalar (`"30s"`) or an object with only `base`. The timeout is a fixed constant. `min` and `max` are ignored in static mode — `Resolve` returns `base` unchanged. Source: [`common/adaptive_duration.go:L88-89`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L88-L89). **Quantile-adaptive mode.** When `quantile > 0`, the effective timeout is computed per request as: ``` effective = clamp(base + P(q) of method latency, min, max) ``` Latency is tracked per *(network × method)* using a streaming `QuantileTracker`. `eth_call` and `eth_getLogs` accumulate independent histograms. The `base` offset adds a constant buffer on top of the quantile value. **Cold-start behavior.** When no latency data exists yet, `AdaptiveDuration.Resolve` returns `Min` as the adaptive component (NOT `base`). If that also resolves to zero, `coldStartFallback` in `NewTimeoutFunc` tries `base` first, then `max`, and returns nil (fail-open) if both are zero. **Cold-start priority order: `base > max > nil (fail-open)`.** Always set `base` or `max` when using quantile mode. Source: [`common/timeout_func.go:L85-93`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L85-L93). **Feedback-loop prevention floor.** When `quantile > 0` and `min` is not configured, `NewTimeoutFunc` auto-populates `min = base/2` (or `500ms` when `base == 0`) on a local copy of the spec. Without this floor, fast quantiles could shrink the timeout so aggressively that all requests start timing out, keeping the quantile low in a self-reinforcing loop. The auto-floor is applied to a local copy — the original config is never mutated. Source: [`common/timeout_func.go:L29-37`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L29-L37). **Retry interaction.** The network timeout is the outer boundary; retries run inside it. A common footgun is setting the network timeout shorter than `upstream.timeout × maxAttempts`. When retry exhausts and the last attempt timed out, `ErrFailsafeRetryExceeded` wins as the top-level error; `erpc_network_timeout_fired_total` does NOT increment in this case. **Hedge interaction.** All legs of a hedge race share the same deadline. If the network timeout fires before any leg wins, all legs are cancelled. **Error sentinel distinction.** `ErrHandlerTimeout` (server) and `ErrDynamicTimeoutExceeded` (failsafe) are different sentinels. The network executor checks for `ErrDynamicTimeoutExceeded` specifically — it will never misclassify an HTTP-server timeout as `ErrFailsafeTimeoutExceeded`. Source: [`erpc/networks.go:L1427-1432`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1427-L1432). **Timeout attribution and counter guards.** `MetricNetworkTimeoutFiredTotal` is incremented by the scope that owns the policy. Four guards prevent double-counting at `erpc/networks.go:L1435-L1438`: 1. `failsafeExecutor.HasTimeout()` — this scope has a configured timeout policy. 2. `errors.Is(execErr, common.ErrDynamicTimeoutExceeded)` — the eRPC-specific sentinel is present; generic `context.DeadlineExceeded` from a parent context does not satisfy this. 3. `!HasErrorCode(execErr, ErrCodeFailsafeRetryExceeded)` — retry-exhausted suppression: when retry exhausts and the last attempt timed out, `ErrFailsafeRetryExceeded` wins and the timeout counter does not fire. 4. `!HasErrorCode(execErr, ErrCodeFailsafeTimeoutExceeded)` — cross-scope suppression: when an upstream-scope timeout already classified the error, the network-scope counter does NOT double-count it. Source: [`erpc/networks.go:L1424-1451`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1424-L1451), [`erpc/networks_timeout_test.go:L495-538`](https://github.com/erpc/erpc/blob/main/erpc/networks_timeout_test.go#L495-L538). ### Config schema #### `server.maxTimeout` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `server.maxTimeout` | `*Duration` | `150s` ([`erpc/http_server.go:L65-67`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L65-L67)) | Absolute HTTP-handler ceiling. POST → HTTP 200 + JSON-RPC `-32603`; non-POST → HTTP 504. No failsafe policy can exceed this. Always set failsafe timeouts shorter. | #### `TimeoutPolicyConfig` — network or upstream scope All fields live under `networks[].failsafe[].timeout` or `upstreams[].failsafe[].timeout`. Struct: [`common/config.go:L1406-1408`](https://github.com/erpc/erpc/blob/main/common/config.go#L1406-L1408). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `timeout.duration` | `Duration \| AdaptiveDuration` | Network: `120s` ([`common/defaults.go:L134-136`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L134-L136)); Upstream: `60s` ([`common/defaults.go:L155-157`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L155-L157)) | The timeout budget. Scalar sets `base` only (static mode). Object `{base, quantile, min, max}` enables adaptive mode. Zero/nil disables the timeout for this scope (fail-open). | | `timeout.duration.base` | `Duration` | `0` | Static fallback and cold-start addend. When `quantile == 0`, this IS the effective timeout. When `quantile > 0`, added to the quantile value before clamping. `coldStartFallback` prefers `base` over `max`. | | `timeout.duration.quantile` | `float64` | `0` (static mode) | Percentile of per-method response times, range `[0, 1]`. When `> 0`, enables adaptive mode. Requires `base` or `max` to avoid cold-start fail-open. Source: [`common/adaptive_duration.go:L83-109`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L83-L109). | | `timeout.duration.min` | `Duration` | **Auto-floor**: when `quantile > 0` and `min == 0`, auto-set to `base/2` (or `500ms` when `base == 0`) at build time. Source: [`common/timeout_func.go:L31-36`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L31-L36). | Floor after quantile resolution. Prevents feedback-loop collapse. Cold-start: when quantile returns 0, `min` is used as the adaptive component inside `Resolve`. | | `timeout.duration.max` | `Duration` | `0` (uncapped) | Ceiling after quantile resolution. Cold-start fallback of last resort when `base == 0`: `coldStartFallback` returns `max`. If both `base` and `max` are zero, cold start is fail-open. Source: [`common/timeout_func.go:L89-91`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L89-L91). | #### Legacy flat siblings (backward compatible) | Field | Type | Folds into | Precedence | |---|---|---|---| | `timeout.quantile` | `float64` | `duration.quantile` | Object form wins; sibling fills only if `duration.quantile == 0`. Source: [`common/config.go:L1471-1473`](https://github.com/erpc/erpc/blob/main/common/config.go#L1471-L1473). | | `timeout.minDuration` | `Duration` (string or int-as-ms) | `duration.min` | Same precedence rule. Source: [`common/config.go:L1474-1476`](https://github.com/erpc/erpc/blob/main/common/config.go#L1474-L1476). | | `timeout.maxDuration` | `Duration` (string or int-as-ms) | `duration.max` | Same precedence rule. Source: [`common/config.go:L1477-1479`](https://github.com/erpc/erpc/blob/main/common/config.go#L1477-L1479). | Legacy form still accepted: ```yaml # Legacy flat form — still valid, folded into duration.* at parse time timeout: duration: 5s quantile: 0.99 minDuration: 200ms maxDuration: 30s ``` ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Finality-split network timeouts (recommended general shape).** Production uses separate failsafe entries per finality state so realtime/unfinalized data — where block-availability races make latency spiky — gets a wider budget than finalized reads. P99 quantile mode means `eth_blockNumber` self-tunes to a tight budget while `eth_getLogs` breathes. The `min` floor prevents the adaptive budget from collapsing after a run of fast responses: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: # eth_call and eth_getLogs: realtime/unfinalized have block-availability races - matchMethod: "eth_call|eth_getLogs" matchFinality: [realtime, unfinalized] timeout: duration: quantile: 0.99 # base doubles as cold-start fallback — always set it base: 30s # min floor prevents feedback-loop collapse after a run of fast responses min: 20s max: 30s # finalized/unknown: same methods but no block-availability race → same ceiling is fine - matchMethod: "eth_call|eth_getLogs" matchFinality: [finalized, unknown] timeout: duration: quantile: 0.99 base: 30s min: 20s max: 30s # generic catch-all for realtime reads; wider because methods like trace_* are slow - matchMethod: "*" matchFinality: [realtime, unfinalized] timeout: duration: quantile: 0.99 base: 60s min: 40s max: 60s - matchMethod: "*" matchFinality: [finalized, unknown] timeout: duration: quantile: 0.99 base: 60s min: 40s max: 60s ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_call|eth_getLogs", matchFinality: ["realtime", "unfinalized"], timeout: { duration: { quantile: 0.99, base: "30s", min: "20s", max: "30s" } }, }, { matchMethod: "eth_call|eth_getLogs", matchFinality: ["finalized", "unknown"], timeout: { duration: { quantile: 0.99, base: "30s", min: "20s", max: "30s" } }, }, { matchMethod: "*", matchFinality: ["realtime", "unfinalized"], timeout: { duration: { quantile: 0.99, base: "60s", min: "40s", max: "60s" } }, }, { matchMethod: "*", matchFinality: ["finalized", "unknown"], timeout: { duration: { quantile: 0.99, base: "60s", min: "40s", max: "60s" } }, }, ] ``` **2. Per-method upstream timeouts with automatic failover.** Upstream-scope timeouts are the first line of defense: when one provider stalls, a tight per-method ceiling triggers failover to another provider without burning the full network budget. Critically, `hedge` and `retry` are both `null` at the upstream scope — the network layer owns those policies. Methods with variable latency (like `eth_getLogs`, `trace_*`) get wider ceilings so legitimate big queries don't time out prematurely: **Config path:** `projects[].upstreams[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: primary endpoint: https://rpc.example.com failsafe: # fee/nonce reads: extremely tight — these must be fast or skip the upstream - matchMethod: "eth_getTransactionCount|eth_gasPrice|eth_maxPriorityFeePerGas" timeout: duration: quantile: 0.8 base: 500ms min: 100ms max: 500ms hedge: null # upstream scope owns no hedge/retry — network layer does retry: null # heavy data: legitimate eth_getLogs on wide ranges routinely take seconds - matchMethod: "eth_getLogs|eth_getBlockReceipts" timeout: duration: quantile: 0.9 # raised from default — subgraph backfills legitimately take 2-15s base: 15s min: 2s max: 15s hedge: null retry: null # light getters: small responses, tight cap encourages fast hedging on stuck upstreams - matchMethod: "eth_get*" timeout: duration: quantile: 0.9 base: 5s min: 200ms max: 5s hedge: null retry: null # catch-all - matchMethod: "*" timeout: duration: quantile: 0.8 base: 60s min: 500ms max: 60s hedge: null retry: null ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "primary", endpoint: "https://rpc.example.com", failsafe: [ { matchMethod: "eth_getTransactionCount|eth_gasPrice|eth_maxPriorityFeePerGas", timeout: { duration: { quantile: 0.8, base: "500ms", min: "100ms", max: "500ms" } }, hedge: null, retry: null, }, { matchMethod: "eth_getLogs|eth_getBlockReceipts", timeout: { duration: { quantile: 0.9, base: "15s", min: "2s", max: "15s" } }, hedge: null, retry: null, }, { matchMethod: "eth_get*", timeout: { duration: { quantile: 0.9, base: "5s", min: "200ms", max: "5s" } }, hedge: null, retry: null, }, { matchMethod: "*", timeout: { duration: { quantile: 0.8, base: "60s", min: "500ms", max: "60s" } }, hedge: null, retry: null, }, ], }] ``` **3. Transaction hash lookups: tight network timeout, no hedge.** A null `eth_getTransactionReceipt` means the tx isn't mined yet — heavy retries only multiply load, and a hedge on receipts is skipped only early in a slot of a slow chain (a settled head ends the race at the first null; see [hedge](/config/failsafe/hedge.llms.txt)). The network timeout ceiling matches the `upstream.timeout × maxAttempts` budget so the last retry isn't silently cut short: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt" timeout: duration: quantile: 0.99 # 10s ceiling covers upstream timeout (8s) × 2 attempts without overflow base: 10s min: 6s max: 10s retry: maxAttempts: 2 # ~one block of patience: tx is either propagated or not; more retries waste budget delay: 500ms # no hedge key — parallel fan-out on a missing tx multiplies load for no gain ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getTransactionByHash|eth_getTransactionReceipt", timeout: { duration: { quantile: 0.99, base: "10s", min: "6s", max: "10s" } }, retry: { maxAttempts: 2, delay: "500ms" }, // no hedge — parallel fan-out on a missing tx multiplies load for no gain }] ``` **4. Cache connector timeout (adaptive against the connector's own latency).** Cache connectors use `failsafeForGets` / `failsafeForSets`; quantile mode resolves against the connector's own 1-minute sliding latency window, tracked per (method, finality) executor ([`data/cache_executor.go:L14-20`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L14-L20), [`data/cache_executor.go:L244-249`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L244-L249)) — not against network metrics. `max` keeps the hard ceiling: a slow remote cache read is abandoned quickly so eRPC falls through to upstream — a cache read that takes longer than an upstream call is never worth it. When `min` is unset, the same auto-floor as `NewTimeoutFunc` applies at executor construction: `min = base/2` (or `500ms` when `base == 0`) — [`data/cache_executor.go:L75-85`](https://github.com/erpc/erpc/blob/main/data/cache_executor.go#L75-L85): **Config path:** `database.evmJsonRpcCache.connectors[].failsafeForGets[]` **YAML — `erpc.yaml`:** ```yaml connectors: - id: remote-cache driver: grpc failsafeForGets: - matchMethod: "*" timeout: duration: # p99 of this connector's own completed reads (1-minute window) quantile: 0.99 # cold-start fallback is base + min; min unset → auto-floor = base/2 (50ms) base: 100ms # 400ms hard ceiling: a slow cache read is worse than a direct upstream call max: 400ms retry: { maxAttempts: 2, delay: "0" } hedge: { delay: 100ms, maxCount: 1 } ``` **TypeScript — `erpc.ts`:** ```typescript connectors: [{ id: "remote-cache", driver: "grpc", failsafeForGets: [{ matchMethod: "*", timeout: { // p99 of this connector's own completed reads (1-minute window); // cold start = base + min; min unset → auto-floor = base/2 (50ms); // 400ms hard ceiling: a slow cache read is worse than a direct upstream call duration: { quantile: 0.99, base: "100ms", max: "400ms" }, }, retry: { maxAttempts: 2, delay: "0" }, hedge: { delay: "100ms", maxCount: 1 }, }], }] ``` **5. Quantile-only cold-start safe pattern.** A pure `{quantile: 0.95}` with no `base`/`max` is fail-open on cold start. Adding `max` provides the cold-start ceiling without hard-coding a `base` offset; useful when you want the budget to be purely data-driven once the tracker warms up: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" timeout: duration: quantile: 0.95 # max acts as cold-start ceiling; base would be added on top of the quantile value max: 20s ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", timeout: { duration: { quantile: 0.95, max: "20s" }, }, }] ``` ### Request/response behavior - When `server.maxTimeout` fires on a POST request, `TimeoutHandler` writes HTTP 200 with body `{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"http request handling timeout"}}`. Non-POST requests receive HTTP 504. Source: [`erpc/http_timeout.go:L107-116`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L107-L116). - When a failsafe timeout fires, the error propagates as `ErrFailsafeTimeoutExceeded` with a `scope` field (`"network"` or `"upstream"`), which maps to a JSON-RPC `-32603` body at the HTTP layer. - Cancelled in-flight upstream requests receive context cancellation; they do not contribute to response headers or metrics beyond what the timeout counter records. - The `ErrHandlerTimeout` (server) and `ErrDynamicTimeoutExceeded` (failsafe) sentinels are distinct; the network executor never misclassifies them. Source: [`erpc/networks.go:L1427-1432`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1427-L1432). ### Best practices - Set the **network timeout larger than `upstream.timeout × maxAttempts`**. If upstream timeout is 10s and retry maxAttempts is 3, a network timeout below 30s silently drops the last retry. - Use **quantile mode with `max`** rather than a static ceiling for production APIs — static values go stale as provider latency shifts; quantile self-adjusts per method. - **Always set `base` or `max`** when using quantile mode. A spec with only `quantile` and no `base`/`max` is fail-open on cold start — no timeout is applied until the tracker warms up. - **Never set `min: 0` explicitly** in quantile mode. The auto-floor (`min = base/2` or `500ms`) is only applied when `min` is unset; manually setting `min: 0` bypasses the guard and allows the budget to collapse toward zero on a run of fast responses. - Keep `server.maxTimeout` as the last-resort ceiling, but size it generously (150–300s) and size failsafe timeouts tightly — callers get a controlled error from the failsafe layer rather than a raw HTTP 504. - Combine upstream-scope timeouts with network-scope retry so a single stalled provider triggers failover rather than consuming the entire network budget. - Use `erpc_network_timeout_duration_seconds` to observe what budget the adaptive policy is computing; it emits on every quantile request, not only on fires. ### Edge cases & gotchas 1. **`server.maxTimeout` is a hard ceiling.** A failsafe `duration: "200s"` will never run for 200s — the HTTP handler times out at `server.maxTimeout` (default 150s) first. Always set failsafe timeouts shorter than `server.maxTimeout`. Source: [`erpc/http_server.go:L65-67`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L65-L67). 2. **Quantile cold-start fail-open when `base` and `max` are both zero.** `{quantile: 0.95}` with no `base` or `max` → `coldStartFallback` returns nil → no timeout on cold start. Always set `base` or `max` with quantile mode. Source: [`common/timeout_func.go:L85-93`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L85-L93). 3. **Network timeout shorter than `upstream.timeout × maxAttempts`.** Upstream `timeout: 10s` + `retry.maxAttempts: 3` = 30s worst-case budget. A network timeout of 15s silently drops the third attempt. Set network timeout ≥ upstream timeout × retry attempts, or accept the tradeoff explicitly. 4. **Static `base` ignores `min`/`max`.** `duration: { base: "30s", min: "1s", max: "60s" }` with no `quantile` applies exactly `30s` — the clamp is never reached. Source: [`common/adaptive_duration.go:L88-89`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L88-L89). 5. **Quantile cold-start adaptive value is `min`, not `base`.** Inside `Resolve`, when `qt.GetQuantile(q) == 0`, `adaptive = spec.Min` — NOT `base`. Then `v = base + min`. The `base`-first fallback only happens at the `coldStartFallback` level in `NewTimeoutFunc` when `Resolve` returns 0. Source: [`common/adaptive_duration.go:L96-98`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L96-L98). 6. **Retry-exhausted error wins over timeout-on-last-attempt.** When retry exhausts and the last attempt timed out, the top-level error is `ErrFailsafeRetryExceeded`. The timeout counter does not fire; only the retry counter reflects the event. Source: [`erpc/networks_timeout_test.go:L429-493`](https://github.com/erpc/erpc/blob/main/erpc/networks_timeout_test.go#L429-L493). 7. **Upstream-scope timeout bubbles correctly.** When an upstream timeout fires, the error is wrapped as `ErrFailsafeTimeoutExceeded{scope: "upstream"}`. The network executor's `!HasErrorCode(execErr, ErrCodeFailsafeTimeoutExceeded)` guard sees this code and skips network-scope classification and counter increment. One event, one counter. Source: [`erpc/networks_timeout_test.go:L495-538`](https://github.com/erpc/erpc/blob/main/erpc/networks_timeout_test.go#L495-L538). 8. **POST timeout response is always HTTP 200.** The JSON-RPC spec requires transport-layer 200 for method errors. Non-POST gets HTTP 504. Source: [`erpc/http_timeout.go:L107-116`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L107-L116). 9. **Legacy `quantile`-only flat form is fail-open on cold start.** A config with only `quantile: 0.7` and no `duration` has `base == 0` and `max == 0` → `coldStartFallback` returns nil. Add `maxDuration` to avoid this. Source: [`common/config.go:L1468-1473`](https://github.com/erpc/erpc/blob/main/common/config.go#L1468-L1473). 10. **Legacy flat siblings silently drop on field conflict.** If `duration: {quantile: 0.95}` is set and `quantile: 0.50` is also provided as a flat sibling, the result is `quantile = 0.95`. No error or warning is emitted. Source: [`common/adaptive_duration_compat_test.go:L75-88`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration_compat_test.go#L75-L88). 11. **`erpc_network_timeout_duration_seconds` emits on every quantile request, not only timeouts.** The histogram reflects what duration was computed, not whether the request actually timed out. Source: [`common/timeout_func.go:L73-80`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L73-L80). 12. **Auto-floor is applied at build time, not config-load time.** `NewTimeoutFunc` modifies a LOCAL copy of the spec. The original `TimeoutPolicyConfig` is not mutated. Manually setting `min: 0` bypasses the auto-floor because `== 0` check fails. Source: [`common/timeout_func.go:L27-36`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L27-L36). 13. **Network-only timeout does not fire the upstream-scope counter.** When only the network scope has a timeout policy and the upstream scope has none, the context cancellation propagates into the upstream's attempt. Because `failsafeExecutor.timeout == nil` at the upstream level, the upstream does NOT increment `erpc_network_timeout_fired_total` and does NOT wrap the error as `ErrFailsafeTimeoutExceeded`. The network scope handles all classification. Source: [`erpc/networks_timeout_test.go:L540-586`](https://github.com/erpc/erpc/blob/main/erpc/networks_timeout_test.go#L540-L586). 14. **`applyLegacySiblings` early-exit: all-zero flat siblings are free.** When `quantile == 0` and `minDuration == 0` and `maxDuration == 0`, `applyLegacySiblings` returns immediately without allocating a `Duration` object. Configs that use only `duration: 5s` (no flat siblings) pay no allocation cost. Source: [`common/config.go:L1465-1467`](https://github.com/erpc/erpc/blob/main/common/config.go#L1465-L1467). 15. **Legacy `quantile`-only flat form (no `duration:` key at all) allocates `Duration` from nil.** A block containing only `quantile: 0.7` with no `duration:` field is valid: `applyLegacySiblings` allocates `c.Duration = &AdaptiveDuration{}` and sets only `Quantile = 0.7`, leaving `Base`, `Min`, and `Max` at zero. At `NewTimeoutFunc` build time `quantile > 0` and `base == 0` — the auto-floor sets `min = 500ms`, but on cold start `coldStartFallback` returns `max` (zero) → nil (fail-open). Add `maxDuration` to avoid cold-start fail-open when using the legacy flat form. Source: [`common/config.go:L1468-1473`](https://github.com/erpc/erpc/blob/main/common/config.go#L1468-L1473). 16. **`context.WithTimeoutCause` cause discrimination.** `errors.Is(ctx.Err(), context.DeadlineExceeded)` is true for both the HTTP-server timeout and a failsafe timeout, but `context.Cause(ctx)` returns different sentinels: `ErrHandlerTimeout` for the server level and `ErrDynamicTimeoutExceeded` for failsafe. The network executor uses this distinction to avoid misclassifying an HTTP-server deadline as `ErrFailsafeTimeoutExceeded`. Source: [`erpc/networks.go:L1427-1432`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1427-L1432). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_timeout_fired_total` | counter | `project`, `network`, `category`, `finality`, `scope` | Timeout policy killed a request. `scope=network` or `scope=upstream`. Suppressed when `ErrFailsafeRetryExceeded` wins; suppressed when a lower scope already fired. Network-scope source: [`erpc/networks.go:L1440`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1440); upstream-scope source: `upstream/upstream.go:L845`; metric declaration: `telemetry/metrics.go:L437-L441`. | | `erpc_network_timeout_duration_seconds` | histogram | `project`, `network`, `category`, `finality` | Computed per request in quantile mode only — reflects the budget computed, not whether it fired. Buckets: `[0.05, 0.1, 0.3, 0.5, 1, 3, 5, 10, 30]`. Source: [`common/timeout_func.go:L73-80`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L73-L80); metric declaration: `telemetry/metrics.go:L820-L824`. | ```promql # Rate of timeout fires by scope rate(erpc_network_timeout_fired_total[5m]) # P99 of dynamically computed timeout budget per method histogram_quantile(0.99, sum by (le, category) ( rate(erpc_network_timeout_duration_seconds_bucket[5m]) ) ) ``` ### Source code entry points - [`erpc/http_timeout.go`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go) — `TimeoutHandler`, `timeoutWriter`; HTTP-server-level timeout and `ErrHandlerTimeout` sentinel - [`erpc/http_server.go:L65-L67`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L65-L67) — `maxTimeout` retrieval and `TimeoutHandler` instantiation - [`common/timeout_func.go:L23-L94`](https://github.com/erpc/erpc/blob/main/common/timeout_func.go#L23-L94) — `NewTimeoutFunc`; auto-floor; `coldStartFallback`; quantile resolution; metric observation - [`common/adaptive_duration.go:L83-L109`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration.go#L83-L109) — `AdaptiveDuration.Resolve`; full resolution algorithm - [`erpc/network_executor.go:L164-L171`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L164-L171) — network-scope `context.WithTimeoutCause` applied to `networkExecutor.Run` - [`erpc/networks.go:L1424-L1451`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1424-L1451) — timeout error classification; `MetricNetworkTimeoutFiredTotal` with all four guards - [`common/defaults.go:L134-L157`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L134-L157) — system-level defaults (network `120s`, upstream `60s`) - [`common/config.go:L1398-L1480`](https://github.com/erpc/erpc/blob/main/common/config.go#L1398-L1480) — `TimeoutPolicyConfig` struct; YAML/JSON unmarshal; `applyLegacySiblings` - [`common/errors.go:L1588-L1603`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1588-L1603) — `NewErrFailsafeTimeoutExceeded`; `ErrCodeFailsafeTimeoutExceeded` - [`common/errors.go:L1981-L1984`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1981-L1984) — `ErrDynamicTimeoutExceeded` sentinel declaration - [`erpc/networks_timeout_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_timeout_test.go) — behavior-locking tests: lifecycle scoping, cold-start, scope attribution, double-count regression - [`common/network.go:L51-L60`](https://github.com/erpc/erpc/blob/main/common/network.go#L51-L60) — `QuantileTracker` and `TrackedMetrics` interfaces - [`common/adaptive_duration_test.go`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration_test.go) — unit tests locking resolution semantics: static mode, quantile mode, clamp, nil spec, cold-start - [`common/adaptive_duration_compat_test.go`](https://github.com/erpc/erpc/blob/main/common/adaptive_duration_compat_test.go) — backward-compat tests for legacy flat-sibling folding and precedence rules - [`erpc/network_executor.go:L86-L88`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L86-L88) — `NewNetworkExecutor` wires `NewTimeoutFunc`; `HasTimeout` method - [`telemetry/metrics.go:L437-L441`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L437-L441) — `MetricNetworkTimeoutFiredTotal` declaration - [`telemetry/metrics.go:L820-L824`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L820-L824) — `MetricNetworkTimeoutDurationSeconds` declaration ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — runs inside the network timeout; budget shared across all attempts. - [Hedge](/config/failsafe/hedge.llms.txt) — all hedge legs share the same network-scope deadline. - [Selection policies](/config/projects/selection-policies.llms.txt) — decides which upstream each failover attempt gets. - [Rate limiters](/config/rate-limiters.llms.txt) — pair with upstream timeouts to cap cost on expensive vendors. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome upstream-scope timeouts serve. --- --- # Matcher syntax > Source: https://docs.erpc.cloud/config/matcher > One pattern engine everywhere — globs, boolean logic, and hex ranges that work identically across cache policies, failsafe rules, rate limits, method filters, and routing directives. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Matcher syntax Write one pattern, use it everywhere. eRPC's single `WildcardMatch` engine handles globs (`eth_*`), boolean composition (`eth_* & !eth_call`), and hex numeric ranges (`>=0x100 & <=0x200`) identically across cache policies, failsafe rules, rate limits, method allow/ignore lists, CORS, aliasing, upstream selectors, and routing. There is nothing new to learn when you reach a new config section. ## Quick taste Illustrative — any method, any finality; exclude debug_ from rate limits: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } failsafe: # glob + boolean: all eth_ methods except eth_call - matchMethod: "eth_* & !eth_call" retry: maxAttempts: 3 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, failsafe: [{ // glob + boolean: all eth_ methods except eth_call matchMethod: "eth_* & !eth_call", retry: { maxAttempts: 3 }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure failsafe rules for specific methods and finalities** ```text I want to tune my eRPC failsafe config so different retry/hedge policies apply to different methods and finality states — e.g. aggressive retry for finalized eth_getLogs, light retry for realtime, and no hedge on tx-hash lookups. Work with my existing eRPC config. Read the matcher syntax reference first: https://docs.erpc.cloud/config/matcher.llms.txt ``` **Prompt Example #2: build an upstream method whitelist** ```text One of my upstreams is an archive node that should only handle eth_getLogs, eth_getBlockByNumber, eth_getBlockByHash, eth_getTransactionByHash, and eth_getTransactionReceipt — all other methods should fall to other upstreams. Configure ignoreMethods and allowMethods correctly. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/matcher.llms.txt ``` **Prompt Example #3: set up cache policies with hex-range and finality scoping** ```text I want eRPC to cache eth_getLogs and block-lookup methods only for finalized and unfinalized requests, using hex block-range patterns in params so only concrete block numbers are cached (not "latest"). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/matcher.llms.txt ``` **Prompt Example #4: debug why my matchMethod or matchFinality rule is not matching** ```text My eRPC failsafe rule with matchMethod "eth_get*" and matchFinality [finalized] does not seem to be picked up for some requests. Walk me through how network-scope vs upstream-scope failsafe selection works (4-tier vs config-order), and check my eRPC config for ordering mistakes or wrong finality values. Reference: https://docs.erpc.cloud/config/matcher.llms.txt ``` **Prompt Example #5: add per-method rate-limit rules without accidentally stacking them** ```text I want to add a rate-limit budget rule that caps debug_* and trace_* at 30 RPS and a separate rule that caps eth_getBlockReceipts at 100 RPS, but I don't want a wildcard "*" rule to stack on top and double-count. Explain how GetRulesByMethod works and write the correct rules for my eRPC config. Reference: https://docs.erpc.cloud/config/matcher.llms.txt ``` --- ### Matcher syntax — full agent reference ### How it works **Core engine (`WildcardMatch`).** Every call tokenizes the pattern string into operators (`|`, `&`, `!`, `(`, `)`) and atom tokens, then builds a recursive function AST via Pratt-style recursive-descent parsing (`parseOr → parseAnd → parseUnary → parsePrimary`). The resulting `func(string) bool` closure is invoked immediately against the test value. There is **no compiled- pattern cache** — each call re-tokenizes and re-parses. This is lightweight for short patterns but re-tokenization cost is paid on every forwarded request for failsafe executor selection. **Glob atoms.** Plain atoms (no operator prefix) are dispatched to the `go-wildcard` library: `*` matches any number of characters, `?` matches exactly one. The `` literal is handled specially before the glob library — it matches only the empty string. **Boolean composition.** Operator precedence, highest to lowest: NOT (`!`) > AND (`&`) > OR (`|`). Parentheses override. Both `&` and `|` are left-associative. Spaces are atom separators — `"a | b"` and `"a|b"` are identical. The characters `|`, `&`, `!`, `(`, `)` **cannot appear as literals** in a pattern — there is no escape mechanism. **Hex numeric comparisons.** When the *runtime value* starts with `0x`, the engine tries numeric comparison operators (`>=`, `<=`, `>`, `<`, `=`) as pattern prefixes. Both sides are parsed as hex integers. If the value does **not** start with `0x` (e.g., a decimal block number or a named tag like `"latest"`), numeric operators fall through to glob matching and will not compare as expected. Use `0x*` to match hex-format values, and combine with named tags using `|` for full coverage. **`MatchesSelector` and upstream tag awareness.** The `use-upstream` directive and served-tip [lane](/reference/lanes.llms.txt) grouping use `MatchesSelector` rather than plain `WildcardMatch`. The function first tests the pattern against the upstream's `id`. If that matches, it returns `true` immediately. If the pattern contains **no `!` anywhere** (purely-positive), it also iterates the upstream's `tags []string` and returns `true` on any tag match. Any `!` anywhere in the pattern — even `"!other-upstream"` — disables tag matching entirely. This is intentional: a tag match must never rescue an upstream the operator meant to exclude. **`matchMethodPattern` helper.** Inside `SelectExecutor`, method matching uses a helper that treats both empty string and `"*"` as match-anything, and tries exact equality before calling `WildcardMatch` to reduce overhead on common exact-match patterns. Source: [`common/match.go:L83-92`](https://github.com/erpc/erpc/blob/main/common/match.go#L83-L92) **`SelectExecutor` — 4-tier priority for failsafe dispatch.** Given executors with `(matchMethod, matchFinality)` fields and the request's `(method, finality)`, `SelectExecutor` selects the first matching executor across four tiers in priority order (single pass): 1. **Exact** — specific method AND specific finality 2. **Method-only** — specific method, any finality (`matchFinality: []`) 3. **Finality-only** — `matchMethod: "*"`, specific finality 4. **Catch-all** — `matchMethod: "*"`, `matchFinality: []` **Important:** upstream-level and network-level failsafe selection use different algorithms. Upstreams use the 4-tier priority algorithm above. Networks use a simpler **first-match-in- config-order scan** — if an any-method entry appears before a specific-method entry in config, the any-method entry wins. Place most-specific entries *before* catch-all entries in network-scope failsafe. **Cache policy param matching.** `matchParams` is positional: index `i` in the config pattern matches `params[i]` in the request. Matching is recursive: map patterns require all keys to match, array patterns require equal length then per-element matching, string patterns use `WildcardMatch`, and other types are converted to strings via `paramToString` (JSON `float64` numbers become their decimal string form: `1234.0 → "1234"`). **Auth method filter semantics.** `ignoreMethods` is checked first (any match → method blocked), then `allowMethods` overrides (any match → force-allowed). Same semantics at upstream, project, and auth-strategy scopes. **Rate-limit rules.** `GetRulesByMethod` returns **all** rules whose method pattern matches — not just the first. Multiple rules can simultaneously consume token-bucket permits for a single request. ### Config schema The matcher engine has no dedicated config block. The table below covers every config field matched via `WildcardMatch`, `MatchesSelector`, `SelectExecutor`, or `MatchFinalities`, grouped by subsystem. **Failsafe** — `*.failsafe[]` (networks, upstreamDefaults, upstreams, networkDefaults, and cache connector `failsafeForGets[]`/`failsafeForSets[]`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `matchMethod` | string | `"*"` (set by `SetDefaults` when empty) | `WildcardMatch` against the request's JSON-RPC method. Empty is rejected by `Validate()`. During defaults inheritance, a default's `matchMethod` is glob-matched against the entry's `matchMethod` to select which default to apply. Source: [`common/config.go:L1280`](https://github.com/erpc/erpc/blob/main/common/config.go#L1280), [`common/defaults.go:L2131-2137`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2131-L2137) | | `matchFinality` | []DataFinalityState | `[]` (empty = any finality) | Exact set-membership check at dispatch time: `slices.Contains(list, finality)`. Empty list = catch-all finality tier. No wildcard inside the list — each element must be an exact finality name. Source: [`common/config.go:L1281`](https://github.com/erpc/erpc/blob/main/common/config.go#L1281), [`common/match.go:L38-41`](https://github.com/erpc/erpc/blob/main/common/match.go#L38-L41) | | `matchCommitment` | []string | `[]` (empty = any commitment) | Network scope only: first-match filter, AND-ed with method/finality/kind. Upstream-scope entries that set it fail startup. Values `none`\|`processed`\|`confirmed`\|`finalized`, OR-ed, exact match (`confirmed` does not match `processed`). Compares the commitment erpc pins on the wire: the caller's value, else the `svm.commitment` default injection writes, else `none`. Non-SVM requests and SVM write methods (`sendTransaction`, `simulateTransaction`, `requestAirdrop`) are `none`. Source: [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go), [`architecture/svm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/hooks.go), [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) | **Cache policies** — `database.evmJsonRpcCache.policies[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `network` | string | `"*"` (set by `SetDefaults`) | `WildcardMatch` against the network ID (e.g., `"evm:1"`, `"evm:*"`). Source: [`common/config.go:L320`](https://github.com/erpc/erpc/blob/main/common/config.go#L320), [`data/cache_policy.go:L67`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L67) | | `method` | string | `"*"` (set by `SetDefaults`) | `WildcardMatch` against the JSON-RPC method. Source: [`common/config.go:L321`](https://github.com/erpc/erpc/blob/main/common/config.go#L321), [`data/cache_policy.go:L75`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L75) | | `params` | []interface{} | `nil` (nil = match any params) | Positional param matching; strings use `WildcardMatch`. Maps/arrays matched recursively. Non-string types converted via `paramToString`. Source: [`common/config.go:L322`](https://github.com/erpc/erpc/blob/main/common/config.go#L322), [`data/cache_policy.go:L166-232`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L166-L232) | | `finality` | DataFinalityState | `finalized` (zero value = 0) | For `MatchesForSet`: exact equality. For `MatchesForGet`: `finalized` requests also match `unfinalized` policies; `unknown` finality matches any policy. **Footgun:** omitting `finality` yields a finalized-only policy silently. Source: [`common/config.go:L323`](https://github.com/erpc/erpc/blob/main/common/config.go#L323), [`data/cache_policy.go:L99-150`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L99-L150) | **Rate-limit rules** — `rateLimiters.budgets[].rules[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `method` | string | required | `WildcardMatch` against request method. **ALL** matching rules are returned (not just first) — each independently consumes a token-bucket permit. Source: [`common/config.go:L1811`](https://github.com/erpc/erpc/blob/main/common/config.go#L1811), [`upstream/ratelimiter_budget.go:L63-78`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L63-L78) | **Upstream method filters** — `upstreams[]`, `projects[]`, `auth.strategies[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `ignoreMethods` | []string | `nil` | `WildcardMatch` per entry; any match → method reported unsupported. Applied before `allowMethods`. Source: [`common/config.go:L731`](https://github.com/erpc/erpc/blob/main/common/config.go#L731), [`upstream/upstream.go:L1375-1385`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1375-L1385) | | `allowMethods` | []string | `nil` | `WildcardMatch` per entry; any match → overrides an `ignoreMethods` hit. To allow only `eth_getLogs`: set `ignoreMethods: ["*"]`, `allowMethods: ["eth_getLogs"]`. Source: [`common/config.go:L732`](https://github.com/erpc/erpc/blob/main/common/config.go#L732), [`upstream/upstream.go:L1388-1399`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1388-L1399) | **CORS, aliasing, headers, selectors** | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `projects[].cors.allowedOrigins[]` | []string | `["*"]` | `WildcardMatch` against `Origin` header; first match allows. Source: [`erpc/http_server.go:L1024`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1024) | | `server.aliasing.rules[].matchDomain` | string | — | `WildcardMatch` against `Host` header (port stripped); first rule match wins. Source: [`common/config.go:L258`](https://github.com/erpc/erpc/blob/main/common/config.go#L258), [`erpc/http_server.go:L244-257`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L244-L257) | | `projects[].forwardHeaders[]` | []string | `nil` | `WildcardMatch` against incoming header names; matching headers forwarded to upstreams. Source: [`common/config.go:L519`](https://github.com/erpc/erpc/blob/main/common/config.go#L519), [`erpc/http_server.go:L480-493`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L480-L493) | | `upstreams[].id` | string | — | Primary identity matched by `MatchesSelector` against `use-upstream` directive value. Source: [`common/matcher.go:L106-112`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L106-L112) | | `upstreams[].tags[]` | []string | `nil` | Secondary match by `MatchesSelector` if id didn't match and pattern has no `!`. Source: [`common/matcher.go:L73-100`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L73-L100) | **Score multipliers** — `upstreams[].routing.scoreMultipliers[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `network` | string | `""` (empty = any) | `WildcardMatch` against network ID. Source: [`common/config.go:L798`](https://github.com/erpc/erpc/blob/main/common/config.go#L798) | | `method` | string | `""` (empty = any) | `WildcardMatch` against method. Source: [`common/config.go:L799`](https://github.com/erpc/erpc/blob/main/common/config.go#L799) | | `finality` | []DataFinalityState | `[]` (any) | `slices.Contains` check. Source: [`common/config.go:L800`](https://github.com/erpc/erpc/blob/main/common/config.go#L800) | **Tracing force-trace matchers** — `tracing.forceTraceMatchers[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `network` | string | `""` (absent = any) | `WildcardMatch` against network ID. Both `network` AND `method` must match. Source: [`common/config.go:L241`](https://github.com/erpc/erpc/blob/main/common/config.go#L241), [`common/tracing_core.go:L306-329`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L306-L329) | | `method` | string | `""` (absent = any) | `WildcardMatch` against method. Source: [`common/config.go:L245`](https://github.com/erpc/erpc/blob/main/common/config.go#L245) | **Served-tip guaranteed methods** — `networks[].evm.servedTip.guaranteedMethods[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[].evm.servedTip.guaranteedMethods[]` | []string | — | Each element validated by `ValidatePattern` at config load (as are `servedTip.guaranteedFor[]` and `safeBlockSource`). At runtime, each pattern selects the upstreams whose `ShouldHandleMethod` accepts it ([guarantee subsets](/reference/evm/block-tracking.llms.txt#guarantee-subsets)). Source: [`common/validation.go:L1669-1685`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1669-L1685) | **Provider network overrides** — `providers[].overrides` (map keys) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `providers[].overrides` (map key) | string | — | `WildcardMatch` pattern against network ID. First matching key wins. Source: [`thirdparty/provider.go:L80-L91`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L80-L91) | **Consensus quota tags** — `consensus/quota.go` Tag membership for quota matching uses `WildcardMatch(pattern, t)` against each tag string in the upstream config's `Tags` slice. Source: [`consensus/quota.go:L96`](https://github.com/erpc/erpc/blob/main/consensus/quota.go#L96) **Static responses** — `networks[].staticResponses[]` (**NOT** WildcardMatch) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `method` | string | required | **Exact string equality only** — no glob, no boolean operators. `"eth_getBlock*"` will NOT match `eth_getBlockByNumber`. Source: [`common/static_response.go:L16`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L16) | | `params` | []interface{} | `nil` (nil = match any params) | Deep equality with numeric-type tolerance (YAML int vs JSON float64). NOT `WildcardMatch`. Source: [`common/static_response.go:L19-39`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L19-L39) | **`DataFinalityState` values** | YAML string | Go constant | iota | Meaning | |---|---|---|---| | `"finalized"` | `DataFinalityStateFinalized` | 0 | Block ≤ upstream finalized block. Zero value — omitting `finality` in config gives this. | | `"unfinalized"` | `DataFinalityStateUnfinalized` | 1 | Block known and > upstream finalized block. | | `"realtime"` | `DataFinalityStateRealtime` | 2 | Fresh, block-unbound data (e.g., `eth_gasPrice`). | | `"unknown"` | `DataFinalityStateUnknown` | 3 | Block number cannot be determined (trace-by-hash, etc.). | YAML/JSON accepts string names or their numeric iota indices (`"0"` = `finalized`, `"1"` = `unfinalized`, `"2"` = `realtime`, `"3"` = `unknown`). Source: [`common/data.go:L8-76`](https://github.com/erpc/erpc/blob/main/common/data.go#L8-L76) ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Method whitelist on a narrow upstream: block everything, allow only what it indexes.** Production indexing upstreams (e.g. archive nodes, specialized caches) only serve a small set of methods — blocking everything else avoids wasting a request slot and lets the router immediately fall to a full-service upstream. This is the canonical `ignoreMethods + allowMethods` pattern used on every specialized upstream in the fleet: **Config path:** `upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: archive-node # Block all methods on this upstream by default ignoreMethods: - "*" # Then re-allow only the methods this upstream actually serves — anything # else immediately falls to the next upstream without a wasted RTT allowMethods: - "eth_getLogs" - "eth_getBlockByNumber" - "eth_getBlockByHash" - "eth_getBlockReceipts" - "eth_getTransactionByHash" - "eth_getTransactionReceipt" ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "archive-node", // Block all methods on this upstream by default ignoreMethods: ["*"], // Then re-allow only the methods this upstream actually serves — anything // else immediately falls to the next upstream without a wasted RTT allowMethods: [ "eth_getLogs", "eth_getBlockByNumber", "eth_getBlockByHash", "eth_getBlockReceipts", "eth_getTransactionByHash", "eth_getTransactionReceipt", ], }] ``` **2. Finality-scoped network failsafe: different retry+hedge per finality state.** In production, `realtime` and `unfinalized` requests are subject to block-availability races — a short non-zero `delay` gives the state-propagation poller time to catch up before retrying. Finalized requests have no race, so `delay: 0` is correct there. At upstream scope the 4-tier priority resolves conflicts automatically; at network scope, most-specific entries MUST come first in config order: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: # Specific method + specific finality wins over all catch-alls (at upstream scope, # this is tier 1 priority; at network scope, place this BEFORE the catch-all) - matchMethod: "eth_call|eth_getLogs" matchFinality: [realtime, unfinalized] retry: maxAttempts: 4 # MUST NOT be 0: a short delay lets block-state propagation catch up before # retrying a "block not available yet" error across another upstream delay: 50ms hedge: delay: quantile: 0.95 min: 500ms max: 10s maxCount: 1 # Same methods, finalized — no block-availability race, so delay: 0 is correct - matchMethod: "eth_call|eth_getLogs" matchFinality: [finalized, unknown] retry: maxAttempts: 4 delay: 0 # Catch-all for everything else — realtime/unfinalized needs the delay too - matchMethod: "*" matchFinality: [realtime, unfinalized] retry: maxAttempts: 6 delay: 50ms - matchMethod: "*" matchFinality: [finalized, unknown] retry: maxAttempts: 6 delay: 0 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [ { matchMethod: "eth_call|eth_getLogs", matchFinality: ["realtime", "unfinalized"], retry: { maxAttempts: 4, // MUST NOT be 0: block-state propagation needs a moment to catch up delay: "50ms", }, hedge: { delay: { quantile: 0.95, min: "500ms", max: "10s" }, maxCount: 1 }, }, { matchMethod: "eth_call|eth_getLogs", matchFinality: ["finalized", "unknown"], retry: { maxAttempts: 4, delay: 0 }, }, { matchMethod: "*", matchFinality: ["realtime", "unfinalized"], retry: { maxAttempts: 6, delay: "50ms" }, }, { matchMethod: "*", matchFinality: ["finalized", "unknown"], retry: { maxAttempts: 6, delay: 0 }, }, ] ``` **3. Per-method upstream timeouts using glob priority.** Production upstream failsafe sets tight timeouts per method tier — heavy methods like `eth_getLogs` need a generous ceiling; light point-reads need a tight one to encourage fast hedging on stuck upstreams. Glob patterns (`eth_get*`) serve as a catch-all tier, with more-specific exact entries placed before them. At upstream scope, 4-tier priority handles the ordering automatically, so explicit placement is not required — but it is still good style: **Config path:** `upstreamDefaults.failsafe[]` **YAML — `erpc.yaml`:** ```yaml upstreamDefaults: failsafe: # Exact method entries are tier 2 (method-only) — win over the glob catch-all tier - matchMethod: "eth_getLogs|eth_getBlockReceipts" timeout: # Variable latency tied to range/density — routinely seconds on big queries duration: 15s - matchMethod: "eth_getTransactionReceipt" timeout: duration: 8s - matchMethod: "eth_getBlockByNumber" timeout: # min raised: archive lookups on fast chains (Sei, Monad) can take 350–500ms duration: 3s - matchMethod: "trace_*|debug_*|arbtrace_*" timeout: # Trace methods can be slow — 30s gives them room without blocking others duration: 30s # Glob catch-all for remaining eth_get* light getters — tier 2, wins over "*" - matchMethod: "eth_get*" timeout: duration: 5s # Final catch-all — tier 4, lowest priority - matchMethod: "*" timeout: duration: 60s ``` **TypeScript — `erpc.ts`:** ```typescript upstreamDefaults: { failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", // Variable latency tied to range/density — routinely seconds on big queries timeout: { duration: "15s" }, }, { matchMethod: "eth_getTransactionReceipt", timeout: { duration: "8s" } }, { matchMethod: "eth_getBlockByNumber", // min raised: archive lookups on fast chains can take 350–500ms timeout: { duration: "3s" }, }, { matchMethod: "trace_*|debug_*|arbtrace_*", // Trace methods can be slow — 30s gives them room without blocking others timeout: { duration: "30s" }, }, // Glob catch-all for remaining eth_get* light getters { matchMethod: "eth_get*", timeout: { duration: "5s" } }, // Final catch-all — lowest priority { matchMethod: "*", timeout: { duration: "60s" } }, ], } ``` **4. Cache policy with explicit method allowlist and all-finality coverage.** In production, cache policies use a pipe-joined method pattern (`|`) rather than a broad glob because `eth_get*` would flood every connector with requests for methods nothing serves (eth_getBalance, eth_getCode, eth_getStorageAt, …), paying a connector RTT for a guaranteed miss. Three finality tiers cover all concrete-block requests; `realtime` finality is intentionally excluded so head-tracking queries always hit fresh upstreams: ```yaml database: evmJsonRpcCache: policies: # Using | instead of eth_get* avoids cache misses on balance/code/storage methods - network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unfinalized connector: my-cache - network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: unknown connector: my-cache - network: "evm:1" method: "eth_getBlockByNumber|eth_getBlockByHash|eth_getBlockReceipts|eth_getLogs|eth_getTransactionByHash|eth_getTransactionReceipt" finality: finalized connector: my-cache # realtime deliberately omitted — eth_blockNumber / eth_getBlockByNumber("latest") # must always hit upstreams so clients see the current chain head ``` **5. Per-method rate-limit rules: protect heavy methods without stacking a wildcard.** Heavy-method traffic (`eth_getBlockReceipts`, `trace_*`) can exhaust proxy concurrency when a single user sends high-error-rate bursts, holding a connection per failed attempt. A method-specific rule caps only that traffic; a separate wildcard rule caps global volume. Note that ALL matching rules fire simultaneously — if you add a `"*"` rule AND a specific rule, a heavy-method request consumes from both buckets: **Config path:** `rateLimiters.budgets[]` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: - id: chain-admission rules: # Heavy receipt methods empirically drive proxy-connection stack-ups — cap tightly. # Healthy peak is ~5 RPS total; 100 RPS gives 20× headroom for legitimate spikes - method: "eth_getBlockReceipts|eth_getTransactionReceipt" maxCount: 100 period: 1s # Trace methods have low typical volume; 30 RPS matches observed traffic - method: "debug_*|trace_*|arbtrace_*" maxCount: 30 period: 1s # Global wildcard intentionally omitted here — these two rules are # independent; a request matching both rules debits both buckets ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [{ id: "chain-admission", rules: [ // Heavy receipt methods empirically drive proxy-connection stack-ups — cap tightly. // Healthy peak is ~5 RPS total; 100 RPS gives 20× headroom for legitimate spikes { method: "eth_getBlockReceipts|eth_getTransactionReceipt", maxCount: 100, period: "1s" }, // Trace methods have low typical volume; 30 RPS matches observed traffic { method: "debug_*|trace_*|arbtrace_*", maxCount: 30, period: "1s" }, // Global wildcard intentionally omitted here — these two rules are // independent; a request matching both rules debits both buckets ], }], } ``` ### Request/response behavior - The `use-upstream` directive is set via the `X-ERPC-Use-Upstream` request header or query param. The value is a `MatchesSelector` pattern — id first, then tags if no `!` in pattern. - `ignoreMethods` and `allowMethods` at project or upstream scope cause eRPC to return `ErrUpstreamMethodIgnored` for blocked methods — surfaced to the client as an upstream unsupported error. - Rate-limit rules whose `method` matches fire simultaneously: a request denied by two matching rules gets a rate-limit error even if only one rule was intended as the effective gate. - A malformed pattern in most config fields silently skips matches at runtime (caller `continue`-on-error pattern) — no error is returned to the client; the config field is simply treated as non-matching. ### Best practices - Prefer **exact method names or simple globs** (`"eth_*"`, `"*"`) on hot paths like failsafe `matchMethod` — complex boolean expressions re-parse on every request with no caching. - At **network scope, order failsafe entries from most-specific to least-specific manually** — unlike upstream scope, there is no 4-tier priority; the first matching entry wins. - For rate-limit budgets, remember that **all matching rules fire simultaneously** — a global `"*"` rule and a per-method rule both debit their buckets. Size them with overlap in mind. - Use **`ignoreMethods: ["*"]` + `allowMethods: [...]`** to build explicit whitelists — it is cleaner and safer than long lists of specific ignore patterns. - For hex numeric comparisons in cache policy params, always **also cover named tags** with `|`: `"(latest | safe | finalized) | >=0x1000000"` — a value like `"latest"` has no `0x` prefix and falls through to glob matching, so numeric-only patterns miss it. - Avoid setting `!` in `use-upstream` selector patterns unless you specifically want to suppress tag matching — any `!` anywhere in the pattern disables tag fallback entirely. - **Validate patterns at startup** where possible: `ValidatePattern` is only automatically called for `evm.servedTip.guaranteedMethods`, `evm.servedTip.guaranteedFor` and `evm.safeBlockSource`; other fields accept invalid patterns silently and fail at runtime. ### Edge cases & gotchas 1. **No escaping for meta-characters.** `|`, `&`, `!`, `(`, `)` cannot appear as literal values in a pattern. A method name like `net_!custom` is untestable via `WildcardMatch`. Source: [`common/matcher.go:L226-258`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L226-L258) 2. **Spaces are atom separators.** `"eth_getLogs "` (trailing space) tokenizes as `["eth_getLogs"]`. A pattern intended to match a literal space will silently split into two tokens. Source: [`common/matcher.go:L229-260`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L229-L260) 3. **Numeric operators require `0x` prefix on the runtime value.** `>100` against value `"200"` does NOT compare numerically — it falls through to glob. Use hex-prefixed values (`"0x64"` = 100) to enable numeric comparison. Source: [`common/matcher.go:L373-391`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L373-L391) 4. **Hex overflow at `0x7FFFFFFFFFFFFFFF`.** `parseNumber` uses `strconv.ParseInt(s, 16, 64)` — values above signed 64-bit max parse silently as errors and `compareNumbers` returns `false`. Source: [`common/matcher.go:L399-438`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L399-L438) 5. **`MatchesSelector` negation guard is coarse.** Any `!` anywhere in the pattern — even `"!other-upstream"` — disables tag matching entirely. This is by design: a tag match must not rescue an excluded upstream. Source: [`common/matcher.go:L87-89`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L87-L89) 6. **Network-level vs upstream-level failsafe selection differ.** Upstream uses 4-tier priority; network uses config-order first-match. Same field names, different semantics. Source: [`upstream/upstream.go:L372-408`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L372-L408), [`erpc/networks.go:L910-928`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L910-L928) 7. **`matchFinality: []` is catch-all at dispatch, but `MatchFinalities` empty-means-any is only for defaults merging.** Two different functions handle the same field in different contexts. Source: [`common/defaults.go:L17-34`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L17-L34), [`common/match.go:L38-41`](https://github.com/erpc/erpc/blob/main/common/match.go#L38-L41) 8. **Static response `method` is exact equality, not wildcard.** Unlike every other string matcher, `FindStaticResponseMatch` uses byte equality. A glob pattern in `staticResponses[].method` is silently treated as a literal string. Source: [`common/static_response.go:L16`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L16) 9. **`CachePolicyConfig.finality` zero-value is `finalized`.** Omitting `finality` in a cache policy gives a finalized-only policy without any warning. Source: [`common/data.go:L15`](https://github.com/erpc/erpc/blob/main/common/data.go#L15) 10. **Multiple rate-limit rules fire simultaneously.** All rules whose `method` pattern matches are returned and each independently debits a token bucket. A single request may be throttled by a `"*"` rule and a specific-method rule at the same time. Source: [`upstream/ratelimiter_budget.go:L63-78`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L63-L78) 11. **`ValidatePattern` is called only for `evm.servedTip.guaranteedMethods`, `evm.servedTip.guaranteedFor` and `evm.safeBlockSource` at startup.** Other pattern fields (cache policy method, failsafe matchMethod, etc.) are not validated at config load — an invalid pattern silently skips matches at runtime. Source: [`common/validation.go:L1676-1691`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1676-L1691) 12. **`WildcardMatch` concurrent calls are safe** (no shared mutable state per call) but `RateLimiterBudget.GetRulesByMethod` holds a `sync.RWMutex` during iteration. Re-tokenization cost is paid under the read lock on every matching call. Source: [`upstream/ratelimiter_budget.go:L63-78`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L63-L78) 13. **`paramToString` on float64 from JSON.** JSON numbers decode as `float64`; `strconv.FormatFloat(v, 'f', -1, 64)` produces `"1234"` not `"1234.0"`. A string pattern `"123*"` would match numeric param `1234`. Source: [`data/cache_policy.go:L234-249`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L234-L249) 14. **Cache `MatchesForGet` returns `true` for `unknown` finality across all policies.** A request with indeterminate finality can be served from a `finalized` policy's cache, potentially returning stale data. Source: [`data/cache_policy.go:L146-149`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L146-L149) 15. **Legacy single-object failsafe migration is silent.** An old `failsafe: {…}` (object form) is quietly converted to a 1-element slice. No log or warning is emitted. The migration only forces `matchMethod` to `"*"` when the field is empty — an explicitly-set non-empty `matchMethod` value (e.g., `"eth_call"`) is preserved as-is. The migration applies at YAML parse time across `NetworkConfig`, `NetworkDefaults`, and `UpstreamConfig`. Source: [`common/config.go:L2041-2103`](https://github.com/erpc/erpc/blob/main/common/config.go#L2041-L2103) 16. **Zero-config auto-generated project only when `projects:` is entirely absent.** Even `projects: []` skips the auto-generated 'main' project defaults. Source: [`common/defaults.go:L100-167`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L167) 17. **`DataFinalityStateAll = -1` is an internal sentinel.** It must never appear in config or on requests — it only lives in health-tracker cross-finality rollup keys. Source: [`common/data.go:L29-36`](https://github.com/erpc/erpc/blob/main/common/data.go#L29-L36) 18. **Empty pattern in `MatchesSelector` always returns `false`.** The function guards against empty patterns at entry and immediately returns `false`. Callers must ensure the `use-upstream` directive value is non-empty — an empty `X-ERPC-Use-Upstream` header or query param results in no upstream being selected by that directive. Source: [`common/matcher.go:L73`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L73) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_unexpected_panic_total{scope="validate-pattern"}` | counter | scope, extra (pattern), error | `ValidatePattern` catches a tokenizer/parser panic | | `erpc_network_static_response_served_total` | counter | project, network, method | Every static-response cache hit in `tryServeStaticResponse` | Trace span attributes set during network-level failsafe selection: - `failsafe.matched_method` — the matched `matchMethod` value - `failsafe.matched_finalities` — the matched finality list Source: [`erpc/networks.go:L1179-1180`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1179-L1180) Notable log lines: - `"method support result"` — Debug, `upstream/upstream.go`, fields: `allowed` (bool), `method` (string). Emitted after each upstream method-support check. - `"skipping static response: cannot inspect request"` — Debug, `erpc/networks_static_responses.go`. Emitted when params cannot be read for static-response matching. - `"served static response (no upstream contacted)"` — Debug, `erpc/networks_static_responses.go`. Emitted on a static-response cache hit. - `"error matching ignore method … with method …"` — Error, `auth/authorizer.go`. Emitted when `WildcardMatch` returns an error during auth method-filter evaluation. ### Source code entry points - [`common/matcher.go:L221-L272`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L221-L272) — `tokenize`: byte-by-byte tokenizer producing `tokenOr`, `tokenAnd`, `tokenNot`, `tokenLParen`, `tokenRParen`, `tokenPattern` - [`common/matcher.go:L73-L134`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L73-L134) — `MatchesSelector`, `UpstreamMatchesSelector`, `ValidatePattern` - [`common/match.go:L18-L78`](https://github.com/erpc/erpc/blob/main/common/match.go#L18-L78) — `SelectExecutor[E]`: generic 4-tier executor picker (single pass, four tier buckets) - [`data/cache_policy.go:L62-L249`](https://github.com/erpc/erpc/blob/main/data/cache_policy.go#L62-L249) — `MatchesForSet`, `MatchesForGet`, `matchParams`, `matchParam`, `paramToString` - [`common/static_response.go:L14-L39`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L14-L39) — `FindStaticResponseMatch`: exact-equality path (distinct from `WildcardMatch`) - [`common/defaults.go:L17-L34`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L17-L34) — `MatchFinalities`: set-overlap utility used only in defaults merging - [`upstream/upstream.go:L372-L408`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L372-L408) — upstream-level `getFailsafeExecutor`: manual 4-tier loop - [`erpc/networks.go:L910-L928`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L910-L928) — network-level `getFailsafeExecutor`: config-order first-match scan - [`auth/authorizer.go:L80-L115`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L80-L115) — `shouldApplyToMethod`: ignore-then-allow semantics - [`consensus/quota.go:L96`](https://github.com/erpc/erpc/blob/main/consensus/quota.go#L96) — `WildcardMatch` on upstream tag strings for consensus quota matching - [`common/matcher_test.go`](https://github.com/erpc/erpc/blob/main/common/matcher_test.go) — comprehensive table-driven tests for `WildcardMatch`, `MatchesSelector`, `ValidatePattern` ### Related pages - [Failsafe](/config/failsafe/retry.llms.txt) — uses `matchMethod` + `matchFinality` for executor dispatch. - [Rate limiters](/config/rate-limiters.llms.txt) — uses `method` pattern; all matching rules fire simultaneously. - [Auth](/config/auth.llms.txt) — uses `ignoreMethods`/`allowMethods` with same ignore-then-allow semantics. - [Database / cache](/config/database.llms.txt) — uses `network`, `method`, and `params` patterns in policies. - [Projects](/config/projects.llms.txt) — project-level `ignoreMethods`/`allowMethods` and `forwardHeaders` patterns. --- --- # Projects > Source: https://docs.erpc.cloud/config/projects > One eRPC, many tenants — each project gets its own networks, upstreams, auth, and budgets. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Projects A project is a tenant inside one eRPC deployment: your frontend, your indexer, and your test environment can each get their own endpoint, providers, auth rules, and rate-limit budget — served from a single process. Everything under this section configures what lives inside a project. - **[Networks](/config/projects/networks.llms.txt)** — Each chain your project serves, with aliases and per-chain tweaks. - **[Upstreams](/config/projects/upstreams.llms.txt)** — The RPC endpoints behind your project and how they behave. - **[Providers](/config/projects/providers.llms.txt)** — One API key that unlocks every chain a vendor supports. - **[Selection & scoring](/config/projects/selection-policies.llms.txt)** — How eRPC decides which upstream deserves the next request. - **[CORS](/config/projects/cors.llms.txt)** — Serve browsers directly, on your own origin rules. - **[Static responses](/config/projects/static-responses.llms.txt)** — Answer chosen methods instantly without touching any upstream. - **[Shadow upstreams](/config/projects/shadow-upstreams.llms.txt)** — Audition a new provider on live traffic, risk-free. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add a second project for my indexer** ```text I want to create a second eRPC project in my eRPC config for my indexer traffic — separate upstreams, longer timeouts, and a different rate-limit budget from my frontend project. Walk me through setting up projects[].id, upstreams, networks, and auth. Also point me at the child pages I should read for each section. Reference: https://docs.erpc.cloud/config/projects.llms.txt ``` **Prompt Example #2: understand project URL routing** ```text Explain how eRPC routes requests to the right project based on the URL structure, and how projects[].id maps to the endpoint path. I want to know the exact URL pattern and any multi-tenant gotchas before I deploy. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects.llms.txt ``` --- ### Projects — agent starting points This page is an orientation hub. Implementation detail lives in the child pages — fetch their machine-readable companions: - [Networks](/config/projects/networks.llms.txt) · [Upstreams](/config/projects/upstreams.llms.txt) · [Providers](/config/projects/providers.llms.txt) - [Selection & scoring](/config/projects/selection-policies.llms.txt) · [CORS](/config/projects/cors.llms.txt) - [Static responses](/config/projects/static-responses.llms.txt) · [Shadow upstreams](/config/projects/shadow-upstreams.llms.txt) Project-level config keys: `projects[].id`, `projects[].auth`, `projects[].cors`, `projects[].networkDefaults`, `projects[].upstreamDefaults`, `projects[].rateLimitBudget`, `projects[].healthCheck`, `projects[].providers`, `projects[].upstreams`, `projects[].networks`, `projects[].allowClientDirectives`. Each is documented exhaustively in the child page whose topic it belongs to; multi-tenant behavior (URL shape `/{projectId}/{architecture}/{chainId}`) is covered in [URL structure](/operation/url.llms.txt). ## How it works **Isolation boundaries.** `ProjectsRegistry` is built once at startup and eagerly registers every `projects[]` entry. Per project: a health tracker (rolling-window scorer), a providers registry, an upstreams registry, an optional auth registry (only when `auth` is configured), a selection-policy JS runtime, and a networks registry. Shared across projects: the rate-limiters registry, shared-state registry, the EVM JSON-RPC cache (project-scoped at network-prepare time via `evmJsonRpcCache.WithProjectId(projectId)`), the vendors registry, and the proxy-pool registry. Duplicate project ids fail startup with `ErrProjectAlreadyExists`. **Request routing (HTTP).** `handleRequest` first applies **domain aliasing**: each `server.aliasing.rules[]` entry is matched against the request `Host` (port stripped) with a wildcard; the first match pre-selects `projectId`/`architecture`/`chainId`. Then `parseUrlPath` fills remaining values from path segments. A trailing `/healthcheck` segment, or any non-POST/non-OPTIONS method (e.g. `GET`), flags a healthcheck rather than an RPC call. Project resolution via `erpc.GetProject` — unknown id returns `ErrProjectNotFound` → HTTP 404. **gRPC routing.** The project comes from `x-erpc-project` metadata (required, else `InvalidArgument`); chain from `x-erpc-chain-id`; architecture from `x-erpc-architecture`, defaulting to `"evm"`. The shared `RequestProcessor` then performs auth + forward identically to HTTP. For query streams, `AcquireRateLimitPermit` is called explicitly before the query executor because streams bypass `Forward`. **Per-request pipeline inside a project.** Each entry of a (possibly batched) request body is processed in its own goroutine: payload validation → `forwardHeaders` capture (wildcard match against incoming header names; matched values forwarded to upstream HTTP requests) → `ignoreMethods`/`allowMethods` gate (allow overrides ignore; rejected methods return JSON-RPC error `-32601` without touching auth or upstreams) → auth payload extraction from query/headers → `project.AuthenticateConsumer` (no-op returning nil user when project has no auth config) → network id resolution (from path or `"networkId"` field in body; lazy network bootstrap on first use) → directive defaults + HTTP enrichment → `project.Forward`. **`PreparedProject.Forward`.** Resolves the network (lazy-loads on first request; lazily created network configs are exposed back into `project.Config.Networks` via `ExposeNetworkConfig`), sets it on the request **before** rate limiting so metrics have the network label, then `AcquireRateLimitPermit` enforces the project-level budget. After that the "requests received" counter fires (so project-rate-limited requests are **not** counted as received). For EVM a pre-forward hook may short-circuit entirely (e.g. `eth_chainId` served statically, cache-affecting normalizations for `eth_blockNumber`/`eth_call`/`eth_getLogs`/`trace_filter`), otherwise `network.Forward` plus a network post-forward hook runs. If the network has shadow upstreams the response is cloned and mirrored asynchronously. **Rate-limit layering.** Project-level: `projects[].rateLimitBudget` names a budget in global `rateLimiters.budgets[]`; `AcquireRateLimitPermit` evaluates rules matching the method and calls `TryAcquirePermit(... origin="project")`; over-limit → `ErrProjectRateLimitRuleExceeded` → HTTP 429. Auth-level: each auth strategy may carry its own `rateLimitBudget`, overridable per-user (JWT claim / database record); checked inside `Authenticate` after a strategy succeeds, over-limit → `ErrAuthRateLimitRuleExceeded` → 429. Network- and upstream-level budgets are separate layers. **All layers fail open**: no store configured, Redis not yet connected, Redis timeout, or admission-semaphore saturation all allow the request. **CORS.** Two CORS surfaces: admin (`admin.cors`, checked before admin request handling) and per-project (`projects[].cors`, checked right after project resolution). `handleCORS`: if the request carries **no `Origin` header it is always allowed** (no point enforcing CORS for non-browser clients — eRPC treats CORS as a soft deterrent, not a security boundary). With an Origin present, each `allowedOrigins` pattern is evaluated with a wildcard/boolean match. Allowed origin → echo the origin in `Access-Control-Allow-Origin` plus methods/headers/expose/credentials/max-age headers; OPTIONS preflight then terminates with 204. Disallowed origin → **no CORS headers but the request still proceeds** (browser blocks it; curl etc. succeed), except OPTIONS which gets a bare 204. CORS for a project only runs when `cors` is configured (nil → OPTIONS falls through to the JSON-RPC body parser). **Auth payload extraction precedence (HTTP).** `?token=` (deprecated, highest priority) → `?secret=` → header `X-ERPC-Secret-Token` → `Authorization: Basic …` (password half = secret; username ignored) → `Authorization: Bearer …` (JWT) → `?jwt=` → `?signature=&message=` (SIWE; message may be base64) → headers `X-Siwe-Message` + `X-Siwe-Signature` → fallback type `network` (client-IP based). **Consumer authentication.** `AuthRegistry.Authenticate`: nil payload → 401; zero strategies → allow (nil user). Iterate strategies in order; skip non-applicable (method filter / unsupported payload type); first success attaches a `User` to the request and enforces the strategy's rate-limit budget. If every applicable strategy errors, errors are joined into one `ErrAuthUnauthorized`. Auth rate-limit denial still returns the authenticated user alongside the 429 error, so `user` labels remain populated on rate-limit metrics. **Admin RPCs.** `erpc_project(params: [projectId])` → `{config, health}`; `erpc_taxonomy` → all projects/networks/upstreams with aliases; API-key CRUD resolves the project's database-auth connector; cordon RPCs resolve upstreams through the project registry. Admin auth itself is global (`admin.auth`), not per-project; requests to an instance without `admin` config return `ErrAuthUnauthorized` "admin is not enabled for this project". **Healthcheck and projects.** No project in path → all projects evaluated; a project with zero initialized upstreams lazily prepares upstreams for its static networks before evaluating; providers-only projects with no initialized upstreams report healthy with an explanatory message. **HTTP status code mapping.** 400 invalid path/unmarshal/invalid request; 401 `ErrAuthUnauthorized`; 404 `ErrProjectNotFound`/`ErrNetworkNotFound`; 429 `ErrAuthRateLimitRuleExceeded`/`ErrProjectRateLimitRuleExceeded`/`ErrNetworkRateLimitRuleExceeded`/capacity; everything else 200 (JSON-RPC app errors). The top-level fatal-error writer forces 200 for POST per JSON-RPC convention. **Wildcard/boolean pattern grammar.** Used by CORS origins, aliasing domains, `forwardHeaders`, `ignoreMethods`/`allowMethods`, and rate-limit rule methods. Tokens: `|` (OR), `&` (AND), `!` (NOT), parentheses. Leaf patterns are glob matches where `*` = any sequence, `?` = exactly one char, **`.` = any single character** (not a literal dot). Operator precedence: NOT \> AND \> OR. For values starting with `0x`, prefixes `>=`, `<=`, `>`, `<`, `=` enable hex/decimal numeric comparison. No escape syntax exists. ## Config schema ### `projects[]` — ProjectConfig | Dotted path | Type | Default | Behavior / interactions | |---|---|---|---| | `projects` | `[]*ProjectConfig` | If empty/nil: a default project `id: "main"` is injected with `server.aliasing.rules: [{matchDomain: "*", serveProject: "main"}]` so `/evm/123` works without a project segment. The injected project carries opinionated `networkDefaults` (`getLogsMaxAllowedRange: 30000`, `getLogsSplitOnError: true`, retry 5 attempts, timeout 120 s, hedge quantile 0.7 max 2) and `upstreamDefaults` (`getLogsAutoSplittingRangeThreshold: 5000`, retry 1 attempt delay 500 ms, timeout 60 s). Validation requires `projects` to be non-nil after defaulting. | Config root | | `projects[].id` | string | — (required) | Used as the `project` label on nearly every metric, in URL path routing, gRPC `x-erpc-project`, admin RPC params. Uniqueness enforced at registration: duplicate → `ErrProjectAlreadyExists`. | | `projects[].auth` | `*AuthConfig` | `nil` (no auth → all requests allowed; `AuthenticateConsumer` returns `(nil, nil)`) | When set, an auth registry is built at registration. Requires ≥1 strategy. | | `projects[].cors` | `*CORSConfig` | `nil` (no CORS handling at all; OPTIONS not short-circuited) | Checked after project resolution. | | `projects[].providers` | `[]*ProviderConfig` | If both `providers` and `upstreams` are empty: one default provider is injected: `{id: "public", vendor: "repository"}`. | Unique ids required. Per-project providers registry. | | `projects[].upstreamDefaults` | `*UpstreamConfig` | `nil` | Applied to every upstream via `ApplyDefaults` before that upstream's own `SetDefaults`; also passed to the providers registry. | | `projects[].upstreams` | `[]*UpstreamConfig` | `nil` | Shorthand non-http(s)/grpc endpoints (e.g. `alchemy://KEY`) are converted into providers and removed from the list at `SetDefaults` time. Requires ≥1 of `upstreams`/`providers`. Unique ids required. | | `projects[].networkDefaults` | `*NetworkDefaults` | `nil` | Applied to statically defined networks at `SetDefaults` and to lazy-loaded networks at first request. Its own `rateLimitBudget` is network-level, distinct from project-level. | | `projects[].networks` | `[]*NetworkConfig` | `nil` | Networks not listed are lazily created on first request and the resulting config is appended back into `Config.Networks` (visible via admin `erpc_project`). Unique network ids and unique aliases required. | | `projects[].rateLimitBudget` | string | `""` (no project-level limiting) | Names a budget id under global `rateLimiters.budgets[]`. Enforced per request in `AcquireRateLimitPermit`. Must exist in `rateLimiters` — unknown budget fails startup. | | `projects[].userAgentMode` | `"simplified"` \| `"raw"` | `""` → treated as `simplified` at request time | `simplified` buckets the User-Agent into ~20 low-cardinality names (curl, viem, ethers, chrome, …); `raw` stores it verbatim (high metric cardinality). Used for the `agent_name` metric label. Query param `?user-agent=` takes precedence over the header. | | `projects[].forwardHeaders` | `[]string` (wildcard patterns) | `nil` (forward nothing) | Each pattern is wildcard-matched against every incoming header name; matches are forwarded to the upstream HTTP request. **FOOTGUN**: values are stored under the **pattern** key, so a wildcard pattern like `X-Custom-*` forwards the value under the literal header name `X-Custom-*`, not the original header name. Exact names work as expected. | | `projects[].allowClientDirectives` | `*string` (wildcard pattern) | `nil` (all directives allowed) | Controls which `X-ERPC-*` request directives (headers and query params) clients may use. The pattern is pre-compiled at project registration and evaluated against each directive's query-param key (e.g. `skip-cache-read`, `use-upstream`, `skip-consensus`) using the standard wildcard/boolean grammar. `nil`/omitted = all allowed (backward-compatible). `""` = none allowed. `"!skip-cache-read & !use-upstream"` = all except those two. Config-set `directiveDefaults` always apply regardless of this filter. Does **not** filter `X-ERPC-Force-Trace` (which bypasses OTel sampling at span creation, before project resolution). Overridable per caller via `projects[].auth.strategies[].allowClientDirectives`. | | `projects[].auth.strategies[].allowClientDirectives` | `*string` (wildcard pattern) | `nil` (inherit project value) | Per-caller override of the project-level pattern, applied to users authenticated by **this** strategy. Same syntax and same `""` = none / `"*"` = all semantics. Overrides in both directions: a strategy may widen (project `""` + strategy `"*"`) or narrow (project `"*"` + strategy `""`) — the project value is a default, not a ceiling. Typical shape is deny-by-default at the project and re-grant to trusted credentials. The capability is attached to the `User` by the authenticating strategy, so a caller identified only through `trustUserIdHeader` always falls back to the project value — an unvalidated identity header can never widen directive access. | | `projects[].ignoreMethods` | `[]string` (wildcard) | `nil` (nothing ignored) | If any pattern matches the JSON-RPC method, the method is rejected — unless re-allowed by `allowMethods`. Rejection is JSON-RPC error `code: -32601` ("method not supported: X") returned without auth/upstream work. | | `projects[].allowMethods` | `[]string` (wildcard) | `nil` | Overrides `ignoreMethods` (e.g. `ignoreMethods: ["*"]` + `allowMethods: ["eth_getLogs"]` = only eth_getLogs). **NOTE**: `allowMethods` alone does NOT create an allowlist — a method matching neither list is still served (initial `shouldHandleMethod = true`). | | `projects[].scoreMetricsWindowSize` | Duration | `0` → falls back to **1 minute** at runtime | Rolling window of the per-upstream health tracker (10 sliding buckets). **FOOTGUN**: source-code comments in two places say "10m" but the actual code value is `var ScoreMetricsWindowSize = 1 * time.Minute`. To get a 10-minute window you must set `scoreMetricsWindowSize: 10m` explicitly. See [source](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go#L50). | ### `projects[].cors.*` / `admin.cors.*` — CORSConfig | Dotted path | Type | Default (after `SetDefaults`) | Behavior | |---|---|---|---| | `cors.allowedOrigins` | `[]string` | `["*"]` programmatically — but `Validate()` errors if the field is missing/empty for explicit `cors:` blocks: `*.cors.allowedOrigins is required`. | Each entry is a full wildcard/boolean pattern matched against the `Origin` header value. Match errors are logged and that pattern skipped. | | `cors.allowedMethods` | `[]string` | `["GET","POST","OPTIONS"]` | Joined with `", "` into `Access-Control-Allow-Methods`. Informational for the browser; no server-side enforcement. | | `cors.allowedHeaders` | `[]string` | `["content-type","authorization","x-erpc-secret-token"]` | Joined into `Access-Control-Allow-Headers`. | | `cors.exposedHeaders` | `[]string` | `nil` (no default) | Joined into `Access-Control-Expose-Headers`. **When nil** (the common default), `strings.Join(nil, ", ")` returns `""`, so the server sends `Access-Control-Expose-Headers: ""`. Browsers interpret this as zero extra headers exposed — any frontend JS call to `response.headers.get('X-ERPC-Cache')` returns `null`. eRPC emits rich diagnostic response headers (`X-ERPC-Cache`, `X-ERPC-Upstream`, `X-ERPC-Duration`, `X-ERPC-Attempts`, `X-ERPC-Upstream-Attempts`, `X-ERPC-Upstream-Retries`, `X-ERPC-Upstream-Hedges`, `X-ERPC-Network-Attempts`, `X-ERPC-Network-Retries`, `X-ERPC-Network-Hedges`, `X-ERPC-Consensus-Slots`, `X-ERPC-Consensus-Disputes`, `X-ERPC-Consensus-Low-Participants`, `X-ERPC-Cache-Attempts`, `X-ERPC-Cache-Retries`, `X-ERPC-Cache-Hedges`) — browser clients cannot read any of these without an explicit `exposedHeaders` list. Set e.g. `exposedHeaders: ["X-ERPC-Cache", "X-ERPC-Upstream", "X-ERPC-Duration", "X-ERPC-Attempts"]`. There is no wildcard shorthand accepted by current browsers. | | `cors.allowCredentials` | `*bool` | `false` | Only when explicitly `true` is `Access-Control-Allow-Credentials: true` emitted. | | `cors.maxAge` | int (seconds) | `3600` if `0` | Emitted as `Access-Control-Max-Age` only when `> 0`. | | `admin.cors` | `*CORSConfig` | If admin section exists and `cors` is nil: `{allowedOrigins: ["*"], allowCredentials: false}` then `SetDefaults` (safe because admin requires secret-token auth). | Applied to `/admin` before any admin handling. | ### `projects[].auth.*` — AuthConfig | Dotted path | Type | Default | Behavior | |---|---|---|---| | `auth.strategies` | `[]*AuthStrategyConfig` | — (required, ≥1) | Evaluated in declaration order; first strategy that applies to the method, supports the extracted payload type, and authenticates successfully wins. | | `auth.strategies[].type` | `"secret"` \| `"jwt"` \| `"siwe"` \| `"network"` \| `"database"` | — (required; unknown type → startup `ErrInvalidConfig`) | Selects the strategy object; the matching sub-config must be present or startup fails. | | `auth.strategies[].ignoreMethods` | `[]string` (wildcard) | `nil` | Strategy skipped for matching methods. | | `auth.strategies[].allowMethods` | `[]string` (wildcard) | `nil` | Re-applies the strategy even when ignored (allow \> ignore). | | `auth.strategies[].rateLimitBudget` | string | `""` (no auth-level limiting) | Applied AFTER successful authentication. Per-user override `User.RateLimitBudget` (from `secret.rateLimitBudget`, `siwe.rateLimitBudget`, `network.rateLimitBudget`, JWT claim named by `jwt.rateLimitBudgetClaimName` (default `"rlm"`), or database record) takes precedence. Over-limit → `ErrAuthRateLimitRuleExceeded` (429). `TryAcquirePermit` is called with `origin = "auth"`. | | `auth.strategies[].database.connector.id` | string | — | Must be unique across database strategies in one project; referenced by admin API-key RPCs (`erpc_addApiKey` etc.). | ### `server.aliasing.*` — AliasingConfig | Dotted path | Type | Default | Behavior | |---|---|---|---| | `server.aliasing.rules` | `[]*AliasingRuleConfig` | `nil` | First rule whose `matchDomain` wildcard-matches the request Host (port stripped) wins; later rules ignored. Match errors are logged and the rule skipped. | | `server.aliasing.rules[].matchDomain` | string (wildcard) | — | e.g. `"*"`, `"eth.mycompany.com"`. | | `server.aliasing.rules[].serveProject` | string | `""` | Pre-selects projectId; path may still override with an explicit 3-segment path. | | `server.aliasing.rules[].serveArchitecture` | string | `""` | Pre-selects architecture (`"evm"` or `"svm"`). | | `server.aliasing.rules[].serveChain` | string | `""` | Pre-selects the chain identifier — the numeric chainId for EVM, the cluster (`mainnet-beta`, or `:` for a fork) for SVM. Combination project+chain WITHOUT architecture is rejected: "it is not possible to alias for project and chain WITHOUT architecture". | ### `rateLimiters.budgets[].*` — global rate-limit budget config | Dotted path | Type | Default | Behavior | |---|---|---|---| | `rateLimiters.budgets[].id` | string | — | Referenced by `projects[].rateLimitBudget`, `auth.strategies[].rateLimitBudget`, network/upstream budgets. | | `rateLimiters.budgets[].rules[].method` | string (wildcard) | `"*"` if empty | A rule applies when the method matches (wildcard). | | `rateLimiters.budgets[].rules[].maxCount` | uint32 | — | Fixed-window limit per period. | | `rateLimiters.budgets[].rules[].period` | `second` \| `minute` \| `hour` \| `day` \| `week` \| `month` \| `year` | `second` if invalid; YAML accepts names, ints 0–6, or duration aliases (`"1s"`, `"24h"`, `"7d"`, …) | Fixed window unit. | | `rateLimiters.budgets[].rules[].perIP` / `perUser` / `perNetwork` | bool | `false` | Adds ip/user/network descriptor entries so counters are scoped per client IP / authenticated user id / network id. | | `rateLimiters.budgets[].rules[].waitTime` | Duration | `0` | Present in config; not consumed in the project-level path. | ### Legacy project fields (YAML-only) These fields are read at load time, converted or warned, then erased. They are never visible after `LoadConfig`. | Field | Type | Behavior | |---|---|---| | `routingStrategy` | string | **Semantic** — triggers eval synthesis. `"round-robin"` → synthesizes `rotateBy(ctx.tickCount)` per network. Any other non-empty value → synthesizes `sortByScore + stickyPrimary`. Deprecation warning emitted. | | `scoreSwitchHysteresis` | float64 | **Semantic** — triggers eval synthesis even without `routingStrategy`. Non-zero → synthesizes `sortByScore + stickyPrimary` eval with `stickyPrimary({ hysteresis: })`. Zero but another semantic field present → defaults to `0.10`. | | `scoreMinSwitchInterval` | Duration | **Semantic** — triggers eval synthesis. Non-zero → synthesizes with `stickyPrimary({ ..., minSwitchInterval: '' })`. Zero but another semantic field present → defaults to `'30s'`. | | `scoreGranularity` | string | **Inert** — warning only, no behavior change. Previously controlled per-upstream vs per-method scoring. Replaced by `selectionPolicy.evalPerMethod`. | | `scorePenaltyDecayRate` | float64 | **Inert** — warning only, no behavior change. Previously modulated penalty recovery. No equivalent exists. | | `scoreMetricsMode` | string | **Inert** — warning only, no behavior change. Previously configured metrics aggregation. Replaced by `erpc_selection_*` metrics with fixed cardinality. | | `scoreRefreshInterval` | Duration | **Inert** — warning only, no behavior change. Previously set score-recalculation polling interval. Replaced by `selectionPolicy.evalInterval`. | **Legacy translation mechanics.** `ProjectConfig.UnmarshalYAML` captures all seven legacy fields. `LoadConfig` calls `legacy.TranslateFromConfig` **before** `SetDefaults` and `Validate`. Semantic fields present → per-network `selectionPolicy.evalFunc` synthesized UNLESS the network already has an explicit `selectionPolicy.eval` (modern fields always win). Inert fields only → warnings emitted, canonical default policy installs. After translation, `LegacyProject` is nil on every `ProjectConfig` — any code path that accesses it after `LoadConfig` always sees nil. **Migration**: remove all seven legacy fields and write an explicit `selectionPolicy.eval` using the chainable stdlib. ## URL path → (project, architecture, chain) resolution `parseUrlPath` cleans and splits the path; preselected values come from aliasing. Decision matrix (P=project, A=architecture, C=chain preselected): - **None preselected**: 1 seg → P; 2 segs → P + (network-alias resolve of seg2, else A); 3 segs → P/A/C; 0 segs → valid for healthcheck only; \>3 → error `must only provide ///`. - **P preselected**: 1 seg → alias resolve else A; 2 segs → A/C; 3 segs → full explicit override. - **P+A preselected**: 1 seg → alias resolve (must yield both) else C; 3 segs → full override. - **P+A+C preselected**: only `/` (or healthcheck) allowed; \>1 seg → error. - **A+C preselected**: 1 seg → P; 3 segs → full override. - **A only preselected**: 1 seg → P; 2 segs → P/C; 3 segs → full override; 0 segs allowed for global healthcheck. - **P+C without A** → error ("it is not possible to alias for project and chain WITHOUT architecture"). Post-checks: project required unless healthcheck; if A or C present, A must be `"evm"`; **any non-POST/non-OPTIONS method becomes a healthcheck**. `/admin` only with exactly one segment + POST/OPTIONS. **Network alias resolution.** Aliases are registered eagerly for static networks and lazily when a network is first prepared. `ResolveAlias(alias)` returns `(architecture, chainId)` or `("","")`. Duplicate alias with a different target keeps the first and logs a warning. Network ids must look like `evm:`; alias misses in path-position fall through to being treated as an architecture, producing `architecture is not valid` for bogus aliases. If both path and body lack a network, the body's `"networkId"` field (e.g. `"evm:42161"`) is consulted; otherwise: `architecture and chain must be provided in URL ... or in request body ... or configured via domain aliasing`. ## Observability All metrics use the `erpc_` namespace. | Metric | Labels | Notes | |---|---|---| | `erpc_cors_requests_total` | `project`, `origin` | Every request that carries an Origin header, before allow/deny. **NOTE**: the `project` label value is actually `r.URL.Path`, not the project id — cardinality grows with distinct request paths. | | `erpc_cors_preflight_requests_total` | `project`, `origin` | Allowed-origin OPTIONS preflights only. Same path-as-project label caveat. | | `erpc_cors_disallowed_origin_total` | `project`, `origin` | Origin present but no pattern matched. Same path-as-project label caveat. | | `erpc_network_request_received_total` | `project`, `network`, `category`, `finality`, `user`, `agent_name` | Fired in `Project.Forward` **after** project rate limiting — project-rate-limited requests are not counted here. | | `erpc_network_successful_request_total` | `project`, `network`, `vendor`, `upstream`, `category`, `attempt`, `finality`, `emptyish`, `user`, `agent_name` | Vendor/upstream = `""` for cache hits, `"n/a"` when upstream missing. | | `erpc_network_failed_request_total` | `project`, `network`, `category`, `attempt`, `error`, `severity`, `finality`, `user`, `agent_name` | `error` = `common.ErrorFingerprint(err)`. | | `erpc_network_request_duration_seconds` | `project`, `network`, `vendor`, `upstream`, `category`, `finality`, `user` | Histogram. vendor/upstream = `""` on failure. | | `erpc_rate_limits_total` | `project`, `network`, `vendor`, `upstream`, `category`, `finality`, `user`, `agent_name`, `budget`, `scope`, `auth`, `origin` | Unified deny counter. Project layer: `origin="project"`, `auth=""`. Auth layer: `origin="auth"`, `auth=":"`. | | `erpc_rate_limiter_budget_max_count` | `budget`, `method`, `scope` | Gauge. | | `erpc_rate_limiter_failopen_total` | `project`, `network`, `user`, `agent_name`, `budget`, `category`, `reason` | Reasons: `admission_full` / `limit_timeout`. Monitor this to detect hard-enforcement gaps. | | `erpc_auth_failed_total` | `project`, `network`, `strategy`, `reason`, `agent_name` | Incremented when `ErrAuthUnauthorized` is returned to the client. | | `erpc_shadow_response_identical_total` | — | Shadow traffic comparison outcomes. | | `erpc_shadow_response_mismatch_total` | — | Mismatches log at error level with both hashes. | | `erpc_shadow_response_error_total` | — | Shadow request error outcomes. | | `erpc_network_evm_block_range_requested_total` | — | Block-range heatmap; emitted when a block number is extractable from the response. | Trace spans: `Project.Forward` (detail span), `Project.PreForwardHook`, `RateLimiter.TryAcquirePermit` (detail) and `RateLimiter.DoLimit` (client span with `budget`, `method`, `scope`, `result` attrs), `Project.executeShadowRequest`, and a request-level span via `common.StartRequestSpan`. Notable logs: `registered project ` info at registration; `successfully forwarded request for network` (info); `CORS request from disallowed origin, continuing without CORS headers` (debug); `skipping duplicate alias registration with different target` (warn); `no projects found in config; will add a default 'main' project` (warn); `no providers or upstreams found in project; will use default 'public' endpoints repository` (warn). ## Edge cases & gotchas 1. **Requests without an `Origin` header bypass CORS entirely** — by design; eRPC treats CORS as a soft deterrent, not a security boundary. 2. **Disallowed origins are NOT rejected**: non-OPTIONS requests proceed and get a normal JSON-RPC response, just without `Access-Control-*` headers; only the browser enforces blocking. OPTIONS gets a bare 204. 3. **`.` matches any single character in glob patterns** (go-wildcard v2): `allowedOrigins: ["https://erpc.cloud"]` also matches `https://erpcXcloud`. Same applies to aliasing `matchDomain` and all wildcard fields. There is no escape syntax. 4. **`forwardHeaders` stores values under the configured pattern, not the matched header name** — a wildcard pattern forwards upstream a literal header named like the pattern (e.g. `X-Custom-*`). Only exact-name patterns round-trip faithfully. 5. **Project rate-limited requests never increment `erpc_network_request_received_total`** because `AcquireRateLimitPermit` runs before the counter; use `errc_rate_limits_total{origin="project"}` for those. 6. **`scoreMetricsWindowSize` stale source-code comments**: two comments in the codebase say "10 minutes" (`common/config.go:530`, `erpc/projects_registry.go:131-132`), but the **actual** package-level variable is `var ScoreMetricsWindowSize = 1 * time.Minute` ([source](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go#L50)). If you omit `scoreMetricsWindowSize` expecting a stable 10 m default, you silently get 1 m: the rolling window rotates every 6 seconds, upstream scoring reacts 10× faster than expected. Set `scoreMetricsWindowSize: 10m` explicitly to get 10 minutes. 7. **All rate limiting fails open**: no store configured, Redis still connecting, Redis call timeout (`limit_timeout`), or admission semaphore full (`admission_full`). Deployments needing hard guarantees must monitor `erpc_rate_limiter_failopen_total`. 8. **`allowMethods` is not an allowlist by itself** — `shouldHandleMethod` starts `true`; without `ignoreMethods` everything is served regardless of `allowMethods`. To build an allowlist: `ignoreMethods: ["*"]` + `allowMethods: [...]`. 9. **Unsupported-method responses normally carry `id: null`** due to an inverted error check before reading the request id in the error path. 10. **`GET /myproject/evm/123` (or any non-POST/non-OPTIONS method) is a healthcheck**, not an RPC error. 11. **OPTIONS to a project without `cors` configured is not short-circuited** — the early-return lives inside the `project.Config.CORS != nil` branch, so the OPTIONS request falls into JSON-RPC body parsing and errors. 12. **CORS for a project can only run after project resolution succeeds**: unknown project → 404 with no CORS headers, which browsers may surface as a CORS failure rather than 404. 13. **Lazy-loaded networks inherit `networkDefaults` and are appended into `project.Config.Networks`** at runtime (visible via admin `erpc_project`). 14. **First aliasing rule wins; rule-match errors are logged and skipped.** An explicit full 3-segment path can always override aliased preselection. 15. **Network aliases are per-project**; a duplicate alias targeting a different chain is ignored with a warning, keeping the first registration. Aliases must be unique within a project's static config. 16. **Zero-project configs still validate** because `SetDefaults` injects the `main` project before `Validate` runs. 17. **Project rate-limit test is fixed-window, not sliding** — rate-limit rules apply to a fixed time window; requests over the limit in the current window are denied regardless of past windows. 18. **`projects[].rateLimitBudget` referencing an unknown budget fails startup** — but auth-strategy budgets and per-user (database/JWT-claim) budgets are resolved at request time and surface as runtime `ErrRateLimitBudgetNotFound`. 19. **CORS metrics label `project` actually contains the URL path**, so cardinality grows with distinct request paths and you cannot group by real project id from these counters alone. 20. **Secret auth via `Authorization: Basic`** uses only the password half; the username is ignored. The deprecated `?token=` query param still works and takes top precedence. 21. **Auth rate-limit denial still returns the authenticated user** alongside the 429 error, so `user` labels remain populated on rate-limit metrics. 22. **`exposedHeaders: nil` silently blocks browser access to all `X-ERPC-*` headers.** `strings.Join(nil, ", ")` returns `""`, so the server sends `Access-Control-Expose-Headers: ""`. Enumerate desired headers explicitly — no glob wildcard shorthand is accepted by current browsers. 23. **Legacy scoring fields are consumed and erased before `SetDefaults`** — after `TranslateFromConfig` runs, `LegacyProject` is nil on every `ProjectConfig`. Admin RPCs and health endpoints always see nil for this field. 24. **Inert legacy fields (`scoreGranularity`, `scorePenaltyDecayRate`, `scoreMetricsMode`, `scoreRefreshInterval`) do NOT synthesize an eval.** A config with only these four fields gets deprecation warnings but retains the full canonical default selection policy (`removeCordoned + keepHealthy + preferTag + sortByScore + stickyPrimary + probeExcluded`). 25. **`routingStrategy: "score-based"` (or any non-`"round-robin"` non-empty string) synthesizes a `sortByScore + stickyPrimary` eval.** A per-network `selectionPolicy.eval` (new field) always wins over the synthesized legacy eval. 26. **`scoreSwitchHysteresis` and `scoreMinSwitchInterval` are semantic fields that trigger eval synthesis even without `routingStrategy`.** If either is non-zero, a `sortByScore + stickyPrimary` eval is synthesized across all networks. 27. **`allowClientDirectives` does not filter `X-ERPC-Force-Trace`** — force-trace bypasses OTel sampling at span creation in `StartHTTPServerSpan`, which runs before project resolution. Filtering it requires deferring the sampling decision until after project resolution. 28. **`allowClientDirectives` does not affect `directiveDefaults`** — config-set directive defaults (via `networks[].directiveDefaults`) always apply regardless of the client directive filter. The filter only gates directives arriving via HTTP headers or query parameters. ## Source code entry points - [`erpc/projects.go`](https://github.com/erpc/erpc/blob/main/erpc/projects.go) — `PreparedProject`: per-tenant facade; `Forward` (metrics, shadow fan-out), `AcquireRateLimitPermit` (project budget), `AuthenticateConsumer`, lazy network-config exposure, health info. - [`erpc/projects_registry.go`](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go) — `ProjectsRegistry`: builds/boots all projects; per-project tracker/policy-engine/auth/upstreams/networks wiring; `ScoreMetricsWindowSize` fallback var. - [`erpc/erpc.go`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go) — `ERPC` root object: constructs shared registries and the projects registry; admin auth registry. - [`erpc/http_server.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go) — HTTP entry: aliasing, `parseUrlPath`, `handleCORS`, per-request pipeline (forwardHeaders, method gates, auth, forward), status-code mapping. - [`erpc/request_processor.go`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go) — shared gRPC/query-stream pipeline. - [`erpc/grpc_server.go`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go) — gRPC project selection via `x-erpc-project`/`x-erpc-chain-id` metadata. - [`erpc/networks_registry.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go) — per-project network lifecycle + alias registry; project-scoped cache binding. - [`erpc/admin.go`](https://github.com/erpc/erpc/blob/main/erpc/admin.go) — `erpc_project`, `erpc_taxonomy`, API-key CRUD, cordon RPCs. - [`erpc/healthcheck.go`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go) — per-project/per-network health evaluation. - [`erpc/shadow.go`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go) — project-layer shadow request execution/comparison. - [`erpc/block_heatmap.go`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go) — per-project block-range heatmap metric emission. - [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go) — `ProjectConfig`, `CORSConfig`, `AuthConfig`/strategy configs, `AliasingConfig`, rate-limiter config types, `UserAgentTrackingMode`, legacy project fields. - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) — default `main` project injection, `ProjectConfig.SetDefaults`, `CORSConfig.SetDefaults`. - [`common/validation.go`](https://github.com/erpc/erpc/blob/main/common/validation.go) — `Config.Validate`/`ProjectConfig.Validate`. - [`common/matcher.go`](https://github.com/erpc/erpc/blob/main/common/matcher.go) — `WildcardMatch` boolean/glob grammar. - [`common/errors.go`](https://github.com/erpc/erpc/blob/main/common/errors.go) — `ErrProjectNotFound` (404), `ErrProjectAlreadyExists`, `ErrProjectRateLimitRuleExceeded` (429), `ErrAuthUnauthorized` (401), `ErrAuthRateLimitRuleExceeded` (429). - [`auth/registry.go`](https://github.com/erpc/erpc/blob/main/auth/registry.go), [`auth/authorizer.go`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go), [`auth/http.go`](https://github.com/erpc/erpc/blob/main/auth/http.go) — per-project auth strategy iteration, method filters, auth-level budgets, HTTP payload extraction. - [`upstream/ratelimiter_registry.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go), [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go) — global budget store, Envoy-based fixed-window evaluation, fail-open machinery. - [`telemetry/metrics.go`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go) — CORS counters, network request counters/histograms, unified rate-limit counter, auth/shadow metrics. - [`common/legacy/translate.go`](https://github.com/erpc/erpc/blob/main/common/legacy/translate.go) — `TranslateFromConfig` hook: walks all projects, classifies legacy fields, synthesizes `selectionPolicy.evalFunc`, clears stashes. - [`common/legacy/eval_synthesis.go`](https://github.com/erpc/erpc/blob/main/common/legacy/eval_synthesis.go) — JS source generators for score-based and round-robin legacy policies. - [`common/legacy/warnings.go`](https://github.com/erpc/erpc/blob/main/common/legacy/warnings.go) — per-field deprecation warning strings. - Tests: [`erpc/projects_test.go`](https://github.com/erpc/erpc/blob/main/erpc/projects_test.go) (project rate limit, lazy networks, aliases), [`erpc/http_server_test.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server_test.go) (CORS, URL-path matrix). --- --- # CORS > Source: https://docs.erpc.cloud/config/projects/cors > Let your frontend talk to eRPC safely — configure which browser origins are allowed, in seconds, without blocking a single server-to-server call. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # CORS Your backend calls always get through — eRPC only applies CORS to requests that carry an `Origin` header, which is every browser and nothing else. Add `cors.allowedOrigins` to a project and browser clients from your listed domains are allowed in; everyone else is quietly blocked by the browser. No config change needed for your servers, indexers, or scripts. ## Quick taste Illustrative, not a tuned production config — allow one origin and expose cache headers to browser JS: **Config path:** `projects[].cors` **YAML — `erpc.yaml`:** ```yaml projects: - id: main cors: allowedOrigins: - "https://app.example.com" # list every X-ERPC-* header your browser JS needs to read exposedHeaders: - "X-ERPC-Cache" - "X-ERPC-Duration" ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", cors: { allowedOrigins: ["https://app.example.com"], // list every X-ERPC-* header your browser JS needs to read exposedHeaders: ["X-ERPC-Cache", "X-ERPC-Duration"], }, }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: serve my dApp frontend directly from eRPC** ```text My dApp frontend at https://app.example.com needs to call my eRPC endpoint directly from the browser. Configure CORS so only my origins are allowed, preflight requests are handled correctly, and local development on localhost keeps working. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/projects/cors.llms.txt ``` **Prompt Example #2: debug browser requests being blocked** ```text Browser requests to my eRPC endpoint fail with CORS errors while curl works fine. Diagnose which CORS setting is wrong (origins, methods, headers, credentials) in my eRPC config and fix it, then explain what preflight response eRPC sends for my corrected config. Reference: https://docs.erpc.cloud/config/projects/cors.llms.txt ``` --- ### CORS — full agent reference ### How it works `handleCORS` ([`erpc/http_server.go:1008-1077`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1008-L1077)) is called right after project resolution, once per inbound request. **No `Origin` header → always allowed.** The code comment at `erpc/http_server.go:1010-1018` explicitly states this is a soft deterrent against casual browser embedding, not a security boundary. Server-to-server callers, indexers, `curl`, and any client that omits `Origin` bypass CORS entirely and go straight to JSON-RPC processing. No headers are written and no metrics fire. **With an `Origin` header present**, eRPC increments `erpc_cors_requests_total`, then evaluates each `allowedOrigins` pattern via `WildcardMatch` (eRPC's glob+boolean grammar). First match wins; pattern-match errors are logged at debug and the pattern is skipped. **Allowed origin:** eRPC writes `Access-Control-Allow-Origin` set to the echoed request origin (never the literal `*`), plus `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers`, `Access-Control-Expose-Headers`, and conditionally `Access-Control-Allow-Credentials` and `Access-Control-Max-Age`. An `OPTIONS` preflight then terminates with HTTP 204 before any JSON-RPC parsing happens. **Disallowed origin:** eRPC omits all `Access-Control-*` headers but still processes the request — non-OPTIONS requests continue and produce a full JSON-RPC response; the browser enforces the block. OPTIONS returns a bare 204. [`erpc/http_server.go:1035-1051`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1035-L1051) **CORS for a project runs only when `cors` is configured.** When `cors: nil`, OPTIONS falls through to the JSON-RPC body parser and errors instead of returning a clean 204. [`erpc/http_server.go:343-347`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L343-L347) **Admin CORS** is a separate surface evaluated before any admin request handling (`erpc/http_server.go:295-301`). When `admin` is configured but `admin.cors` is absent, `SetDefaults` auto-injects `{allowedOrigins: ["*"], allowCredentials: false}` — safe because admin endpoints require a secret token. **Origin pattern syntax.** `allowedOrigins` entries are full `WildcardMatch` patterns: `*` = any sequence, `?` = exactly one character, `.` = **any single character** (not a literal dot — see gotchas), `|` OR, `&` AND, `!` NOT, parentheses for grouping. Precedence: NOT > AND > OR. Examples: `"https://*.example.com"` allows all subdomains; `"https://app.example.com | https://staging.example.com"` allows either of two explicit origins. Source: [`common/matcher.go:34-47`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L34-L47). ### Config schema All fields belong to `projects[].cors` (`CORSConfig`, [`common/config.go:L658-665`](https://github.com/erpc/erpc/blob/main/common/config.go#L658-L665)). Defaults applied by [`common/defaults.go:L2824-2846`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2824-L2846). Validation at [`common/validation.go:L773-775`](https://github.com/erpc/erpc/blob/main/common/validation.go#L773-L775). | Field | Type | Default (after `SetDefaults`) | Behavior / footguns | |---|---|---|---| | `cors.allowedOrigins` | `[]string` | **Required** — validation errors if missing/empty (`*.cors.allowedOrigins is required`). `["*"]` only for auto-injected admin CORS and programmatic configs that skip validation. | Each entry is a full `WildcardMatch` pattern matched against the `Origin` header. First match wins; match errors are logged and the pattern is skipped. Source: [`erpc/http_server.go:L1022-1033`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1022-L1033) | | `cors.allowedMethods` | `[]string` | `["GET","POST","OPTIONS"]` | Joined into `Access-Control-Allow-Methods`. No server-side enforcement; informational for the browser preflight. Source: [`common/defaults.go:L2828-2830`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2828-L2830) | | `cors.allowedHeaders` | `[]string` | `["content-type","authorization","x-erpc-secret-token"]` | Joined into `Access-Control-Allow-Headers`. Source: [`common/defaults.go:L2831-2837`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2831-L2837) | | `cors.exposedHeaders` | `[]string` | `nil` — **no default set**; `strings.Join(nil, ", ")` emits `""` so the browser exposes zero extra headers. | Joined into `Access-Control-Expose-Headers`. **Footgun**: omitting this field silently blocks browser JS access to every `X-ERPC-*` diagnostic header. eRPC emits the following response headers that are inaccessible to browser JS without an explicit list: `X-ERPC-Cache`, `X-ERPC-Upstream`, `X-ERPC-Duration`, `X-ERPC-Attempts`, `X-ERPC-Upstream-Attempts`, `X-ERPC-Upstream-Retries`, `X-ERPC-Upstream-Hedges`, `X-ERPC-Network-Attempts`, `X-ERPC-Network-Retries`, `X-ERPC-Network-Hedges`, `X-ERPC-Consensus-Slots`, `X-ERPC-Consensus-Disputes`, `X-ERPC-Consensus-Low-Participants`, `X-ERPC-Cache-Attempts`, `X-ERPC-Cache-Retries`, `X-ERPC-Cache-Hedges`. Enumerate desired headers explicitly — glob shorthand is not part of the CORS spec. Sources: [`erpc/http_server.go:L1057`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1057), [`erpc/http_server.go:L1088-1204`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1088-L1204) | | `cors.allowCredentials` | `*bool` | `false` | When `true`, emits `Access-Control-Allow-Credentials: true`. **Footgun**: browsers reject `allowCredentials: true` combined with `allowedOrigins: ["*"]`; the response is blocked entirely. Source: [`common/defaults.go:L2838-2840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2838-L2840) | | `cors.maxAge` | `int` (seconds) | `3600` when `0` | Emitted as `Access-Control-Max-Age` only when `> 0`. Controls browser preflight cache TTL. Source: [`common/defaults.go:L2841-2843`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2841-L2843) | `admin.cors` uses the same `CORSConfig` struct. When `admin` is present and `cors` is nil, `SetDefaults` injects `{allowedOrigins: ["*"], allowCredentials: false}` then runs `SetDefaults`. Source: [`common/defaults.go:L769-787`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L769-L787). ### Worked examples **1. Minimal single-origin setup.** The simplest production config: one explicit origin allowed, no extras needed. Browser preflight is answered with 204; all server-to-server calls are unaffected: **Config path:** `projects[].cors` **YAML — `erpc.yaml`:** ```yaml cors: allowedOrigins: - "https://app.example.com" ``` **TypeScript — `erpc.ts`:** ```typescript cors: { allowedOrigins: ["https://app.example.com"], } ``` **2. Frontend dashboard that reads eRPC diagnostic headers.** Browser JS cannot read `X-ERPC-Cache` or `X-ERPC-Duration` without explicit `exposedHeaders`. Add every header your frontend needs — glob shorthand (`X-ERPC-*`) is not part of the CORS spec and most browsers ignore it: **Config path:** `projects[].cors` **YAML — `erpc.yaml`:** ```yaml cors: allowedOrigins: - "https://dashboard.example.com" exposedHeaders: - "X-ERPC-Cache" - "X-ERPC-Upstream" - "X-ERPC-Duration" - "X-ERPC-Attempts" ``` **TypeScript — `erpc.ts`:** ```typescript cors: { allowedOrigins: ["https://dashboard.example.com"], exposedHeaders: [ "X-ERPC-Cache", "X-ERPC-Upstream", "X-ERPC-Duration", "X-ERPC-Attempts", ], } ``` **3. Multi-environment with boolean OR pattern.** When you have a production and staging origin, use the boolean OR syntax instead of two separate entries — the matcher evaluates them as a single expression: **Config path:** `projects[].cors` **YAML — `erpc.yaml`:** ```yaml cors: allowedOrigins: - "https://app.example.com | https://staging.example.com" exposedHeaders: - "X-ERPC-Cache" ``` **TypeScript — `erpc.ts`:** ```typescript cors: { allowedOrigins: ["https://app.example.com | https://staging.example.com"], exposedHeaders: ["X-ERPC-Cache"], } ``` **4. Wildcard subdomain with credentials.** Allow any subdomain of your company domain and send cookies/auth headers. Never combine `allowedOrigins: ["*"]` with `allowCredentials: true` — browsers will reject the response: **Config path:** `projects[].cors` **YAML — `erpc.yaml`:** ```yaml cors: allowedOrigins: - "https://*.example.com" allowCredentials: true ``` **TypeScript — `erpc.ts`:** ```typescript cors: { allowedOrigins: ["https://*.example.com"], allowCredentials: true, } ``` ### Request/response behavior - No `Origin` header → CORS is skipped entirely; no headers written, no metrics fired. [`erpc/http_server.go:L1010-1018`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1010-L1018) - Origin present → `erpc_cors_requests_total` incremented before allow/deny evaluation. [`erpc/http_server.go:L1020`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1020) - Allowed origin → `Access-Control-Allow-Origin` is set to the **echoed request origin**, never the literal `*`. [`erpc/http_server.go:L1053-1065`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1053-L1065) - Disallowed origin → no `Access-Control-*` headers; non-OPTIONS request continues to JSON-RPC processing; OPTIONS returns bare 204. [`erpc/http_server.go:L1035-1051`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1035-L1051) - OPTIONS + allowed origin → `erpc_cors_preflight_requests_total` incremented; response is HTTP 204; caller returns without JSON-RPC parsing. [`erpc/http_server.go:L1069-1075`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1069-L1075) - CORS for a project runs only when `cors` is configured; `cors: nil` means OPTIONS falls through to JSON-RPC body parsing and errors. [`erpc/http_server.go:L343-347`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L343-L347) - CORS for a project can only run after project resolution succeeds; an unknown project id → HTTP 404 with no CORS headers (browsers may surface this as a CORS error rather than a 404). [`erpc/http_server.go:L326-347`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L326-L347) - All pattern-match errors are logged at debug and the pattern is skipped — never panics. [`erpc/http_server.go:L1022-1033`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1022-L1033) ### Best practices - Always list `exposedHeaders` explicitly when your frontend reads any `X-ERPC-*` response header. The default produces `Access-Control-Expose-Headers: ""`, silently blocking browser JS access to all eRPC diagnostic headers: `X-ERPC-Cache`, `X-ERPC-Upstream`, `X-ERPC-Duration`, `X-ERPC-Attempts`, `X-ERPC-Upstream-Attempts`, `X-ERPC-Upstream-Retries`, `X-ERPC-Upstream-Hedges`, `X-ERPC-Network-Attempts`, `X-ERPC-Network-Retries`, `X-ERPC-Network-Hedges`, `X-ERPC-Consensus-Slots`, `X-ERPC-Consensus-Disputes`, `X-ERPC-Consensus-Low-Participants`, `X-ERPC-Cache-Attempts`, `X-ERPC-Cache-Retries`, `X-ERPC-Cache-Hedges`. ([`erpc/http_server.go:L1088-1204`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1088-L1204)) - Never use `allowedOrigins: ["*"]` with `allowCredentials: true`. eRPC will emit both headers; browsers reject the combination entirely. Use an explicit origin list when credentials are required. - Use the boolean OR pattern (`"https://app.example.com | https://staging.example.com"`) rather than two entries when combining origins — both forms work but the single-expression form is easier to audit. - Verify disallowed-origin behavior with `curl --header "Origin: https://evil.example.com" ...`. eRPC still returns a JSON-RPC response; only the browser enforces the block. CORS is not an access-control boundary — pair it with an [auth strategy](/config/auth.llms.txt) for real security. - Be aware that `.` in wildcard patterns matches any single character, not a literal dot. `allowedOrigins: ["https://erpc.cloud"]` also matches `https://erpcXcloud`. Prefer explicit origins in security-sensitive deployments. - Set `maxAge` to a higher value (e.g. `86400`) in production to reduce browser preflight frequency. The default of 3600 seconds is conservative. ### Edge cases & gotchas 1. **`.` matches any single character, not a literal dot.** `"https://erpc.cloud"` also matches `"https://erpcXcloud"`. No escape syntax exists. Review each pattern for unintended substitutions. Source: [`common/matcher.go:L34-47`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L34-L47) 2. **Disallowed origins are not rejected server-side.** Non-OPTIONS requests proceed and receive a full JSON-RPC response; only the browser enforces the block. Test with `curl` and `Origin: https://evil.example.com` to confirm. 3. **`exposedHeaders: nil` silently blocks all `X-ERPC-*` headers from browser JS.** `strings.Join(nil, ", ")` → `""`. Browser interprets as zero extra headers. eRPC writes these headers on every response (all blocked without an explicit list): `X-ERPC-Cache`, `X-ERPC-Upstream`, `X-ERPC-Duration`, `X-ERPC-Attempts`, `X-ERPC-Upstream-Attempts`, `X-ERPC-Upstream-Retries`, `X-ERPC-Upstream-Hedges`, `X-ERPC-Network-Attempts`, `X-ERPC-Network-Retries`, `X-ERPC-Network-Hedges`, `X-ERPC-Consensus-Slots`, `X-ERPC-Consensus-Disputes`, `X-ERPC-Consensus-Low-Participants`, `X-ERPC-Cache-Attempts`, `X-ERPC-Cache-Retries`, `X-ERPC-Cache-Hedges`. Enumerate by name — no wildcard shorthand is accepted by current browsers. Sources: [`erpc/http_server.go:L1057`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1057), [`erpc/http_server.go:L1088-1204`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1088-L1204) 4. **CORS metrics label `project` contains the URL path, not the project id.** The value passed for the `project` label at metric increment time is `r.URL.Path` (e.g. `/main/evm/1`). Cardinality grows with distinct request paths; you cannot group by project id from these counters alone. Source: [`erpc/http_server.go:L1020`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1020) 5. **`allowedOrigins` is required — explicit `cors:` block without it fails startup** with `*.cors.allowedOrigins is required`. The `["*"]` fallback only applies to auto-injected admin CORS. Source: [`common/validation.go:L773-775`](https://github.com/erpc/erpc/blob/main/common/validation.go#L773-L775) 6. **OPTIONS to a project without `cors` configured falls through to JSON-RPC parsing.** The `OPTIONS` early-return lives inside the `project.Config.CORS != nil` branch. Without `cors`, the request errors on body parsing rather than returning a clean 204. Source: [`erpc/http_server.go:L343-347`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L343-L347) 7. **`allowCredentials: true` with `allowedOrigins: ["*"]` is not rejected at startup**, only at browser runtime. eRPC will send the conflicting headers; browsers refuse the response with a CORS error. Validate this combination manually. 8. **CORS is not a security boundary.** Any client that omits `Origin` bypasses CORS entirely. For real access control use [auth strategies](/config/auth.llms.txt) or [rate limiters](/config/rate-limiters.llms.txt). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cors_requests_total` | counter | `project` (URL path), `origin` | Every request that carries an `Origin` header, before allow/deny | | `erpc_cors_preflight_requests_total` | counter | `project` (URL path), `origin` | Allowed-origin OPTIONS preflight only | | `erpc_cors_disallowed_origin_total` | counter | `project` (URL path), `origin` | Origin present but no pattern matched | Note: the `project` label value is `r.URL.Path` (e.g. `/main/evm/1`), not the project id. Cardinality scales with distinct request paths. ### Source code entry points - [`erpc/http_server.go:L1008-L1077`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1008-L1077) — `handleCORS`: full algorithm; no-origin fast path, wildcard matching loop, header writing, 204 preflight termination - [`common/config.go:L658-L665`](https://github.com/erpc/erpc/blob/main/common/config.go#L658-L665) — `CORSConfig` struct definition - [`common/defaults.go:L2824-L2846`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2824-L2846) — `CORSConfig.SetDefaults`: method/header defaults, `allowCredentials` false, `maxAge` 3600 - [`common/validation.go:L773-L775`](https://github.com/erpc/erpc/blob/main/common/validation.go#L773-L775) — `CORSConfig.Validate`: `allowedOrigins` required check - [`common/matcher.go:L34-L47`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L34-L47) — `WildcardMatch` tokenizer including the `.` = any-char rule - [`common/defaults.go:L769-L787`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L769-L787) — admin CORS auto-injection (`allowedOrigins: ["*"]`) - [`erpc/http_server_test.go:L3239-L3376`](https://github.com/erpc/erpc/blob/main/erpc/http_server_test.go#L3239-L3376) — CORS allowed/disallowed/preflight test suite ### Related pages - [Auth](/config/auth.llms.txt) — the correct tool for access control; pair with CORS to stop real attackers, not just browsers. - [Rate limiters](/config/rate-limiters.llms.txt) — per-IP or per-user limits complement CORS for public-facing projects. - [Projects overview](/config/projects.llms.txt) — full per-project config including method filtering, auth strategies, and rate-limit budgets. - [Server config](/config/server.llms.txt) — domain aliasing rules that pre-select a project via `Host` header, evaluated before CORS runs. --- --- # Networks > Source: https://docs.erpc.cloud/config/projects/networks > One entry per chain — eRPC routes every request to the right upstreams, caches results, and retries failures, all without touching your code. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Networks A **network** is one chain inside a project. Declare it once and eRPC owns the whole pipeline: smarter caching, automatic failover, and in-flight deduplication — on every chain you touch. Three things make it ergonomic: **zero-config chains** bootstrap automatically from your providers on first request, **`networkDefaults`** lets one block set shared policy for every chain, and a human-readable **`alias`** replaces `evm/42161` in every URL. **What you get:** - Any EVM chain or SVM (Solana) cluster, any provider — routes automatically on first request. - One `networkDefaults` block replaces repetitive per-chain config. - `alias: arbitrum` turns every URL into `/main/arbitrum` instead of `/main/evm/42161`. - Static canned replies for chains with non-standard genesis blocks. - In-flight deduplication so 100 identical concurrent requests cost you one upstream call. ## Quick taste Illustrative, not a tuned production config — declare Ethereum with a human-readable alias: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 1 # human-readable alias replaces evm/1 in every URL and metric label alias: ethereum ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, // human-readable alias replaces evm/1 in every URL and metric label alias: "ethereum", }], }] ``` ## Future-block polling Clients that follow a chain by number (for example rollup nodes reading L1) poll `eth_getBlockByNumber` for the block after the head and treat `null` as "not produced yet". No upstream has that block, so each one returns `null` in turn and every poll walks every routed upstream, fallbacks included. Enable `shortCircuitFutureBlocks` to return `null` for a numbered `eth_getBlockByNumber` above the latest head of every upstream of the network (static availability caps included), without dispatching it. A block at or below the last head any upstream reported is still dispatched, and the request is dispatched as usual while any upstream's head is unknown. Only this flag turns it on. **yaml:** ```yaml filename="erpc.yaml" projects: - id: main networks: - architecture: evm evm: chainId: 1 # Returns null for eth_getBlockByNumber(N) when N is above every # upstream's head, instead of asking each upstream. # default: false shortCircuitFutureBlocks: true ``` **typescript:** ```ts filename="erpc.ts" export default createConfig({ projects: [ { id: "main", networks: [ { architecture: "evm", evm: { chainId: 1, // Returns null for eth_getBlockByNumber(N) when N is above every // upstream's head, instead of asking each upstream. // default: false shortCircuitFutureBlocks: true, }, }, ], }, ], }); ``` The head is what eRPC last saw from the state poller and head subscriptions. A block an upstream produced after that gets `null` until eRPC sees it, so a client that learned of the block elsewhere (for example from the node's own `newHeads`) can briefly get `null` for a block that exists. Only enable it where heads arrive promptly, such as networks with WebSocket head subscriptions, and where clients retry a `null`. ## Failover By default a request only reaches the upstreams the [selection policy](/config/projects/selection-policies.llms.txt) currently routes to; upstreams tagged `tier:fallback` join once the policy promotes them, which happens on its evaluation interval. `failover.onDefaultsExhausted` adds a per-request escape for the moments before that: when every routed upstream failed with an error that another upstream might not repeat, the same request is retried once on the `tier:fallback` upstreams it has not tried yet — even while the policy still keeps them cordoned. **yaml:** ```yaml filename="erpc.yaml" projects: - id: main networkDefaults: failover: onDefaultsExhausted: true # default: false upstreams: - endpoint: https://primary.example.com - endpoint: https://backup.example.com tags: ["tier:fallback"] ``` **typescript:** ```ts filename="erpc.ts" export default createConfig({ projects: [ { id: "main", networkDefaults: { failover: { onDefaultsExhausted: true }, // default: false }, upstreams: [ { endpoint: "https://primary.example.com" }, { endpoint: "https://backup.example.com", tags: ["tier:fallback"] }, ], }, ], }); ``` The escape: - escalates only on errors that are retryable toward the network — an error every upstream would return (e.g. an execution revert) is returned as-is; - treats an empty result as a miss only for a concrete block number the network should already have (see `evm.emptyResultConfidence`), so polling for a pending transaction receipt does not sweep the fallbacks; - skips fallbacks whose circuit breaker is open for the method, or that don't handle the method; - fires at most once per request, and never for consensus requests; - is counted in `erpc_network_fallback_escape_total{project,network,category}` — expect zero in steady state. The validation report warns when `onDefaultsExhausted` is enabled but no upstream is tagged `tier:fallback`. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add multiple chains with shared policy** ```text I'm running eRPC for several EVM chains and want to declare Ethereum mainnet, Arbitrum, and Base in a single project. Set human-readable aliases (e.g. "ethereum", "arbitrum", "base"), share a common rate-limit budget and failsafe via networkDefaults, and keep per-chain blocks minimal. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/projects/networks.llms.txt ``` **Prompt Example #2: tune getLogs limits and splitting** ```text My eRPC instance is hitting "block range too large" errors from upstreams on eth_getLogs. Adjust getLogsMaxAllowedRange for my Ethereum mainnet network, enable automatic range splitting on errors, and set a safe concurrency cap so sub-requests don't flood the provider. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/networks.llms.txt ``` **Prompt Example #3: serve latest only once most upstreams have it** ```text My clients occasionally get "block not found" right after asking for "latest", because the served tip is a block only two of my upstreams have. Set servedTip.quorum on my production chains so "latest" is a block a majority of upstreams already has. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/networks.llms.txt ``` **Prompt Example #4: disable validation for a non-standard chain** ```text I'm adding zkSync Era to eRPC and eth_getBlockByNumber responses from zkSync use a non-standard transactionsRoot — the data-integrity module is rejecting them. For the zkSync network only, make sure data-integrity is off (or disable the transactionsRoot checks via the integrity block) without touching the global policy. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/networks.llms.txt ``` **Prompt Example #5: debug 503 on a newly added chain** ```text I added a new chain to eRPC's networks list but requests are returning HTTP 503 with ErrNetworkInitializing. Walk me through what the bootstrap task does, what conditions produce 503 vs 404, and which config keys to check first (providers, onlyNetworks/ignoreNetworks, rateLimitBudget). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/networks.llms.txt ``` --- ### Networks — full agent reference ### How it works **Architecture concept.** `NetworkArchitecture` is a string enum with two valid values: `"evm"` and `"svm"` ([`common/network.go:L14-17`](https://github.com/erpc/erpc/blob/main/common/network.go#L14-L17)). The canonical id is `evm:` from `util.EvmNetworkId`, or `svm:` / `svm::` from `util.SvmNetworkId` ([`util/ids.go:L1-30`](https://github.com/erpc/erpc/blob/main/util/ids.go#L1-L30)). The `network` Prometheus label equals the alias when set, otherwise the raw id. `architecture` is inferred when omitted: a network carrying an `svm` block derives `architecture: svm`, one carrying `evm` (or neither) derives `evm` ([`common/defaults.go:L2010-2028`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2010-L2028)). Declaring `architecture: svm` auto-creates an empty `svm` block, and `networkDefaults.evm` is never injected into an SVM network. See [SvmNetworkConfig](#projectsnetworkssvm--svmnetworkconfig) below and the [SVM reference pages](/reference/svm/commitment.llms.txt). **Lazy creation.** `NetworksRegistry.GetNetwork` fast-paths a `sync.Map` lookup; on miss it validates the id format and schedules a bootstrap task. The task: (1) resolves or synthesizes a `NetworkConfig` and runs `SetDefaults` so it inherits `networkDefaults` exactly like static networks; (2) calls `PrepareUpstreamsForNetwork` — fans out to every configured provider, polls 200 ms for up to 30 s until ≥1 upstream is ready; (3) wires the cache DAL; (4) registers with the selection-policy engine. Statically-declared networks bootstrap in background at startup through the same machinery; a failed eager bootstrap is retried when the first request arrives. **Forward pipeline order** (exact sequence, `erpc/networks.go:L931-1603`): 1. Apply `directiveDefaults` + start OTel span. 2. **Static response** match — returns immediately if hit (before multiplexer, cache, upstreams). 3. **Multiplexer** — leader/follower on `CacheHash`; followers copy the leader's response. 4. **Cache read** — non-null hit closes the mux and returns. 5. **Policy-engine upstream ordering** — falls back to registration order if empty; `ErrNoUpstreamsFound` (404) if still empty. 6. EVM pre-forward hook (future-block short-circuit; never cached). 7. Stateful-method guard, network rate-limit, request normalization. 8. **Failsafe executor selection** — first config-order entry matching method + finality. 9. **Upstream sweep** — per-upstream block-availability gate, hedge/retry orchestration. 10. Post-sweep: timeout translation, last-valid-response fallback, async cache set, misbehavior accounting. **networkDefaults inheritance** (`common/defaults.go:L1781-1973`). "Network wins; defaults fill gaps." Scalars inherit when zero-valued; pointers when nil. `selectionPolicy` and `directiveDefaults` are whole-struct copies (no per-field merge). `evm` is a whole-struct copy when absent from the network, otherwise per-field fill for 14 named fields. Failsafe: if the network has entries, each is matched against the first compatible default (wildcard method + finality) and missing sub-fields are inherited; if the network has no entries the defaults list is deep-copied wholesale. **Finality classification** (`Network.GetFinality`). Explicit `finalized`/`realtime` flags in `methods.definitions` win. Otherwise the block ref/number is extracted from the request, then from the response body (for hash-keyed cache hits). Non-numeric tags → `realtime`; a numbered block is finalized when it is at or below the request's `Head.Finalized`. An upstream's answer is finalized, and so cached permanently, only when that upstream has also finalized the block and is not on a minority fork. An upstream without a `finalized` tag reports latest minus the derived finality depth (`fallbackFinalityDepth`, at least 30 minutes of chain). **Served tip.** Both axes advertise the highest block that `servedTip.quorum` of the network's voters already have, per process and with no stored pick; the rule, benching, guard and floors are in [Block tracking & served tip](/reference/evm/block-tracking.llms.txt#served-tip). A `use-upstream` selector scopes the pick to its matched upstreams and may get its own [lane](/reference/lanes.llms.txt). ### Config schema #### `projects[].networks[]` — NetworkConfig | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `architecture` | `string` (`evm` \| `svm`) | Inferred from the sub-block: `svm` present → `"svm"`, otherwise `"evm"` ([`common/defaults.go:L2010-2028`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2010-L2028)) | Both `evm` and `svm` are valid ([`common/network.go:L82-88`](https://github.com/erpc/erpc/blob/main/common/network.go#L82-L88)). Required by validation. | | `evm` | `EvmNetworkConfig` | Auto-created empty struct for EVM networks ([`common/defaults.go:L1914-1916`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1914-L1916)); never injected into an SVM network | See EvmNetworkConfig table below. | | `svm` | `SvmNetworkConfig` | Auto-created empty struct when `architecture: svm` ([`common/defaults.go:L2026-2028`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2026-L2028)) | Required for SVM networks — `network.*.svm is required for svm networks` otherwise. See SvmNetworkConfig table below. | | `alias` | `string` | `""` | Charset `[a-zA-Z0-9_-]+` ([`common/validation.go:L1264-1269`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1264-L1269)); unique per project ([`common/validation.go:L622-627`](https://github.com/erpc/erpc/blob/main/common/validation.go#L622-L627)). Used as the `network` metric label via `Network.Label()` ([`erpc/networks.go:L278-286`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L278-L286)). Aliases work in URL path only — not in body `networkId`. | | `cacheKeySuffix` | `string` | `""`; inherits `networkDefaults.cacheKeySuffix` when empty ([`common/defaults.go:L2107-2109`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2107-L2109)) | Inserted into the JSON-RPC cache partition key as `{networkId}:{suffix}:{blockRef}` so two networks that share a chainId and a Redis do not collide. Empty keeps `{networkId}:{blockRef}`. Charset `[a-zA-Z0-9_-]+` (same as alias); `:` is rejected. Not unique — many networks may share `systx`. When `{networkId}:{suffix}` is itself a valid network id (`svm:` plus a suffix), colons in the network id are escaped so that partition cannot be read as the longer network; unsuffixed keys and EVM suffixed keys are unchanged. Reverse-index wildcard is `{networkId}:{suffix}:*` (same helper as the main key), so hash-keyed / tag reads are isolated even when the block ref contains `:`. | | `maxClientBatchSize` | `*int` | unset (`0` and unset both mean no limit); inherits `networkDefaults.maxClientBatchSize` when unset ([`common/defaults.go:L2242-2245`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2242-L2245)) | Most requests one client JSON-RPC batch may address to this network. Over it, **none** of the batch runs and no upstream is called: the reply is one error object, `id: null`, code `-32600`, message `batch of N requests to network X exceeds the limit of M (maxClientBatchSize)`; HTTP **400**, or **200** on Solana networks — the same status as any other invalid request body ([`erpc/http_server.go:L568-586`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L568-L586)). A batch with a network in its URL path counts every element; a path-less batch counts, per network, only the elements whose `networkId` names it, and is refused when any one network's limit is exceeded ([`erpc/http_server.go:L1879-1923`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1879-L1923)). Applies to WebSocket batches on the connection's network too ([`erpc/ws_server.go:L441-447`](https://github.com/erpc/erpc/blob/main/erpc/ws_server.go#L441-L447)). Distinct from upstream `jsonRpc.batchMaxSize`, which only shapes the batches eRPC itself sends. Negative → config error. | | `rateLimitBudget` | `string` | `""` (none); inherits `networkDefaults.rateLimitBudget` when empty ([`common/defaults.go:L1783-1785`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1783-L1785)) | Must reference an existing budget. Enforced per-request before upstream contact → `ErrNetworkRateLimitRuleExceeded`. | | `failsafe[]` | `[]FailsafeConfig` | `nil`; inherited/merged from `networkDefaults.failsafe` | One `networkExecutor` per entry + a no-op catch-all ([`erpc/networks_registry.go:L115-138`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L115-L138)). Selection: first config-order match on `matchMethod` wildcard + `matchFinality` ([`erpc/networks.go:L907-929`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L907-L929)). Old single-object YAML auto-converted to a one-element list with `matchMethod: "*"`. | | `selectionPolicy` | `SelectionPolicyConfig` | `nil`; inherited wholesale from `networkDefaults.selectionPolicy` when nil ([`common/defaults.go:L1833-1836`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1833-L1836)) | Auto-attached when any upstream has tag `tier:fallback` ([`common/defaults.go:L1932-1940`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1932-L1940)). See [Selection & scoring](/config/projects/selection-policies.llms.txt). | | `directiveDefaults` | `DirectiveDefaultsConfig` | Always materialized ([`common/defaults.go:L1947-1950`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1947-L1950)); inherited wholesale from `networkDefaults.directiveDefaults` when nil ([`common/defaults.go:L1837-1840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1837-L1840)) | **Footgun**: a network that sets ANY `directiveDefaults` field ignores `networkDefaults.directiveDefaults` entirely — no per-field merge. Applied at request start ([`erpc/networks.go:L937`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L937)). | | `multiplexing` | `*bool` | `nil` = enabled ([`common/config.go:L2034-2039`](https://github.com/erpc/erpc/blob/main/common/config.go#L2034-L2039)); inherits `networkDefaults.multiplexing` when nil ([`common/defaults.go:L1841-1844`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1841-L1844)) | Gates in-flight identical-request dedup. **Footgun**: legacy single-object `networkDefaults.failsafe` YAML drops this field silently (old struct has no `Multiplexing` field, [`common/config.go:L626-655`](https://github.com/erpc/erpc/blob/main/common/config.go#L626-L655)). | | `staticResponses[]` | `[]StaticResponseConfig` | `nil` | Checked before multiplexer, cache, upstreams ([`erpc/networks.go:L976-981`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L976-L981)). See [Static responses](/config/projects/static-responses.llms.txt). | | `staticResponses[].method` | `string` | required | Exact JSON-RPC method name; case-sensitive string equality ([`common/validation.go:L1282-1284`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1282-L1284)). | | `staticResponses[].params` | `[]any` | `nil` | `nil` and `[]` are interchangeable in matching (both have `len==0`). YAML `params: []` deserializes to non-nil empty slice; omitted `params:` deserializes to nil — both match requests with zero params. Hex strings (`"0x0"` vs `"0x00"`) are NOT normalized — exact string match only. Declaration order matters: first match wins. | | `staticResponses[].response.result` | `any` | — | Exactly one of `result` or `error` must be set; both or neither → startup error. | | `staticResponses[].response.error.code` | `int` | `0` | No minimum/maximum enforced. **Footgun**: code `0` passes validation but is omitted from the wire JSON (`json:"code,omitempty"` on `int`, [`common/errors.go:L2226`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2226)). Always set a non-zero code in production. | | `staticResponses[].response.error.message` | `string` | required when error set | Non-empty string required; `Validate()` returns `"response.error.message is required"` otherwise. | | `staticResponses[].response.error.data` | `any` | `nil` | Optional arbitrary extra data; omitted from JSON when nil. | | `methods.preserveDefaultMethods` | `bool` | `false` | **Critical footgun**: `false` + any `definitions` entries → ALL built-in methods (hundreds, including `eth_call`, `eth_getLogs`) are silently replaced by only your custom entries plus stateful markers. `false` + no `definitions` → all built-ins kept (same as omitting the block). `true` + any `definitions` → built-ins copied first, then user entries merged on top ([`common/defaults.go:L493-576`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L493-L576)). | | `methods.definitions` | `map[string]CacheMethodConfig` | Full built-in table ([`common/defaults.go:L493-528`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L493-L528)) | Per-method fields: `finalized`, `realtime`, `stateful`, `reqRefs`, `respRefs`, `translateLatestTag`, `translateFinalizedTag`, `enforceBlockAvailability`. | | `methods.definitions..finalized` | `bool` | `false` (true for static-cache methods) | **Footgun**: setting `true` on a non-finalized method (e.g. `eth_getBalance`) permanently caches ALL responses from that method with long/permanent TTL — a severe data-correctness bug ([`erpc/networks.go:L1656-1660`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1656-L1660)). | | `methods.definitions..realtime` | `bool` | `false` (true for `eth_blockNumber` and similar) | Forces `GetFinality` → `Realtime`; responses use the realtime cache policy (short TTL). | | `methods.definitions..stateful` | `bool` | `true` for `DefaultStatefulMethodNames`, else `false` | **Footgun**: `stateful: false` on any of the 6 built-in stateful methods (`eth_newFilter`, `eth_newBlockFilter`, `eth_newPendingTransactionFilter`, `eth_getFilterChanges`, `eth_getFilterLogs`, `eth_uninstallFilter`) is silently overridden to `true` with no warning ([`common/defaults.go:L512-519`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L512-L519)). | | `methods.definitions..translateLatestTag` | `*bool` | `nil` = enabled for every method, `eth_getBlockByNumber` included; `false` for `arbtrace_*` | `nil`/`true` → `"latest"` (plain, EIP-1898 leaf, or an absent selector) replaced with the request's `Head.Latest` before forwarding and cache keying, so `eth_getBlockByNumber("latest")` answers the block `eth_blockNumber` reports. `false` → the tag reaches upstreams as is, an absent selector as the literal `"latest"`, and the method leaves the one-number promise: its answer may name a different block than `eth_blockNumber`, and it is not cached. `arbtrace_*` ship with `false`: Arbitrum classic nodes serve them, and their latest is not the network's; their absent params stay absent ([`common/config.go:L307-309`](https://github.com/erpc/erpc/blob/main/common/config.go#L307-L309)). | | `methods.definitions..translateFinalizedTag` | `*bool` | `nil` = enabled | Same as `translateLatestTag` for the `"finalized"` tag ([`common/config.go:L310-312`](https://github.com/erpc/erpc/blob/main/common/config.go#L310-L312)). | | `methods.definitions..enforceBlockAvailability` | `*bool` | `nil` (inherit) | Per-method override; highest priority in the 5-step enforcement chain ([`erpc/networks.go:L1806-1813`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1806-L1813)). | #### `projects[].networks[].evm` — EvmNetworkConfig | Field | Type | Default | Notes | |---|---|---|---| | `chainId` | `int64` | — (no default) | Drives `networkId = "evm:"`. Not validated > 0 for networks; `chainId: 0` yields `evm:0`. | | `fallbackFinalityDepth` | `int64` | `1024` ([`common/defaults.go:L1975`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1975)) | Used when an upstream doesn't expose the `finalized` tag: its finalized is latest minus the deeper of this and 30 minutes of chain, counted at the block time floor so a cold-start estimate never shortens it. Must be > 0 after defaults. | | `fallbackStatePollerDebounce` | `Duration` | unset | Set: the block-polling debounce until the block time is learned. Unset: the 1s cold block time × `dynamicBlockTimeDebounceMultiplier` (0.7s). | | `dynamicBlockTimeDebounceMultiplier` | `*float64` | `0.7` ([`common/defaults.go:L1977`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1977)) | Polling debounce = EMA block time × multiplier. Lower → more aggressive polling (fresher data, more upstream load). | | `finalizedDebounceDepthMultiplier` | `*float64` | `0.05` ([`common/defaults.go:L2446`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2446)) | Finalized-poll debounce = (latest − finalized) × EMA block time × multiplier, when longer than the regular debounce. `0` disables it. | | `blockUnavailableDelayMultiplier` | `*float64` | `1.0` ([`common/defaults.go:L1978`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1978)) | Retry delay for block-unavailable = EMA block time × multiplier. | | `enforceBlockAvailability` | `*bool` | `nil` (defer; fallback = enabled) | Network-level priority 2 in 5-step chain. `nil` defers to upstream bounds and system defaults. `false` disables enforcement even when an upstream has explicit bounds configured. | | `maxRetryableBlockDistance` | `*int64` | `nil` → `128` at use site ([`erpc/networks.go:L1973-1979`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1973-L1979)) | Block-unavailable errors within this distance of upstream head are retryable; beyond → non-retryable skip. | | `getLogsMaxAllowedRange` | `int64` | `30_000` ([`common/defaults.go:L2092-2094`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2092-L2094)) | Hard limit on `eth_getLogs` block range. Must be > 0; `0` inherits defaults value. | | `getLogsMaxAllowedAddresses` | `int64` | `0` = unlimited | Enforced only when > 0 ([`architecture/evm/eth_getLogs.go:L212`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L212)). | | `getLogsMaxAllowedTopics` | `int64` | `0` = unlimited | Enforced only when > 0. | | `getLogsSplitOnError` | `*bool` | `true` ([`common/defaults.go:L2095-2097`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2095-L2097)) | Retry by bisecting range on "too many results" errors. | | `getLogsSplitConcurrency` | `int` | `10` ([`common/defaults.go:L2098-2100`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2098-L2100)) | Parallelism cap for split sub-requests. | | `traceFilterSplitOnError` | `*bool` | `nil` = **off** (deliberate opt-in, [`common/defaults.go:L2102-2104`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2102-L2104)) | Opt-in bisecting for `trace_filter`/`arbtrace_filter`. | | `traceFilterSplitConcurrency` | `int` | `10` ([`common/defaults.go:L2105-2107`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2105-L2107)) | Parallelism cap for trace-filter splits. | | `idempotentTransactionBroadcast` | `*bool` | `nil` = **enabled** ([`architecture/evm/eth_sendRawTransaction.go:L27-36`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L27-L36)) | "Already known"/"nonce too low"-verified errors become success-with-tx-hash, making retry/hedge safe for `eth_sendRawTransaction`. | | `markEmptyAsErrorMethods` | `[]string` | `eth_blockNumber`, `eth_getBlockByNumber`, `eth_getTransactionByHash`, and 8 others ([`common/defaults.go:L2044-2057`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2044-L2057)) | Methods where empty response = error (retried, upstream scored down). `eth_getTransactionReceipt` deliberately excluded. | | `localAnswers` | `map[string]bool` | all on | Methods eRPC answers itself: `eth_chainId`, `net_version`, `net_listening`, `net_peerCount`, `web3_clientVersion`, `eth_syncing`. `false` routes that method to the upstreams with no eRPC answer. Other keys fail validation. [Local answers](/reference/evm/method-handlers.llms.txt#local-answers). | | `emptyResultConfidence` | `blockHead` \| `finalizedBlock` | `blockHead` ([`common/defaults.go:L2075-2079`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2075-L2079)) | How confirmed a block must be for empty point-lookups to be retried as missing data. | | `shortCircuitFutureBlocks` | `*bool` | `nil` = **off**; inherited from `networkDefaults.evm` ([`common/defaults.go:L2288-2290`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2288-L2290)) | Returns `null` for a numbered `eth_getBlockByNumber` above the highest latest head across every upstream of the network (static caps included; selection policy, tier and syncing state ignored), without dispatching. Fails open while any upstream's head is unknown. Uses latest heads regardless of `emptyResultConfidence`. Only an explicit `true` enables it ([`common/config.go:L2780-2789`](https://github.com/erpc/erpc/blob/main/common/config.go#L2780-L2789)). Does not change what `latest` resolves to. | | `safeBlockSource` | `string` (upstream selector) | `""` = inherit or provider-defined routing | Routes standard block-tagged JSON-RPC requests carrying `safe` to matching upstreams and skips cache reads. The tag stays verbatim so those upstreams define both height and hash. Operator routing overrides client `use-upstream`; retry/consensus still applies inside the matching pool. An empty network value inherits `networkDefaults.evm.safeBlockSource` when present. Does not affect `eth_query*` or direct gRPC Query APIs. | | `evm.integrity.enforceHighestBlock` | `*bool` | `true` ([`common/defaults.go:L2117-2120`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2117-L2120)) | **Deprecated** — migrated into `directiveDefaults.enforceHighestBlock` at `SetDefaults` time when the directive is unset ([`common/defaults.go:L1952-1966`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1952-L1966)). Prefer `directiveDefaults.enforceHighestBlock`. | | `evm.integrity.enforceGetLogsBlockRange` | `*bool` | `true` ([`common/defaults.go:L2121-2123`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2121-L2123)) | **Deprecated** — same migration path as `enforceHighestBlock`. | | `evm.integrity.enforceNonNullTaggedBlocks` | `*bool` | `true` ([`common/defaults.go:L2124-2126`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2124-L2126)) | **Deprecated** — same migration path. | | `maxFutureBlockRetryDistance` | `*int64` | `nil` | **Deprecated** — warned about and set to nil in `SetDefaults` ([`common/defaults.go:L2080-2083`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2080-L2083)). Has no effect; remove from configs. | | `servedTip` | `EvmServedTipConfig` | `nil` = the defaults below | Copied wholesale from `networkDefaults.evm.servedTip` when nil. Tunes the [served-tip rule](/reference/evm/block-tracking.llms.txt#served-tip), which runs either way ([`common/config.go:L2812-2855`](https://github.com/erpc/erpc/blob/main/common/config.go#L2812-L2855)). | | `servedTip.quorum` | `int` ≥ 1 \| `"majority"` | `2` | Voters that must already have a block before it is served; capped at the voter count. `"majority"` = `floor(N/2)+1`. Other values fail config load ([`common/served_tip.go:L36-68`](https://github.com/erpc/erpc/blob/main/common/served_tip.go#L36-L68)). | | `servedTip.maxRegressionBlocks` | `int64` | `0` = max(1024, 2 × typical finality step) | Tolerance of the [regression guard](/reference/evm/block-tracking.llms.txt#regression-guard) below the corroborated live head. An explicit value wins over the learned one. `-1` disables; other negatives fail validation. | | `servedTip.guaranteedMethods` | `[]string` (glob) | `[]` | Methods whose supporting upstreams must be able to serve the tip ([guarantee subsets](/reference/evm/block-tracking.llms.txt#guarantee-subsets)). Patterns validated at load. | | `servedTip.guaranteedFor` | `[]string` (selector) | `[]` | Upstream groups (id/tag selector) that must be able to serve the tip ([guarantee subsets](/reference/evm/block-tracking.llms.txt#guarantee-subsets)). Selectors validated at load. | | `servedTip.followCacheHead` | `bool` | `false` | Lowers the `latest` a network-wide read takes to the newest block the cache serves, while its realtime policy's TTL admits that block's age, and keeps `finalized` at or below it ([cache-head anchor](/reference/evm/block-tracking.llms.txt#cache-head-anchor)). Never raises `latest`; the chain tracker and every stream (`newHeads`, gRPC, taps) never see it. Needs a realtime cache policy with a TTL on a head-aware connector (`grpc` driver) serving `eth_getBlockByNumber("latest")`; without one a warning is logged and reads are not anchored. | | `servedTip.enabledFor` | — | — | **Removed**; configs that set it fail to load. Use `servedTip.quorum: majority` (with ≤ 3 voters the default quorum already serves the same block). If it listed `latest`, also set `shortCircuitFutureBlocks: true`, which it used to turn on. | | `servedTip.clusterDelta`, `servedTip.trajectoryWindow` | — | — | **Removed**; configs that set them fail to load. Delete them; benching replaces the trajectory referee. | | `chainTracker` | `EvmChainTrackerConfig` | the defaults below | The network's [chain tracker](/operation/websocket.llms.txt#how-heads-reach-subscribers): one canonical chain for ws subscriptions, gRPC `StreamBlocks` and the integrity follow tap. | | `chainTracker.reorgWindow` | `int` | `32` | Floor of the held window in blocks, the window of use-upstream group trackers, and the deepest reorg a tracker walks and replays. Raise it for deep-reorg chains (Polygon: `256`). A ws `logs` subscription that falls `reorgWindow` × block time behind closes with `1013`. | | `chainTracker.maxBackfill` | `Duration` | `5m` | Chain time, compared on header timestamps, the network-wide tracker holds for resuming gRPC `StreamBlocks` clients. A cursor older than this ends with `OUT_OF_RANGE`. | | `stripSubscribeFromBlockZero` | — | — | **Removed**; configs that set it fail to load. No upstream `logs` subscription is made. | | `integrity.reorgWindow`, `integrity.follow.maxBlocksPerTick` | — | — | **Removed** at project, network and profile level; configs that set them fail to load. Use `evm.chainTracker.reorgWindow` and `evm.chainTracker.maxBackfill`; the follow tap is driven by the confirmed head. | #### `projects[].networks[].svm` — SvmNetworkConfig | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `cluster` | `string` | `""` (required) | The cluster these upstreams serve — `mainnet-beta`, `devnet`, `testnet`, or a fork's own cluster name. Together with `chain` it forms the network id. **This is network identity** (the SVM analogue of `evm.chainId`) and is therefore **not** inherited from `networkDefaults.svm`. | | `chain` | `string` | `""` → treated as `"solana"` | Which SVM chain this network runs on. Set it explicitly for forks and variants (`fogo`, `eclipse`) so several SVM chains can be hosted side by side without network-id or cache-key collisions. Inherited from `networkDefaults.svm.chain`. | | `commitment` | `string` | `""` — **no default** | One of `finalized`, `confirmed`, `processed`. When unset nothing is injected and each node applies its own default (Solana's is `finalized`), so a deviating vendor can disagree on identical requests. Serving and routing assume that documented default; cacheability stays stricter — unpinned slot-addressed reads classify `unfinalized`. Setting it pins one level across the pool so the cache and consensus compare like-for-like. Details: [Commitment & finality](/reference/svm/commitment.llms.txt). | | `statePollerDebounce` | Duration | `400ms` (one slot) ([`common/defaults.go:L2617-2619`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2617-L2619)) | Pool/network default minimum interval between poll fan-outs of an upstream's slot/health view when that upstream does not set `upstreams[*].svm.statePollerDebounce`. A **gate**, not the ticker period — the ticker stays pinned at 400 ms, so values below it have no effect. Raising it widens the `getBlock` availability guard's staleness margin proportionally. Per-upstream override: see [Upstreams](/config/projects/upstreams.llms.txt). | | `skipProcessedSlotProbe` | `bool` | `false` (poll) ([`common/config.go:L2867-2874`](https://github.com/erpc/erpc/blob/main/common/config.go#L2867-L2874)) | When `true`, skips the poller's `getSlot(processed)` probe and lets the finalized probe double-feed `LatestSlot` — one fewer call per poll. **Only safe on chains that finalize within ~1 slot of the processed tip** (Alpenglow); on a ~32-slot-gap chain (TowerBFT) it silently shifts the shred-lag cordon and availability windows by that gap. An opt-in `true` in `networkDefaults.svm` is inherited ([`common/defaults.go:L2600-2606`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2600-L2606)). | | `maxFinalizedSlotLag` | `*int64` | `100` slots ≈ 40 s ([`common/defaults.go:L2620-2628`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2620-L2628)) | Bounds how far an upstream's finalized slot may trail the pool reference before it is excluded from **consensus voting on finalized data**. Applied only when a consensus policy is active AND the request's resolved finality is `Finalized`. **Tri-state**: omitted → `100`; explicit `0` → filter **disabled**; `>0` → that value. The field is a pointer precisely so an explicit `0` is distinguishable from "unset" — a plain integer would collapse the two and make the documented disable switch unreachable. | | `enforceBlockAvailability` | `*bool` | `nil` → `true` (materialized at read time by `SvmEnforceBlockAvailability()`, [`erpc/networks.go:L1487-1494`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1487-L1494)) | Gates the `getBlock`/`getConfirmedBlock` guard that short-circuits requests for slots above the pool's highest indexed slot, saving quota and firing the indexing-lag retry immediately, **and** any operator-declared `upstreams[*].svm.blockAvailability` window. It does **not** enable a history-floor skip by itself: the floor (`getBlocksWithLimit(0, 1)`) is probed for every upstream but gates only a declared `firstAvailableSlotPlus` bound, and there is no always-on floor or pool-level `-32009`. Set `false` when shred-insert tracking is unavailable or unreliable on a deployment. An explicit `false` in `networkDefaults.svm` **is** honored. | Not present on `SvmNetworkConfig`: there is no `maxSlotsPerSignaturesQuery`. An early design proposed one as an analogue of EVM's `getLogs` range cap, but `getSignaturesForAddress` is bounded by signature cursors (`before`/`until`), not by a slot range, so the key described semantics Solana does not have and was removed. `minContextSlot` is a node-freshness floor — the minimum bank slot at which a request may be *evaluated* — not a lower bound on returned history, so it cannot serve as a range cap either. **Cluster and genesis-hash validation.** Known `(chain, cluster)` pairs — currently Solana `mainnet-beta`, `devnet`, and `testnet` — have their genesis hash validated at bootstrap by a single `getGenesisHash` call compared against a hardcoded table. Both a mismatch and a *fetch failure* fail the upstream, so a node mis-pointed at the wrong cluster never joins the pool. For unknown clusters (forks, private clusters) the same check runs only when the upstream sets `svm.checkGenesisHash: true`. `getGenesisHash` itself is then answered from the table with no upstream round-trip, mirroring EVM's `eth_chainId` short-circuit. #### `projects[].networks[].directiveDefaults` — DirectiveDefaultsConfig | Field | Type | Default | |---|---|---| | `retryEmpty` | `*bool` | `nil` | | `retryPending` | `*bool` | `nil` | | `skipCacheRead` | `bool\|string` | `nil` | | `useUpstream` | `*string` | `nil` | | `skipInterpolation` | `*bool` | `nil` | | `skipConsensus` | `*bool` | `nil` | | `enforceHighestBlock` | `*bool` | **`true`** ([`common/defaults.go:L1458-1460`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1458-L1460)) | | `enforceGetLogsBlockRange` | `*bool` | **`true`** ([`common/defaults.go:L1461-1463`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1461-L1463)) | | `enforceNonNullTaggedBlocks` | `*bool` | **`true`** ([`common/defaults.go:L1464-1466`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1464-L1466)) | > **Data-integrity validation** is configured under `networks[].integrity` (not `directiveDefaults`) — an opt-in `level`/`checks`/`profiles` block. The deprecated per-check flags (`validateLogsBloomMatch`, `enforceLogIndexStrictIncrements`, `validateTransactionsRoot`, …) are translated into it at startup. See [Integrity checks](/config/failsafe/integrity.llms.txt). #### `projects[].networkDefaults` — NetworkDefaults | Field | Type | Default | Inheritance rule | |---|---|---|---| | `rateLimitBudget` | `string` | `""` | Copied when network's value is empty string ([`common/defaults.go:L1783-1785`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1783-L1785)). Validated after inheritance per network — an invalid name surfaces as a per-network error (e.g. `"network.*.rateLimitBudget 'x' does not exist"`), not a top-level `networkDefaults` error. Networks that explicitly set their own non-empty `rateLimitBudget` are not affected. | | `cacheKeySuffix` | `string` | `""` | Copied when network's value is empty string ([`common/defaults.go:L2107-2109`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2107-L2109)). Same charset as `alias`. Not unique. | | `maxClientBatchSize` | `*int` | unset | Copied when the network's value is unset; a network's explicit `0` keeps no limit ([`common/defaults.go:L2242-2245`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2242-L2245)). Negative → `networkDefaults.maxClientBatchSize must be 0 (no limit) or greater` ([`common/validation.go:L1955-1957`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1955-L1957)). | | `failsafe[]` | `[]FailsafeConfig` | `nil` | Network has none → deep-copied wholesale. Network has some → per-entry merge from the FIRST compatible default (wildcard method + finality match); break on first match ([`common/defaults.go:L1793-1832`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1793-L1832)). | | `selectionPolicy` | `SelectionPolicyConfig` | `nil` | Shallow-copied when network's is nil ([`common/defaults.go:L1833-1836`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1833-L1836)). | | `directiveDefaults` | `DirectiveDefaultsConfig` | `nil` | Shallow-copied when network's is nil — **no per-field merge** ([`common/defaults.go:L1837-1840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1837-L1840)). | | `evm` | `EvmNetworkConfig` | `nil` | Struct-copied wholesale when network has no `evm` block — **except onto SVM networks, which never receive it**. Otherwise per-field fill for: `integrity`, `fallbackStatePollerDebounce`, `dynamicBlockTimeDebounceMultiplier`, `finalizedDebounceDepthMultiplier`, `blockUnavailableDelayMultiplier`, `fallbackFinalityDepth`, `getLogsMaxAllowed*`, `getLogs*`, `traceFilter*`, `servedTip`, `emptyResultConfidence`, `shortCircuitFutureBlocks`, and `localAnswers` per method the network does not set. NOT inherited individually: `chainId`, `enforceBlockAvailability`, `maxRetryableBlockDistance`, `markEmptyAsErrorMethods`, `idempotentTransactionBroadcast` ([`common/defaults.go:L1845-1889`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1845-L1889)). | | `svm` | `SvmNetworkConfig` | `nil` | Per-field fill: `chain`, `commitment`, `statePollerDebounce`, `skipProcessedSlotProbe` (opt-in `true` only), `maxFinalizedSlotLag`, `enforceBlockAvailability` ([`common/defaults.go:L2579-2606`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2579-L2606)). **`cluster` is deliberately NOT inherited** — it is network identity, and inheriting it would let two networks alias one another. The two pointer fields are tested for `nil`, not for their zero value, so an explicit `maxFinalizedSlotLag: 0` or `enforceBlockAvailability: false` set here survives the merge. | | `multiplexing` | `*bool` | `nil` | Value-copied when network's `multiplexing` is nil ([`common/defaults.go:L1841-1844`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1841-L1844)). No deep merge — a network must set its own `multiplexing` to deviate from the project-wide default. | Note: `networkDefaults` has **no** `alias`, `methods`, `staticResponses`, or `architecture` fields — those are per-network only. `cacheKeySuffix` *is* inherited. #### `server.aliasing.rules[]` — domain-based aliasing | Field | Type | Default | Behavior | |---|---|---|---| | `rules[]` | list | `nil`; auto-created `{matchDomain: "*", serveProject: "main"}` when config has zero projects ([`common/defaults.go:L100-110`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L110)) | First rule whose `matchDomain` wildcard matches the request Host wins ([`erpc/http_server.go:L232-257`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L232-L257)). | | `rules[].matchDomain` | `string` (wildcard) | — | Matched against Host header (port stripped). | | `rules[].serveProject` | `string` | — | Pre-selects projectId. | | `rules[].serveArchitecture` | `string` | — | Pre-selects architecture. | | `rules[].serveChain` | `string` | — | Pre-selects chainId. Pre-selecting project+chain WITHOUT architecture is rejected at parse time. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. The production baseline: `networkDefaults` with finality-split failsafe policies.** Block-availability races on realtime/unfinalized requests need a non-zero retry delay; finalized/unknown don't — this is why production splits them: **Config path:** `projects[].networkDefaults` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: # All chains inherit these unless they set their own failsafe list directiveDefaults: retryEmpty: true retryPending: false # multiplexing: false in production to avoid follower-timeout amplification # on chains where every block is a write (e.g. high-throughput L2s) multiplexing: false evm: getLogsMaxAllowedRange: 30000 getLogsSplitOnError: true # serve "latest" once a majority of upstreams has it servedTip: quorum: majority failsafe: # NOTE: delay MUST NOT be 0 for realtime/unfinalized — a short non-zero # delay gives shared-state propagation time to catch up after a block # arrives on one upstream but not yet on another - matchMethod: "eth_call|eth_getLogs" matchFinality: [realtime, unfinalized] hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s retry: maxAttempts: 4 delay: 50ms - matchMethod: "eth_call|eth_getLogs" matchFinality: [finalized, unknown] hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s retry: maxAttempts: 4 delay: 0 - matchMethod: "*" retry: maxAttempts: 6 delay: 50ms networks: - architecture: evm evm: { chainId: 1 } alias: ethereum - architecture: evm evm: { chainId: 42161 } alias: arbitrum ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { directiveDefaults: { retryEmpty: true, retryPending: false }, // multiplexing: false in production to avoid follower-timeout amplification multiplexing: false, evm: { getLogsMaxAllowedRange: 30000, getLogsSplitOnError: true, // serve "latest" once a majority of upstreams has it servedTip: { quorum: "majority" }, }, failsafe: [ // NOTE: delay MUST NOT be 0 for realtime/unfinalized — non-zero delay // gives shared-state propagation time after a block arrives on one upstream { matchMethod: "eth_call|eth_getLogs", matchFinality: ["realtime", "unfinalized"], hedge: { quantile: 0.95, maxCount: 1, minDelay: "500ms", maxDelay: "10s" }, retry: { maxAttempts: 4, delay: "50ms" }, }, { matchMethod: "eth_call|eth_getLogs", matchFinality: ["finalized", "unknown"], hedge: { quantile: 0.95, maxCount: 1, minDelay: "500ms", maxDelay: "10s" }, retry: { maxAttempts: 4, delay: "0" }, }, { matchMethod: "*", retry: { maxAttempts: 6, delay: "50ms" } }, ], }, networks: [ { evm: { chainId: 1 }, alias: "ethereum" }, { evm: { chainId: 42161 }, alias: "arbitrum" }, ], }] ``` **2. Per-chain bespoke policy appended before the shared catch-all.** Ethereum mainnet adds consensus on eth_getLogs and state-read integrity checks; Arbitrum bumps the getLogs hedge floor for its faster blocks. Both spread `sharedNetworkFailsafe` at the end so the catch-all policy is never per-chain: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml networks: - evm: { chainId: 1 } alias: ethereum failsafe: # Ethereum-specific: 2-of-3 consensus on getLogs for indexing integrity - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: [unfinalized, unknown] timeout: { duration: 15s } hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s retry: maxAttempts: 6 delay: 0 emptyResultDelay: 1000ms # consensus config would follow here # ... sharedNetworkFailsafe spread after (catch-all always last) - evm: { chainId: 42161 } alias: arbitrum-one failsafe: # Arbitrum-specific: getLogs minDelay raised to 1000ms — Arbitrum delivers # blocks at ~250ms and block-availability races persist slightly longer - matchMethod: "eth_getLogs|eth_getBlockReceipts" matchFinality: [unfinalized] hedge: quantile: 0.95 maxCount: 1 minDelay: 1000ms maxDelay: 10s retry: maxAttempts: 6 delay: 0 # ... sharedNetworkFailsafe spread after ``` **TypeScript — `erpc.ts`:** ```typescript networks: [ { evm: { chainId: 1 }, alias: "ethereum", failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: ["unfinalized", "unknown"], timeout: { duration: "15s" }, hedge: { quantile: 0.95, maxCount: 1, minDelay: "500ms", maxDelay: "10s" }, retry: { maxAttempts: 6, delay: "0", emptyResultDelay: "1000ms" }, // consensus config would follow }, // ...sharedNetworkFailsafe spread after ], }, { evm: { chainId: 42161 }, alias: "arbitrum-one", failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", matchFinality: ["unfinalized"], // Arbitrum delivers ~250ms blocks; minDelay raised to avoid // block-availability races more common on fast L2s hedge: { quantile: 0.95, maxCount: 1, minDelay: "1000ms", maxDelay: "10s" }, retry: { maxAttempts: 6, delay: "0" }, }, // ...sharedNetworkFailsafe spread after ], }, ] ``` **3. Static genesis-block response for a chain that starts at block 1.** Serve a canned reply before the multiplexer and cache so clients don't hit a dead upstream on block 0. The `staticResponses` array is checked before everything else in the forward pipeline: **Config path:** `projects[].networks[].staticResponses[]` **YAML — `erpc.yaml`:** ```yaml networks: - evm: { chainId: 1328 } alias: sei-testnet staticResponses: - method: eth_getBlockByNumber params: ["0x0", false] response: result: # Fill the fields your clients read; unrecognised fields are fine number: "0x0" hash: "0x0000000000000000000000000000000000000000000000000000000000000000" parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000" transactions: [] ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ evm: { chainId: 1328 }, alias: "sei-testnet", staticResponses: [{ method: "eth_getBlockByNumber", params: ["0x0", false], response: { result: { number: "0x0", hash: "0x0000000000000000000000000000000000000000000000000000000000000000", parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000", transactions: [], }, }, }], }] ``` **4. Skip data-integrity validation for non-standard chains.** ZkSync Era and other ZK-rollups use a non-standard `transactionsRoot` (and other encodings) the [data-integrity module](/config/failsafe/integrity.llms.txt)'s recompute checks can't model. The module is opt-in, but if you enabled it project-wide, turn it off for that chain — a network `integrity` block overrides the project one: **Config path:** `projects[].networks[].integrity` **YAML — `erpc.yaml`:** ```yaml networks: - evm: { chainId: 324 } alias: zksync-mainnet # Override the project-wide integrity level to off for this chain # (or disable just the transactionsRoot checks via integrity.checks). integrity: level: off ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ evm: { chainId: 324 }, alias: "zksync-mainnet", integrity: { level: "off" }, }] ``` **5. Domain-based aliasing for fully path-free routing.** Route an entire subdomain straight to a chain — no project or network segment in the URL path. The alias and domain rule work together so clients call a clean HTTPS endpoint: ```yaml server: aliasing: rules: - matchDomain: "eth.rpc.example.com" serveProject: main serveArchitecture: evm serveChain: "1" # Wildcard: any unknown subdomain falls through to the main project - matchDomain: "*.rpc.example.com" serveProject: main ``` ``` POST https://eth.rpc.example.com/ → main/evm:1 ``` **6. Multiple SVM chains side by side.** `chain` defaults to `solana`, so a plain Solana cluster keeps the short two-segment id. Naming a fork's chain switches the id to three segments, which is what keeps cache partitions and alias registration from colliding between `svm:mainnet-beta` and `svm:fogo:mainnet`. Note that `cluster` stays per-network — it is identity, so `networkDefaults.svm` carries only the shared policy: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: svm: # shared policy only — cluster is network identity and must not be here commitment: confirmed statePollerDebounce: 500ms networks: # chain omitted → "solana" → networkId "svm:mainnet-beta" - architecture: svm svm: cluster: mainnet-beta # explicit chain → networkId "svm:fogo:mainnet" - architecture: svm svm: chain: fogo cluster: mainnet ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { svm: { // shared policy only — cluster is network identity and must not be here commitment: "confirmed", statePollerDebounce: "500ms", }, }, networks: [ // chain omitted → "solana" → networkId "svm:mainnet-beta" { architecture: "svm", svm: { cluster: "mainnet-beta" } }, // explicit chain → networkId "svm:fogo:mainnet" { architecture: "svm", svm: { chain: "fogo", cluster: "mainnet" } }, ], }] ``` Both id shapes are addressable the same three ways — URL path, request-body `networkId`, or an `alias`. The fork's colon is carried inside the third path segment: ``` POST /main/svm/mainnet-beta → svm:mainnet-beta POST /main/svm/fogo:mainnet → svm:fogo:mainnet POST /main → body {"networkId": "svm:fogo:mainnet", ...} ``` ### Request/response behavior - The `network` label on every Prometheus metric equals the alias when set, otherwise the raw network id (`evm:1`, `svm:mainnet-beta`, `svm:fogo:mainnet`). This affects all `erpc_network_*` metrics. [`erpc/networks.go:L278-286`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L278-L286) - Static-response hits short-circuit before the multiplexer; `static_response.hit=true` is set on the `Network.Forward` OTel span. They never read or write the cache. - Multiplexer followers receive a copy of the leader's response; if the follower's context deadline fires before the leader completes, the error is `ErrNetworkRequestTimeout` (HTTP 504 status code, JSON-RPC error code −32603). This is distinct from `ErrFailsafeTimeoutExceeded` (failsafe policy timeout) and `ErrEndpointRequestTimeout` (individual upstream HTTP timeout). - `ErrNetworkInitializing` (HTTP 503) is returned while the bootstrap task is still running. The client should retry. Failed (non-fatal) bootstrap tasks are auto-retried by the background loop with factor-1.5 backoff (3 s to 130 s, task timeout 120 s). - `ErrNetworkNotSupported` (HTTP 404) is returned when all providers report the chain is not supported and zero upstreams were registered. It is never retried by the bootstrap loop. - `ErrNetworkNotFound` (HTTP 404) is returned after a successful bootstrap task that stored nothing (defensive path). The caller must retry. - `ErrInvalidRequest` (HTTP 400) is returned when the networkId in the URL is not a valid `evm:` format — the error message suggests using an alias or `evm/42161` form. [`erpc/networks_registry.go:L220-222`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L220-L222) - `ErrNoUpstreamsFound` (HTTP 404) fires when the policy engine returns an empty ordered list and the raw registration list is also empty — all upstreams have been filtered out. - `ErrUpstreamsExhausted` fires when every upstream in the ordered list was tried and all failed; it carries per-upstream errors. [`erpc/networks.go:L1392-1406`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1392-L1406) - `ErrNotImplemented` (HTTP 501) is returned for `eth_accounts` and `eth_sign` (always); stateful methods with more than one candidate upstream also produce this error unless scoped by a `use-upstream` directive. - `ErrInvalidEvmChainId` (HTTP 400) is returned when the chain id cannot be parsed. - `ErrNetworkRequestTimeout` wire behavior: JSON-RPC error code −32603; HTTP transport status is 200 (JSON-RPC over HTTP); `ErrorStatusCode()` returns 504 but this is only seen in non-JSON-RPC error paths. The error is retryable toward both network and upstream (no explicit non-retryable flag). Message format: `"network-level request towards one or more upstreams timed out after ms"` where N is the elapsed time since the follower registered with the multiplexer. - An alias in the request body `networkId` field is silently ignored — the body fallback splits the literal value on `:` with no alias lookup. Only URL path segments resolve aliases. ### Best practices - Always set `networkDefaults.failsafe` before adding per-chain `failsafe` entries — once a network has any failsafe list, the defaults list is superseded entirely for that network. - Use `alias` on every statically-declared chain you control. It makes URLs readable, shows up in every Prometheus label, and costs nothing. - Set `preserveDefaultMethods: true` before adding any custom `methods.definitions` entry. The default `false` silently drops all built-in methods (including `eth_call`, `eth_getLogs`) the moment you add one definition. - Never set `finalized: true` on a method that returns block-specific data (`eth_getBalance`, `eth_getCode`, etc.) — every response will be permanently cached at the first value ever returned. - Use `servedTip.quorum: majority` on pools of 4+ upstreams when "block not found" follows `latest` requests; the default 2 serves a block only two upstreams may have. - Keep `getLogsMaxAllowedRange` at its default 30 000 unless your upstreams document a higher limit — range splits happen automatically on oversized requests but `getLogsSplitConcurrency` caps parallelism at 10 to avoid flooding providers. - For `eth_sendRawTransaction` in high-retry configs, leave `idempotentTransactionBroadcast` enabled (default). Disabling it turns idempotent "already known" errors back into real failures, making retries unsafe. ### Edge cases & gotchas 1. **Aliases work in URLs only, not body `networkId`** — body fallback splits on `:` with no alias lookup; only `parseUrlPath` resolves aliases. [`erpc/http_server.go:L613-634`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L613-L634) 2. **Unknown alias segment falls through silently** — an unresolvable single path segment is treated as architecture, yielding "architecture is not valid (must be 'evm')" instead of an alias-not-found error. 3. **`directiveDefaults` is all-or-nothing** — a network-level `directiveDefaults` block completely replaces `networkDefaults.directiveDefaults`; individual fields are not merged. [`common/defaults.go:L1837-1840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1837-L1840) 4. **`failsafe` replaces, not merges** — any `networks[].failsafe` list supersedes `networkDefaults.failsafe` entirely for that network. 5. **`preserveDefaultMethods: false` + one custom `definitions` entry drops ALL built-ins** — including `eth_call`, `eth_getLogs`, etc. Only the custom entries plus the 6 stateful markers survive. [`common/defaults.go:L561-573`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L561-L573) 6. **`finalized: true` on a non-finalized method permanently caches all responses** — every response is placed in the `finalized` cache bucket (long/permanent TTL). Setting this on `eth_getBalance` would permanently cache every balance at the first value returned. [`erpc/networks.go:L1656-1660`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1656-L1660) 7. **`networkDefaults.multiplexing` has no deep merge** — a network must set its own `multiplexing` field; there is no per-network override via defaults alone. 8. **Legacy single-object `networkDefaults.failsafe` silently drops `multiplexing`** — the old-format fallback struct has no `Multiplexing` field. [`common/config.go:L626-655`](https://github.com/erpc/erpc/blob/main/common/config.go#L626-L655) 9. **Lazily-exposed networks never get a metrics alias resolver entry** — `erpc/init.go` builds the map only from static `cfg.Projects[].Networks[]`; gRPC-cache metrics for lazy networks show the raw networkId. [`erpc/init.go:L62-77`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L62-L77) 10. **`evm.enforceBlockAvailability: false` overrides upstream bounds** — step 3 of the enforcement chain (upstream-has-bounds) is only reached when steps 1–2 yield no decision; an explicit `false` at the network level (step 2) short-circuits it. [`erpc/networks.go:L1814-1817`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1814-L1817) 11. **Static response error code `0` is omitted from the wire response** — `Code` is tagged `json:"code,omitempty"` on int, so `0` disappears from the JSON error object. Always use a non-zero code in production. [`common/errors.go:L2226`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2226) 12. **Failsafe merge picks the FIRST matching default** — ordering of `networkDefaults.failsafe` entries matters when multiple wildcard entries could match. 13. **`stateful: false` on a built-in stateful method is silently overridden** — `MethodsConfig.SetDefaults` force-sets `Stateful = true` for all 6 stateful methods in all three code paths, overwriting any user-supplied `false` without any warning. [`common/defaults.go:L512-573`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L512-L573) 14. **`EnforceGetLogsBlockRange` directives cannot be overridden per-request via HTTP headers for `eth_getLogs`, `trace_filter`, and `arbtrace_filter`** — these hooks read from the config baked in at startup, not live per-request directives. Set `enforceGetLogsBlockRange: false` in `directiveDefaults`, not as an HTTP header. `eth_blockNumber` reads the live `enforceHighestBlock` directive, so a header does override it. [`architecture/evm/eth_getLogs.go:L282-285`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L282-L285) 15. **`ErrNetworkRequestTimeout` is produced only in the multiplexer follower path** — a request that is itself the leader experiences `ErrFailsafeTimeoutExceeded` or upstream sweep errors, never `ErrNetworkRequestTimeout`. [`erpc/networks.go:L2079-2084`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2079-L2084) 16. **`evm.chainId: 0` is not rejected** — `chainId: 0` produces `networkId = evm:0`, which passes `util.IsValidNetworkId` but is excluded by provider `onlyNetworks`/`ignoreNetworks` lists that use the stricter `chainId > 0` check. 17. **`translateLatestTag: false` on a non-historical method collapses all callers to one cache key** — all requests for that method share the literal `"latest"` key; stale data is returned until the cache TTL expires. 18. **`preserveDefaultMethods: false` with NO `definitions` block keeps ALL built-ins** — the drop-all behavior only triggers when `definitions` is non-empty AND `preserveDefaultMethods` is false. A config with `methods: { preserveDefaultMethods: false }` and no `definitions` key is identical to omitting the `methods` block entirely. [`common/defaults.go:L494`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L494) 19. **Lazy network alias registration happens after first bootstrap** — statically-declared networks register aliases eagerly in the `NetworksRegistry` constructor; lazily-created networks only register their alias inside `prepareNetwork`, which runs during bootstrap. Until bootstrap completes, alias-based URLs for lazy networks return an alias-not-found error. [`erpc/networks_registry.go:L322-328`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L322-L328) 20. **Failed lazy bootstrap is user-retryable** — non-fatal bootstrap tasks are retried by the background auto-retry loop and by the next request's `ExecuteTasks`. Only `resolveNetworkConfig` format errors are `TaskFatal` and never retried. [`erpc/networks_registry.go:L263-266`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L263-L266) 21. **Provider `onlyNetworks` bypasses vendor support checks entirely** — a networkId listed in `onlyNetworks` returns `SupportsNetwork = true` without consulting the vendor's dynamic check; `ignoreNetworks` is evaluated first and short-circuits to false. [`thirdparty/provider.go:L34-49`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L34-L49) 22. **Synthesized lazy network configs become permanently visible** — `ExposeNetworkConfig` appends to `project.Config.Networks` (admin API surface) and never overwrites an existing entry, so lazy networks persist in the admin response after first use. [`erpc/projects.go:L58-77`](https://github.com/erpc/erpc/blob/main/erpc/projects.go#L58-L77) 23. **Syncing upstreams are excluded from every head computation** — the served-tip ballots, lowest-finalized, and guaranteed-method floor calculations all skip upstreams in `EvmSyncingStateSyncing`. The future-block short-circuit is the exception: it counts every upstream of the network, syncing ones included ([`erpc/networks.go:L849-868`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L849-L868)). [`erpc/networks.go:L451-470`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L451-L470) 24. **Future-block short-circuit compares against the MAX head across every upstream of the network, not the served tip** — selection policy, tier (a cordoned fallback can still serve through the escape) and syncing state are ignored, and it fails open while any upstream's head is unknown, so it never nulls a block that any upstream reports having. One upstream whose head is never learned (for example a broken endpoint) therefore keeps it from firing on that network. It runs only when `evm.shortCircuitFutureBlocks` is true, and always compares latest heads: `emptyResultConfidence: finalizedBlock` does not make it null an unfinalized block an upstream already has. The synthetic null response is never cached, and the short-circuit only fires for concrete block numbers (not tags or hashes). [`erpc/networks.go:L893-964`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L893-L964) 25. **Wrong-empty misbehavior is suppressed outside an upstream's declared range** — a missing-data answer is neither counted nor recorded as misbehavior when the target block (the response's, else the request's own, as for `eth_call`) falls outside the upstream's configured `blockAvailability` bounds, or when the upstream has bounds and the request names no number (a request by block hash): a pruned full node cannot be shown to have missed data it should hold. [`erpc/networks.go:L2691-L2705`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2691-L2705) 26. **`getLogsMaxAllowedRange: 0` is rejected by validation** — the field must be > 0 after defaults (`common/validation.go:L1309-1311`). Unlike `getLogsMaxAllowedAddresses` and `getLogsMaxAllowedTopics` (which default to 0 = unlimited), `getLogsMaxAllowedRange` defaults to 30 000 and cannot be explicitly zeroed out; setting `0` in a network inheriting from defaults is treated as "unset" and inherits the parent value. [`common/defaults.go:L2092-2094`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2092-L2094) 27. **Zero projects → implicit `main` project + catch-all aliasing rule** — when the config has no projects, eRPC auto-creates `{matchDomain: "*", serveProject: "main"}`, so `/evm/123` works without a project path segment. [`common/defaults.go:L100-110`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L110) 28. **Selector-scoped tips never pollute network gauges** — only a simple group selector gets a [lane](/reference/lanes.llms.txt) and its own `lane` series; any other selector's pick writes no gauge. [`erpc/networks.go:L628-655`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L628-L655) 29. **Static response params matching has no wildcard** — there is no glob or `*` support; every params slot must match exactly. To catch a method regardless of params, add an entry with an empty `params` array. To match block 0 (`"0x0"`), be exact — `"0x00"` will not match. [`common/static_response.go:L14-99`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L14-L99) 30. **Same-chain networks share Redis cache keys unless `cacheKeySuffix` is set** — partition keys are `{networkId}:{blockRef}` (`evm:998:64321354`). Two projects on chainId 998 with a shared Redis will HIT each other's bodies. `X-ERPC-Skip-Cache-Read` still writes, so the last fetch poisons the other project. Set `cacheKeySuffix: systx` on one network to get `evm:998:systx:{blockRef}`. Colon is rejected. Reverse-index wildcard is `{networkId}:{suffix}:*`, passed from the known network id and suffix rather than inferred from the concrete key. Memory/Redis `Delete` must use the same `WithReverseIndex` ctx as `Set`. A chain-wide main-key flush of `evm:998:*` still matches suffixed data keys. [`common/config.go:L3022-L3028`](https://github.com/erpc/erpc/blob/main/common/config.go#L3022-L3028), [`data/connector.go`](https://github.com/erpc/erpc/blob/main/data/connector.go) 31. **`shortCircuitFutureBlocks` can briefly null a block that exists** — the head it compares against is what the state poller and head subscriptions last reported. A block an upstream produced after that gets `null` until eRPC sees it, even if the client already saw it via the node's own `newHeads` (the case covered by `TestNetworkAvailability_Issue934_*`, which run with the option off). Enable it only where heads arrive promptly (WebSocket head subscriptions) and clients retry a `null`. [`erpc/networks.go:L893-936`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L893-L936) 32. **`maxClientBatchSize` refuses the whole batch, not the excess** — a batch of `limit+1` runs zero requests and gets one `id: null` error, never a partial array. Set it per network: EVM clients send large batches, Solana clients rarely batch, so one project-wide value under `networkDefaults` rarely fits every network. [`erpc/http_server.go:L568-586`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L568-L586) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_request_received_total` | counter | `project`, `network`, `category`, `finality`, `user`, `agent_name` | On project forward entry | | `erpc_network_successful_request_total` | counter | `project`, `network`, `vendor`, `upstream`, `category`, `attempt`, `finality`, `emptyish`, `user`, `agent_name` | Successful response (vendor/upstream = `` for cache hits) | | `erpc_network_failed_request_total` | counter | `project`, `network`, `category`, `attempt`, `error`, `severity`, `finality`, `user`, `agent_name` | Failed response | | `erpc_network_request_duration_seconds` | histogram | `project`, `network`, `vendor`, `upstream`, `category`, `finality`, `user` | Request completed (vendor/upstream = `` on failure) | | `erpc_network_multiplexed_request_total` | counter | `project`, `network`, `category`, `finality`, `user`, `agent_name` | Follower registered with the in-flight deduplicator | | `erpc_network_static_response_served_total` | counter | `project`, `network`, `category` | Static response matched and served | | `erpc_network_timeout_fired_total` | counter | `project`, `network`, `category`, `finality`, `scope` | Failsafe timeout fired; `scope=network` at network level | | `erpc_network_hedged_request_total` | counter | `project`, `network`, `upstream`, `category`, `attempt`, `finality`, `user`, `agent_name` | Hedge attempt dispatched for this upstream | | `erpc_network_hedge_discards_total` | counter | `project`, `network`, `upstream`, `category`, `attempt`, `hedge`, `finality`, `user`, `agent_name` | Hedge response discarded (a faster response already won) | | `erpc_upstream_wrong_empty_response_total` | counter | `project`, `vendor`, `network`, `upstream`, `category`, `finality`, `user`, `agent_name` | Upstream returned missing-data while another upstream served real data; suppressed when the upstream's head was below the target block, or the target block is outside (or, by block hash, unknown to) the upstream's `blockAvailability` bounds | | `erpc_unexpected_panic_total` | counter | (standard labels) | Panic recovered in the async cache-set goroutine | Served-tip and bench metrics: see the [metrics reference](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking). **Notable logs** (zerolog, at `erpc/networks_registry.go` and `erpc/networks.go` unless noted): - `"registered network alias"` / `"skipping duplicate alias registration with different target"` — alias map events. - `"network initialization ended with zero upstreams"` — bootstrap completed but no upstreams were registered. - `"networks bootstrap completed"` / `"failed to bootstrap networks in background"` — startup background bootstrap outcome. - `"response served from cache"` — cache hit in the forward pipeline. - `"found identical request initiating multiplexer"` — multiplexer follower registered. - `"block availability check failed; failing open to allow request"` — block-availability extraction or poller error; request proceeds. - `"served static response (no upstream contacted)"` (debug) — static response matched and served (`erpc/networks_static_responses.go`). - `"skipping static response: cannot inspect request"` (debug) — `JsonRpcRequest()` failed; static check skipped. - `"failed to build static response"` (error) — `NewJsonRpcResponse` failed on a matched static entry. - Provider task: `"registering N upstream(s) from provider"` (`upstream/registry.go`). **Span attributes** (on the `Network.Forward` span): - `future_block.short_circuit=true` — the future-block short-circuit returned `null` without dispatching (`evm.shortCircuitFutureBlocks: true`). No metric counts these; they are not dispatched, so they do not appear in upstream request metrics. ### Source code entry points - [`erpc/networks_registry.go:L83-376`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L83-L376) — `NetworksRegistry`: lazy `GetNetwork`, bootstrap tasks, `resolveNetworkConfig` synthesis, alias map register/resolve, `NewNetwork` constructor. - [`erpc/networks.go:L931-1603`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L931-L1603) — `Network.Forward`: full request pipeline, failsafe-executor matching, static responses, multiplexing, cache, upstream ordering, block-availability gating, finality classification. - [`common/defaults.go:L1781-1973`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1781-L1973) — `NetworkConfig.SetDefaults`: networkDefaults inheritance, per-field fill rules, EvmNetworkConfig/MethodsConfig/DirectiveDefaults sub-passes. - [`erpc/http_server.go:L810-1006`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L810-L1006) — `parseUrlPath`: URL/alias parsing decision table, domain-aliasing rules, body-networkId fallback. - [`common/config.go:L1995-2256`](https://github.com/erpc/erpc/blob/main/common/config.go#L1995-L2256) — `NetworkConfig`, `EvmNetworkConfig` struct definitions, legacy single-failsafe decode, `NetworkId()`. - [`upstream/registry.go:L155-293`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L155-L293) — `PrepareUpstreamsForNetwork`: provider fan-out, ready-wait, 503/404 error states. - [`erpc/networks_static_responses.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go) — `tryServeStaticResponse`: canned-response serving, metric emit. - [`common/static_response.go:L14-99`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L14-L99) — `FindStaticResponseMatch`, `paramsEqual`, `valueEqual`: pure matching logic (YAML int vs JSON float64 tolerance, map key order independence). ### Related pages - [SVM commitment & finality](/reference/svm/commitment.llms.txt) — how `svm.commitment` is injected and how SVM finality is classified. - [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) — the state poller behind `statePollerDebounce`, plus `maxFinalizedSlotLag` and `enforceBlockAvailability` in depth. - [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt) — caching for SVM networks. - [Static responses](/config/projects/static-responses.llms.txt) — full matching semantics and edge cases for canned replies. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — upstream ordering within a network. - [Retry](/config/failsafe/retry.llms.txt) — per-network failsafe retry policy. - [Hedge](/config/failsafe/hedge.llms.txt) — parallel backup requests on slow upstreams. - [Timeout](/config/failsafe/timeout.llms.txt) — bounds the upstream sweep from outside. - [Rate limiters](/config/rate-limiters.llms.txt) — budgets referenced by `rateLimitBudget`. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome networks + failsafe deliver together. --- --- # Providers & vendors > Source: https://docs.erpc.cloud/config/projects/providers > One API key, every chain — declare a single provider entry and eRPC auto-generates upstreams for each network on first request, with 26 built-in vendor integrations. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Providers & vendors One API key, every chain. Instead of wiring one upstream per (vendor, network) pair, you declare a single provider and eRPC lazy-generates concrete upstreams the moment a new network is first requested. 26 vendor integrations are built in — from general-purpose node providers to ERC-4337 bundlers to public-endpoint catalogs — and a project with no config at all gets a sensible zero-cost default automatically. **What you get** - One line to cover all chains a vendor supports — no manual network list. - Hot-path chain discovery with no I/O: static maps and lock-free remote caches keep routing decisions off the slow path. - Zero-config fallback: eRPC auto-injects a `repository` provider when no upstreams or providers are configured. ## Quick taste Illustrative, not a tuned production config — one key, every Alchemy chain: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - # URL shorthand — one line, all Alchemy chains endpoint: alchemy://YOUR_API_KEY ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreams: [{ // URL shorthand — one line, all Alchemy chains endpoint: "alchemy://YOUR_API_KEY", }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up providers from scratch** ```text I want to configure eRPC providers so a single API key per vendor covers all EVM chains automatically. Add Alchemy and dRPC as providers, restrict Alchemy to the chains we actually need (mainnet, Arbitrum, Base, Polygon), and leave everything else to dRPC. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/projects/providers.llms.txt ``` **Prompt Example #2: add per-network overrides to an existing provider** ```text My eRPC config already has providers for Alchemy and QuickNode. I need Arbitrum (evm:42161) to pre-split eth_getLogs at 1000 blocks and have a lower score multiplier for QuickNode on mainnet. Apply these as provider overrides without touching the upstreams list. Reference: https://docs.erpc.cloud/config/projects/providers.llms.txt ``` **Prompt Example #3: debug a provider not generating upstreams on cold start** ```text My eRPC instance logs ErrNetworkInitializing for evm:130 on every first request after a redeploy, even though I have a conduit provider configured. Explain why conduit returns ErrRemoteCacheCold on cold start and what I can pair it with to avoid the first-request delay. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/providers.llms.txt ``` **Prompt Example #4: route ERC-4337 bundler traffic to pimlico** ```text Add Pimlico as a provider in my eRPC config so all bundler methods (eth_sendUserOperation, pimlico_*, pm_*) route to Pimlico while general eth_* methods still hit Alchemy. Explain the method allow-list that Pimlico injects automatically. Reference: https://docs.erpc.cloud/config/projects/providers.llms.txt ``` **Prompt Example #5: split QuickNode endpoint groups by tag** ```text I have two logical QuickNode endpoint groups: one tagged "archive" and one tagged "realtime". Wire them as separate providers in my eRPC config so each group's endpoints are used for the right traffic, and explain the apiKey cache-key footgun so I don't accidentally share snapshots. Reference: https://docs.erpc.cloud/config/projects/providers.llms.txt ``` --- ### Providers & vendors — full agent reference ### How it works **Two distinct concepts.** A *vendor* (`common.Vendor` interface) is stateless integration logic: `Name()`, `OwnsUpstream(cfg)`, `SupportsNetwork(ctx, logger, settings, networkId)`, `GenerateConfigs(...)`, and `GetVendorSpecificErrorIfAny(...)`. A *provider* is a configured instance of a vendor: `ProviderConfig{Id, Vendor, Settings, OnlyNetworks, IgnoreNetworks, UpstreamIdTemplate, Overrides}`. All 26 vendors are registered in a global `VendorsRegistry` at startup; a per-project `ProvidersRegistry` resolves each `providers[].vendor` string and fails startup if the name is unknown. [`thirdparty/vendors_registry.go:L9-39`](https://github.com/erpc/erpc/blob/main/thirdparty/vendors_registry.go#L9-L39) [`thirdparty/providers_registry.go:L15-34`](https://github.com/erpc/erpc/blob/main/thirdparty/providers_registry.go#L15-L34) **Lazy upstream generation.** When a request arrives for a network with no prepared upstreams, `UpstreamsRegistry.PrepareUpstreamsForNetwork` schedules — exactly once per network via `sync.Once` — one bootstrap task per declared provider named `network//provider/`. Each task: (1) calls `Provider.SupportsNetwork`, applying `ignoreNetworks` deny-list first, then `onlyNetworks` allow-list, then delegating to the vendor; (2) calls `Provider.GenerateUpstreamConfigs`, which copies the first wildcard-matching `overrides` entry (or creates a fresh defaults-filled config), stamps `VendorName`, renders the upstream id from `upstreamIdTemplate`, and runs `os.ExpandEnv` over every generated endpoint; (3) registers the resulting configs as ordinary upstream bootstrap tasks. The caller waits up to 30 seconds (polling every 200 ms) for at least one upstream to become ready. While tasks run, clients receive the retryable `ErrNetworkInitializing`; if all tasks finish without producing any upstreams, the error becomes the retryable `ErrNetworkNotSupported`. Failed tasks auto-retry with exponential backoff (factor 1.5, 3 s → 130 s). [`upstream/registry.go:L155-293`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L155-L293) **Vendor chain-support strategies.** Vendors answer "do you support this network?" in four ways: 1. **Static in-code map** (ankr, blastapi, blockdaemon, blockpi, dwellir, infura, llama, onfinality, etherspot, spectrum): instant, no I/O, works on cold start. 2. **Remote catalog with static fallback** (alchemy — 134-chain map; drpc — 150-chain map; willow — 7-chain map): fetches on warm paths; cold start falls back to the built-in map so the first request never blocks on I/O. 3. **Remote catalog, no fallback** (conduit, superchain, tenderly, quicknode, chainstack, repository): cold start returns the retryable sentinel `ErrRemoteCacheCold`; the initializer retries with 3 s → 130 s exponential backoff until the first fetch lands. 4. **Live `eth_chainId` probe** (envio for unknown chains, erpc, pimlico for unknown chains, routemesh, thirdweb): sends a real JSON-RPC call to the candidate endpoint with a 10 s timeout; probe clients are cached per chain id in `sync.Map`. **The request-path safety rule.** Any vendor consulting remote data on the hot path uses the shared `RemoteDataCache[T]`: reads are a single `atomic.Pointer` load — never a mutex, never I/O. Staleness triggers a single-flight async refresh in a goroutine with its own 90 s timeout, fully decoupled from the caller's context. [`thirdparty/remote_cache.go:L13-78`](https://github.com/erpc/erpc/blob/main/thirdparty/remote_cache.go#L13-L78) **URL shorthand scheme.** Any upstream whose endpoint scheme is not `http`, `https`, `grpc`, or `grpc+bds` is converted to a `ProviderConfig` at config-defaults time. The `evm+` prefix is stripped first (`evm+alchemy://` equals `alchemy://`). The original upstream config (failsafe, rate limits, method filters, etc.) is placed into `overrides: {"*": ...}` so it applies to every generated upstream. The provider id defaults to `-` (process-wide counter per vendor name). Unknown scheme is a config-load error. [`common/defaults.go:L1113-1241`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1113-L1241) **Default providers.** A project with zero upstreams, zero providers, and no CLI `--endpoint` flags automatically gets `{id:"public", vendor:"repository"}` injected with all defaults, and logs a warning. Setting `providers: []` explicitly still satisfies the zero-providers condition — the injection fires unless you have at least one upstream or one CLI endpoint. [`common/defaults.go:L1113-1146`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1113-L1146) **Vendors also serve statically-configured upstreams.** At `NewUpstream`, `LookupByUpstream` finds a vendor by explicit `upstream.vendorName` (exact match, wins — if the name is unknown, `OwnsUpstream` is NOT consulted and the result is nil) or the first vendor whose `OwnsUpstream` matches the endpoint (in registration order). If no vendor matches, `vendorName` is guessed as `unknown-` from the endpoint host. The vendor's `GenerateConfigs` is invoked with `settings == nil` to apply vendor defaults (e.g. dRPC forcing `autoIgnoreUnsupportedMethods: false`, envio's method allow-list). Vendor-specific JSON-RPC error mapping fires before generic normalization: `GetVendorSpecificErrorIfAny` is called on the upstream's attached vendor first. [`architecture/evm/error_normalizer.go:L878-900`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L878-L900) [`thirdparty/vendors_registry.go:L54-71`](https://github.com/erpc/erpc/blob/main/thirdparty/vendors_registry.go#L54-L71) ### Config schema #### `projects[].providers[]` — ProviderConfig | field | type | default | behavior / footguns | |---|---|---|---| | `id` | string | vendor name (`p.Id = p.Vendor`) | Unique handle; appears in `` placeholder and bootstrap task names `network//provider/`. Shorthand-converted providers get `-` (process-wide counter). No duplicate-id check — two providers with the same default id both run and may produce upstream-id collisions. [`common/defaults.go:L1474-1476`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1474-L1476) [`util/ids.go:L32-41`](https://github.com/erpc/erpc/blob/main/util/ids.go#L32-L41) | | `vendor` | string | — (required) | Must exactly match one of 26 registered `Name()` strings: `goldsky, alchemy, blastapi, conduit, drpc, dwellir, envio, etherspot, infura, pimlico, quicknode, llama, thirdweb, repository, superchain, tenderly, chainstack, onfinality, erpc, blockpi, ankr, routemesh, blockdaemon, satelink, spectrum, willow`. Unknown vendor → startup error. [`thirdparty/vendors_registry.go:L12-37`](https://github.com/erpc/erpc/blob/main/thirdparty/vendors_registry.go#L12-L37) | | `settings` | `map[string]any` (VendorSettings) | `nil` | Free-form, vendor-interpreted. Redacted in JSON/YAML marshaling (never echoed in admin dump). See per-vendor tables below. [`common/config.go:L667-700`](https://github.com/erpc/erpc/blob/main/common/config.go#L667-L700) | | `settings.creditUnits` | `map[string]int64` | `nil` | Vendor-generic (works for every vendor): per-method **credit-unit** overrides for the cost accounting behind `X-ERPC-Credits` (`server.costHeaders`). Merged per method over the vendor's built-in `CreditUnitsProvider` table (alchemy and quicknode ship their public pricing); `"*"` = the vendor's fallback for unlisted methods. Vendors with no table default to a flat **1 credit per request** — set `"*": 0` to opt a vendor out entirely. Overriding one method keeps the rest; copied onto every upstream the provider generates. [`thirdparty/provider.go:L59-77`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L59-L77) | | `onlyNetworks` | `[]string` | `nil` | Exhaustive allow-list (`evm:` format, validated). If set, vendor's own `SupportsNetwork` is **not** called. Mutually exclusive with `ignoreNetworks` (validation error). [`thirdparty/provider.go:L42-49`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L42-L49) | | `ignoreNetworks` | `[]string` | `nil` | Exact-match deny-list checked **before** `onlyNetworks` and before vendor. Same `evm:` validation. Omitted from `MarshalJSON` (present in YAML marshal). [`thirdparty/provider.go:L34-40`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L34-L40) | | `upstreamIdTemplate` | string | `"-"` | Placeholders: ``, ``, `` (full network id e.g. `evm:1`), `` (numeric; `N/A` for non-evm networks). Validation requires non-empty. [`common/defaults.go:L1477-1479`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1477-L1479) | | `overrides` | `map[string]*UpstreamConfig` | `nil` | Keys are wildcard patterns (WildcardMatch grammar: `*`, `?`, `\|` OR, `&` AND, `!` NOT). First match from Go map iteration (nondeterministic for overlapping keys) is copied as the base config; no match → fresh `UpstreamConfig` with defaults. Pattern-match errors silently skipped. Each override validated with endpoint check skipped. [`thirdparty/provider.go:L77-101`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L77-L101) | #### URL shorthand derivation | shorthand | derived settings | |---|---| | `goldsky://[?tier=&secret=]` | `{secret: authority}` + `tier`/`secret` from query (host is always `edge.goldsky.com`) | | `alchemy://` | `{apiKey: key}` | | `ankr://` | `{apiKey: key}` | | `blastapi://` | `{apiKey: key}` | | `satelink://free@polygon` | free tier, no key | | `satelink://@polygon` | `{apiKey: key}` | | `blockdaemon://` | `{apiKey: key}` | | `blockpi://` | `{apiKey: key}` | | `chainstack://[?project=®ion=&…]` | `{apiKey: key}` + all query params copied verbatim | | `conduit://` | `{apiKey: key}` | | `drpc://` | `{apiKey: key}` | | `dwellir://` | `{apiKey: key}` | | `envio://` | `{rootDomain: host}` | | `erpc://[/][?secret=]` | `{endpoint: "https://"+host+"/"+path}` + `secret` from query | | `etherspot://` | `{apiKey: key}` | | `infura://` | `{apiKey: key}` | | `llama://` | `{apiKey: key}` | | `onfinality://` | `{apiKey: key}` | | `pimlico://` | `{apiKey: key}` | | `quicknode://[?tagIds=1,2&tagLabels=a,b]` | `{apiKey: key}` + parsed `tagIds`/`tagLabels` | | `repository:///[?query]` | `{repositoryUrl: "https://"+host+"/"+path+"?"+query}` | | `routemesh:///rpc//` | `{baseURL: host, apiKey: pathParts[2]}` — path must match exactly | | `spectrum:///[?host=&plan=&nodeType=]` | `{apiKey: "/"}` + `host`/`plan`/`nodeType` from query | | `superchain://` | `{registryUrl: host+path}` | | `tenderly://` | `{apiKey: key}` | | `thirdweb://` | `{clientId: host}` | | `willow://` | `{apiKey: key}` | | unknown scheme | config-load error: `unsupported vendor name in vendor.settings: ` | ### Vendor catalog #### goldsky [Goldsky Edge](https://docs.goldsky.com/edge-rpc/introduction) — a multi-region public RPC service built on eRPC. One secret token covers every chain Goldsky serves; upstreams are lazy-generated per network. SupportsNetwork probes live `eth_chainId` against `https://edge.goldsky.com/{tier}/evm/{chainId}?secret={secret}` (10 s timeout) and confirms the returned chain id matches — so the secret's plan authoritatively decides chain support. A missing `secret` makes SupportsNetwork return `(false, nil)` (silent skip, no retry storm). `tier` defaults to `standard`; `endpoint` defaults to `https://edge.goldsky.com` and may be overridden for enterprise/custom deployments (an explicit path on the base URL is respected verbatim and the tier route is not injected). The secret can also be supplied out-of-band via the `X-ERPC-Secret-Token` header on a preset endpoint. Probe clients are cached per `"{url}-{chainId}"`. OwnsUpstream: `goldsky://`/`evm+goldsky://` prefix, `vendorName=="goldsky"`, or endpoint contains `edge.goldsky.com`. | key | required | default | |---|---|---| | `secret` | yes (auth fails without it) | — | | `tier` | no | `standard` | | `endpoint` | no | `https://edge.goldsky.com` | [`thirdparty/goldsky.go:L31-249`](https://github.com/erpc/erpc/blob/main/thirdparty/goldsky.go#L31-L249) #### alchemy Chain discovery: remote catalog (default `https://app-api.alchemy.com/trpc/config.getNetworkConfig`) keyed by URL via `RemoteDataCache`; **cold-start fallback** to a 134-chain built-in map; after a successful fetch the API result is merged with static defaults (API wins on conflict, static fills gaps). URL template: `https://{subdomain}.g.alchemy.com/v2/{apiKey}`. Error mapping: `-32600` + authenticated message → `ErrEndpointUnauthorized`; code `3` → EVM revert. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `chainsUrl` | no | `https://app-api.alchemy.com/trpc/config.getNetworkConfig` | | `recheckInterval` | no | `24h` | | `creditUnits` | no | Alchemy's documented CU table | Cost accounting: implements `CreditUnitsProvider` with Alchemy's [documented compute-unit costs](https://www.alchemy.com/docs/reference/compute-unit-costs) (`eth_call` 26, `eth_getLogs` 60, `eth_blockNumber` 10, `"*"` 20, …). The table is **auto-fetched** from the docs' Markdown endpoint (`compute-unit-costs.md`) and cached ~1 week (refreshed off the hot path from `SupportsNetwork`/`GenerateConfigs`), so pricing tracks Alchemy without a redeploy; the built-in table is the cold-start / fetch-failure fallback. `settings.creditUnits` overrides per method. [`thirdparty/alchemy.go:L186-320`](https://github.com/erpc/erpc/blob/main/thirdparty/alchemy.go#L186-L320) OwnsUpstream: `alchemy://`/`evm+alchemy://` prefix, `vendorName=="alchemy"`, or endpoint contains `.alchemy.com`/`.alchemyapi.io`. [`thirdparty/alchemy.go:L156-326`](https://github.com/erpc/erpc/blob/main/thirdparty/alchemy.go#L156-L326) #### ankr Static map of 47 chains. URL: `https://rpc.ankr.com/{netName}/{apiKey}` (URL-escaped). OwnsUpstream: scheme prefixes or `rpc.ankr.com`. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/ankr.go:L15-144`](https://github.com/erpc/erpc/blob/main/thirdparty/ankr.go#L15-L144) #### blastapi Static map of 79 chains. URL: `https://{netName}.blastapi.io/{apiKey}`; Avalanche appends `/ext/bc/C/rpc`. OwnsUpstream: scheme prefixes or `.blastapi.io`. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/blastapi.go:L15-181`](https://github.com/erpc/erpc/blob/main/thirdparty/blastapi.go#L15-L181) #### blockdaemon Static map of 18 chains with heterogeneous path shapes. **Auth is always header-based**: `apiKey` is injected as `Authorization: Bearer ` on every request regardless of whether the endpoint was preset or generated — a static upstream pointing at `svc.blockdaemon.com` fails at `NewUpstream` without `apiKey`. HTTP 401 → `ErrEndpointUnauthorized`. | key | required | default | |---|---|---| | `apiKey` | yes (even with preset endpoint) | — | [`thirdparty/blockdaemon.go:L24-156`](https://github.com/erpc/erpc/blob/main/thirdparty/blockdaemon.go#L24-L156) #### blockpi Static map of 56 chains (exported `BlockPiNetworkNames`). URL: `https://{netName}.blockpi.network/v1/rpc/{escapedKey}`; chain `movement` uses `/rpc/v1/{escapedKey}/v1`. Error mapping: message containing `apikey is on another chain` → `ErrEndpointUnauthorized`. OwnsUpstream: scheme prefixes or `.blockpi.network`. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/blockpi.go:L15-173`](https://github.com/erpc/erpc/blob/main/thirdparty/blockpi.go#L15-L173) #### chainstack Account-level node discovery: paginated GET `https://api.chainstack.com/v1/nodes/` with `Authorization: Bearer {apiKey}` and optional filter params; chain ids discovered by `eth_chainId` probe per node (concurrency-limited, semaphore 10, 10 s client timeout). Cache key includes all filter values so providers sharing an apiKey but different filters get separate snapshots. Missing `apiKey` → `(false, nil)` (silent skip). Cold cache → `ErrRemoteCacheCold`. GenerateConfigs fans out one upstream per matching running node; upstream endpoint = `https_endpoint + "/" + auth_key`; id suffix `-`. Node decode is intentionally lenient: each node is decoded individually from the paginated response and malformed nodes (type mismatches, missing fields) are skipped rather than failing the entire refresh. OwnsUpstream: scheme prefixes or `.core.chainstack.com`. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `recheckInterval` | no | `1h` | | `project` | no | `""` | | `organization` | no | `""` | | `region` | no | `""` | | `provider` | no | `""` | | `type` | no | `""` | [`thirdparty/chainstack.go:L51-429`](https://github.com/erpc/erpc/blob/main/thirdparty/chainstack.go#L51-L429) #### conduit Dynamic-only discovery from `networksUrl`; no static fallback → cold start returns `ErrRemoteCacheCold`. URL: `{httpEndpoint}/{apiKey}`. OwnsUpstream: scheme prefixes or `vendorName=="conduit"` only (no domain heuristic — chains live on customer domains). Preset endpoint bypasses discovery entirely. Error mapping: `-32600` + auth/api-key message → `ErrEndpointUnauthorized`; message `"limit exceeded"`/`"capacity limit"` → `ErrEndpointCapacityExceeded`; code in range `[-32099, -32000]` → `ErrEndpointServerSideException` (note: as written the condition `code >= -32000 && code <= -32099` is never true — same impossible-range pattern as alchemy, so this branch is dead code). | key | required | default | |---|---|---| | `apiKey` | yes | — | | `networksUrl` | no | `https://api.conduit.xyz/public/network/all` | | `recheckInterval` | no | `24h` | [`thirdparty/conduit.go:L16-222`](https://github.com/erpc/erpc/blob/main/thirdparty/conduit.go#L16-L222) #### drpc Remote catalog (default `https://lb.drpc.org/networks`) with a 150-chain static fallback; after a successful fetch the fallback is **fully replaced** (no merge). **Forces `autoIgnoreUnsupportedMethods: false`** on every config (even preset endpoints) because dRPC transiently returns method-not-found responses that must stay retryable. URL: `https://lb.drpc.org/ogrpc?network={name}&dkey={apiKey}`. Catalog filters to premium EVM JSON-RPC chains only (`blockchain_type=="eth" && api_type=="jsonrpc" && has_premium`); when multiple names map to one chain id, the highest `priority` value wins. Error mapping: message `"token is invalid"` → `ErrEndpointUnauthorized`; `"ChainException: Unexpected error (code=40000)"` or `"invalid block range"` → `ErrEndpointMissingData`. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `chainsUrl` | no | `https://lb.drpc.org/networks` | | `recheckInterval` | no | `24h` | | `creditUnits` | no | dRPC's flat CU table | Cost accounting: implements `CreditUnitsProvider` with dRPC's [documented compute-unit costs](https://drpc.org/docs/pricing/compute-units) — a **flat 20 CU** for every billable method (debug/trace included, no multiplier tier), `0` for informational methods (`eth_chainId`, `net_version`, `web3_clientVersion`, …), and `"*"` = 20 for anything unlisted; `settings.creditUnits` overrides per method. [`thirdparty/drpc.go:L207-240`](https://github.com/erpc/erpc/blob/main/thirdparty/drpc.go#L207-L240) [`thirdparty/drpc.go:L19-455`](https://github.com/erpc/erpc/blob/main/thirdparty/drpc.go#L19-L455) #### dwellir Static map of 71 chains → subdomain prefixes. URL: `https://{subdomain}.dwellir.com/{apiKey}`. OwnsUpstream: only `dwellir://` prefix (NOT `evm+dwellir://`) or `.dwellir.com` — the `evm+` form still works because shorthand conversion runs first. Avalanche appends `/ext/bc/C/rpc` to the URL. `SupportsNetwork` quirk: an unparseable numeric chain id part returns `(false, nil)` rather than an error (unlike every other static-map vendor which propagates the parse error). | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/dwellir.go:L15-180`](https://github.com/erpc/erpc/blob/main/thirdparty/dwellir.go#L15-L180) #### spectrum [Spectrum Nodes](https://spectrumnodes.com). Static map of 142 EVM chains from the public catalog at [spectrumnodes.com/networks](https://spectrumnodes.com/networks) → route and offered node types. URL: `https://{host}/{apiKey}/{network}/{mn|tn}/{chain}/{plan}/{nodeType}/rpc/`; `{chain}` is the numeric chain ID except on Cronos (`cronosmainnet_25-1`, `cronostestnet_338`), and Avalanche ends in `rpc/ext/bc/C/rpc`. A chain answers only after it is enabled in the Spectrum dashboard project that owns the key, so pair this vendor with `onlyNetworks` listing the enabled chains. OwnsUpstream: `spectrum://`, `evm+spectrum://`, or a `.simplystaking.xyz/` endpoint. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `host` | no | `spectrum-03.simplystaking.xyz` (the region host shown in the dashboard) | | `plan` | no | `shared` (`dedicated` for dedicated nodes) | | `nodeType` | no | `archive`; `pruned` to prefer pruned nodes. A chain that offers only the other type uses that type. | [`thirdparty/spectrum.go:L1-272`](https://github.com/erpc/erpc/blob/main/thirdparty/spectrum.go#L1-L272) #### envio **Method allow-list injected on every upstream** (even preset static ones): `ignoreMethods: ["*"]` + 14 read-oriented methods (`eth_getLogs`, `eth_blockNumber`, `eth_getBlockByNumber`, etc.). SupportsNetwork: 61 known chain ids short-circuit true; unknown chains are live-probed via `eth_chainId` (10 s timeout; TLS error with `"failed to verify certificate"` → false). URL: `https://{chainId}.{rootDomain}[/{apiKey}]`. | key | required | default | |---|---|---| | `rootDomain` | no | `rpc.hypersync.xyz` | | `apiKey` | no | `""` | [`thirdparty/envio.go:L20-258`](https://github.com/erpc/erpc/blob/main/thirdparty/envio.go#L20-L258) #### erpc Chains to another eRPC instance. SupportsNetwork probes live `eth_chainId`. `parseEndpointURL` appends `/{chainId}` and optionally sets `?secret=`. Port-based scheme inference applies in `settings.endpoint`; the shorthand `erpc://host:8080` forces HTTPS. Probe clients are cached per `"{url}-{chainId}"`. | key | required | default | |---|---|---| | `endpoint` | yes | — | | `secret` | no | `""` | [`thirdparty/erpc.go:L35-265`](https://github.com/erpc/erpc/blob/main/thirdparty/erpc.go#L35-L265) #### etherspot ERC-4337 bundler (Skandha). **Method allow-list injected**: `ignoreMethods: ["*"]` + 6 bundler methods (`skandha_*`, `eth_sendUserOperation`, etc.). Static map of 15 mainnets + 11 testnets. URL shape differs by network type: mainnet `https://{networkName}-bundler.etherspot.io/`, testnet `https://testnet-rpc.etherspot.io/v1/{chainId}`; `?apikey=` appended unless apiKey is `"public"` or empty. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/etherspot.go:L15-146`](https://github.com/erpc/erpc/blob/main/thirdparty/etherspot.go#L15-L146) #### infura Static map of 31 chains. URL: `https://{netName}.infura.io/v3/{apiKey}`. Error mapping: `-32600` auth message → unauthorized; `-32001`/`-32004` → unsupported; `-32005` → capacity exceeded. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/infura.go:L15-163`](https://github.com/erpc/erpc/blob/main/thirdparty/infura.go#L15-L163) #### llama Static map of 6 chains (eth, arbitrum, base, binance, optimism, polygon). URL: `https://{netName}.llamarpc.com/{apiKey}`. OwnsUpstream matches `.llamarpc.com` domain only (no `llama://` scheme check — shorthand still works because conversion runs first). Cloudflare rate-limit message (`code: 1015`) → `ErrEndpointCapacityExceeded`. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/llama.go:L14-97`](https://github.com/erpc/erpc/blob/main/thirdparty/llama.go#L14-L97) #### onfinality Static map of 25 chains. URL: `https://{netName}.api.onfinality.io/rpc?apikey={escapedKey}` (apiKey as query param). OwnsUpstream: scheme prefixes or `.api.onfinality.io`. | key | required | default | |---|---|---| | `apiKey` | yes | — | [`thirdparty/onfinality.go:L15-122`](https://github.com/erpc/erpc/blob/main/thirdparty/onfinality.go#L15-L122) #### pimlico ERC-4337 bundler/paymaster. **Method allow-list injected**: `ignoreMethods: ["*"]` + 11 bundler/paymaster methods (`pimlico_*`, `pm_*`, `eth_sendUserOperation`, etc.). SupportsNetwork: 67-chain static set short-circuits true; unknown chains probe live `eth_chainId` — **missing `apiKey` is an error** (unlike quicknode/chainstack which return `false, nil`). URL: `"public"` → `https://public.pimlico.io/v2/{chainId}/rpc`; else `https://api.pimlico.io/v2/{chainId}/rpc?apikey={apiKey}`. | key | required | default | |---|---|---| | `apiKey` | yes (error if missing, even for SupportsNetwork) | — | [`thirdparty/pimlico.go:L21-252`](https://github.com/erpc/erpc/blob/main/thirdparty/pimlico.go#L21-L252) #### quicknode Account endpoint discovery: paginated GET `https://api.quicknode.com/v0/endpoints?limit=100&offset=N` with `x-api-key` header and optional tag filters; a response-level `error` field aborts the refresh; chain ids discovered by `eth_chainId` probe per endpoint (concurrency-limited, semaphore 10, 10 s timeout). **Cache key is `apiKey` only** — two providers sharing an apiKey but different `tagIds`/`tagLabels` share one endpoint snapshot. Missing `apiKey` → `(false, nil)`. Cold cache → `ErrRemoteCacheCold`. GenerateConfigs fans out one upstream per matching endpoint; id `{upstreamId}-{endpointID}`. Full error mapping: `-32614` or (`eth_getLogs` + message `"limited to"`) → `ErrEndpointRequestTooLarge`; `-32009`/`-32007` → capacity exceeded; `-32612`/`-32613` → `ErrEndpointUnsupported`; message `"failed to parse"` → client-side, not retryable toward network; `-32010` (tx cost exceeds gas limit) → client-side but network-retryable (per-client gas caps differ); `-32602` + `"cannot unmarshal hex string"` → invalid-argument client-side, not retryable; message `"UNAUTHORIZED"` → unauthorized; code `3` → EVM revert. Note: the error handler builds a fresh local details map, so per-request `details` passed by the caller are not modified. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `recheckInterval` | no | `1h` | | `tagIds` | no | `nil` | | `tagLabels` | no | `nil` | | `creditUnits` | no | QuickNode's published credit model | Cost accounting: implements `CreditUnitsProvider`. When the account `apiKey` is set, the **account-accurate** per-method table is **auto-fetched** from QuickNode's Admin API ([`GET /v0/api-credits/{chain}`](https://www.quicknode.com/docs/admin-api/api-credits/v0-api-credits-chain), `x-api-key`; the chain slug is resolved from the already-discovered endpoint list) and cached ~1 week off the hot path. The built-in [published model](https://www.quicknode.com/api-credits) (base 20 on EVM, 2x debug/trace = 40, 4x trace replays = 80) is the fallback when no key is set or the fetch fails. `settings.creditUnits` overrides per method. [`thirdparty/quicknode.go:L28-120`](https://github.com/erpc/erpc/blob/main/thirdparty/quicknode.go#L28-L120) [`thirdparty/quicknode.go:L44-452`](https://github.com/erpc/erpc/blob/main/thirdparty/quicknode.go#L44-L452) #### repository Fetches `repositoryUrl` returning `{"": {"endpoints": [...]}}`. No static fallback → `ErrRemoteCacheCold` on cold start. **Defaults `autoIgnoreUnsupportedMethods: true`** — public RPCs are inconsistent in method support. GenerateConfigs fans out one upstream per http endpoint (http/https prefix only; ws/wss skipped); ids embed `RedactEndpoint(ep)` (`https#redacted=ab12c`) so dashboards can distinguish endpoints without exposing them. Each generated upstream gets deep copies of `Evm`, `JsonRpc`, `Failsafe` (per-element), `RateLimitAutoTune`, and `Tags` from the base config, and inherits `IgnoreMethods`, `AllowMethods`, and `RateLimitBudget`. OwnsUpstream: only `repository://`/`evm+repository://` scheme prefixes (no domain matching — generated upstreams have arbitrary third-party hosts). One half of the implicit default provider pair. | key | required | default | |---|---|---| | `repositoryUrl` | no | `https://evm-public-endpoints.erpc.cloud` | | `recheckInterval` | no | `1h` | [`thirdparty/repository.go:L17-232`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L17-L232) #### routemesh No chain catalog — SupportsNetwork always probes live `eth_chainId`. Missing `apiKey` → error (provider task retries forever). URL: `https://{baseURL}/rpc/{chainId}/{apiKey}`. Shorthand requires exact path shape `/rpc//` or config-load error. | key | required | default | |---|---|---| | `apiKey` | yes (error if missing) | — | | `baseURL` | no | `lb.routemes.sh` | [`thirdparty/routemesh.go:L20-167`](https://github.com/erpc/erpc/blob/main/thirdparty/routemesh.go#L20-L167) #### superchain OP Superchain registry. `parseSuperchainSpec` accepts: `github.com/org/repo` (defaults branch `main`, file `chainList.json`), `github.com/org/repo/branch`, `github.com/org/repo/branch/path/to/file.json`, GitHub UI blob/tree URLs (the `/blob/` or `/tree/` segment is stripped), full `http(s)://` URLs passed through, or bare `domain/path` (https prepended). GitHub specs are rewritten to raw.githubusercontent.com. Registry JSON is an array of `{chainId, rpc:[...]}`; entries with chainId ≤ 0 or empty rpc list dropped; no static fallback → `ErrRemoteCacheCold`. GenerateConfigs fans out one upstream per rpc URL with id suffix `-{index}` (e.g. `{id}-0`, `{id}-1`, …). OwnsUpstream: scheme prefixes or `vendorName=="superchain"` only (no domain matching). | key | required | default | |---|---|---| | `registryUrl` | no | `https://raw.githubusercontent.com/ethereum-optimism/superchain-registry/main/chainList.json` | | `recheckInterval` | no | `24h` | [`thirdparty/superchain.go:L16-312`](https://github.com/erpc/erpc/blob/main/thirdparty/superchain.go#L16-L312) #### tenderly Remote catalog from hardcoded `https://api.tenderly.co/api/v1/supported-networks` (not overridable via settings — there is no `chainsUrl`-style override). No static fallback → `ErrRemoteCacheCold`. Catalog decodes `chain_id` + `network_slugs`; slug preference: `node_rpc_slug` > `vnet_rpc_slug` > `explorer_slug`; entries with no usable slug or unparseable chain id are skipped. URL: `https://{slug}.gateway.tenderly.co/{apiKey}`. OwnsUpstream: scheme prefixes, `vendorName=="tenderly"`, or `.gateway.tenderly.co`. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `recheckInterval` | no | `24h` | [`thirdparty/tenderly.go:L34-285`](https://github.com/erpc/erpc/blob/main/thirdparty/tenderly.go#L34-L285) #### thirdweb No chain catalog — SupportsNetwork always probes live `eth_chainId`. Missing `clientId` → error. URL: `https://{chainId}.rpc.thirdweb.com/{clientId}`. | key | required | default | |---|---|---| | `clientId` | yes (error if missing) | — | [`thirdparty/thirdweb.go:L35-141`](https://github.com/erpc/erpc/blob/main/thirdparty/thirdweb.go#L35-L141) #### willow Remote catalog (default `https://api.willow.tech/v1/rpc/chains`) with a 7-chain static fallback (1, 10, 130, 4663, 8453, 42161, 57073); after a successful fetch the fallback is **fully replaced** (no merge). The catalog is `{"chains":[{"id":…,"name":…},…]}` and only `id` is read: an entry without a positive integer `id` is skipped (debug log), and a failed fetch (a connection error, a non-2xx status, unparseable JSON, or a response with no readable entry) keeps the previous snapshot or the fallback (warn log). The URL is built for any chain id, so `onlyNetworks` can add one the catalog lacks. URL: `https://api.willow.tech/v1/rpc/{chainId}/{escapedKey}`. No method list and no vendor error mapping: Willow answers `-32601` for a method the key's plan does not serve, and the generic normalizer maps its other errors (pinned in `willow_test.go`, [`thirdparty/willow_test.go:L252-308`](https://github.com/erpc/erpc/blob/main/thirdparty/willow_test.go#L252-L308)). OwnsUpstream: scheme prefixes or an endpoint containing `://api.willow.tech/`. | key | required | default | |---|---|---| | `apiKey` | yes | — | | `chainsUrl` | no | `https://api.willow.tech/v1/rpc/chains` | | `recheckInterval` | no | `24h` | [`thirdparty/willow.go:L17-191`](https://github.com/erpc/erpc/blob/main/thirdparty/willow.go#L17-L191) ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Multi-vendor setup with score de-weighting.** Production fleets use Alchemy as the premium primary and cheaper providers (dRPC, Envio) as volume fillers. The `scoreMultipliers` `overall` factor deliberately de-weights weaker vendors so the scorer favors Alchemy on latency-sensitive methods while still using them as backfill: **Config path:** `projects[].providers[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main providers: - id: alchemy vendor: alchemy settings: # premium vendor — no score penalty apiKey: \${ALCHEMY_KEY} # keep Alchemy away from chains where it adds no value or costs more ignoreNetworks: [evm:999] overrides: # catch-all: apply rate limit budget + light de-weight so fast vendors win "evm:*": rateLimitBudget: alchemy-global routing: scoreMultipliers: - network: "" method: "" # 0.2 = use as 20% of baseline score — Alchemy only wins when # others are slow, erroring, or behind on block head overall: 0.2 - id: drpc vendor: drpc settings: apiKey: \${DRPC_KEY} - id: envio vendor: envio settings: rootDomain: rpc.hypersync.xyz ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", providers: [ { id: "alchemy", vendor: "alchemy", settings: { apiKey: process.env.ALCHEMY_KEY }, ignoreNetworks: ["evm:999"], overrides: { "evm:*": { rateLimitBudget: "alchemy-global", routing: { scoreMultipliers: [{ network: "", method: "", overall: 0.2 }], }, }, }, }, { id: "drpc", vendor: "drpc", settings: { apiKey: process.env.DRPC_KEY }, }, { id: "envio", vendor: "envio", settings: { rootDomain: "rpc.hypersync.xyz" }, }, ], }], }); ``` **2. Per-chain getLogs splitting via provider overrides.** High-throughput chains (Arbitrum, Sei) routinely hit block-range limits when indexers issue large `eth_getLogs` queries. Production sets `getLogsAutoSplittingRangeThreshold` per chain inside the provider's `overrides` so every upstream that vendor auto-generates for that chain inherits the limit without wiring individual upstreams: **Config path:** `projects[].providers[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main providers: - id: quicknode vendor: quicknode settings: apiKey: \${QN_KEY} ignoreNetworks: [evm:1, evm:8453, evm:42161] overrides: # catch-all: slow down state polling on every QN chain (it polls fast by default) "evm:*": evm: # 10s is a safe floor; most chains don't need sub-second head tracking statePollerInterval: 10s routing: scoreMultipliers: - network: "" method: "" # 0.3 = mid-tier weight; QN is good but not the fastest in tests overall: 0.3 # Arbitrum produces enormous logs — split at 1000 blocks before upstream rejects "evm:42161": evm: getLogsAutoSplittingRangeThreshold: 1000 # Sei has aggressive range limits — split at 500 "evm:1329": evm: getLogsAutoSplittingRangeThreshold: 500 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", providers: [{ id: "quicknode", vendor: "quicknode", settings: { apiKey: process.env.QN_KEY }, ignoreNetworks: ["evm:1", "evm:8453", "evm:42161"], overrides: { "evm:*": { evm: { statePollerInterval: "10s" }, routing: { scoreMultipliers: [{ network: "", method: "", overall: 0.3 }], }, }, "evm:42161": { evm: { getLogsAutoSplittingRangeThreshold: 1000 } }, "evm:1329": { evm: { getLogsAutoSplittingRangeThreshold: 500 } }, }, }], }], }); ``` **3. Provider-level method exclusions to avoid bad upstreams.** Some vendors (dwellir, blockpi) do not support `trace_filter` reliably on testnets. Production adds `ignoreMethods` per-chain inside `overrides` so auto-generated upstreams for those chains never receive trace requests that would 405-error and burn retry budget: **Config path:** `projects[].providers[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main providers: - id: dwellir vendor: dwellir settings: apiKey: \${DWELLIR_KEY} # skip chains covered by better vendors — avoids redundant SupportsNetwork probes ignoreNetworks: [evm:1, evm:137, evm:42161, evm:8453] overrides: # Sepolia and BSC testnet: trace_filter returns errors on dwellir — exclude it # so the scorer doesn't keep retrying it "evm:11155111": ignoreMethods: [trace_filter] "evm:97": ignoreMethods: [trace_filter] ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", providers: [{ id: "dwellir", vendor: "dwellir", settings: { apiKey: process.env.DWELLIR_KEY }, ignoreNetworks: ["evm:1", "evm:137", "evm:42161", "evm:8453"], overrides: { "evm:11155111": { ignoreMethods: ["trace_filter"] }, "evm:97": { ignoreMethods: ["trace_filter"] }, }, }], }], }); ``` **4. ERC-4337 bundler alongside general RPC.** Pimlico and etherspot auto-inject method allow-lists so only bundler methods route to them — combine with a general-purpose provider for all other methods. No manual `allowMethods` needed; the vendor injects it at `NewUpstream` time: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - endpoint: alchemy://\${ALCHEMY_KEY} # pimlico auto-injects: ignoreMethods: ["*"] + allowMethods: [eth_sendUserOperation, # pimlico_*, pm_*] — bundler traffic routes here automatically - endpoint: pimlico://\${PIMLICO_KEY} ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreams: [ { endpoint: \`alchemy://\${process.env.ALCHEMY_KEY}\` }, // pimlico auto-injects ignoreMethods/allowMethods — no manual filter needed { endpoint: \`pimlico://\${process.env.PIMLICO_KEY}\` }, ], }], }); ``` **5. QuickNode with tag-based endpoint groups.** Use separate `apiKey` values per tag group — the RemoteDataCache is keyed by `apiKey` only, so two providers sharing one key with different `tagIds`/`tagLabels` both see whichever snapshot the first refresh produced: **Config path:** `projects[].providers[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main providers: # archive-grade endpoints tagged in the QuickNode dashboard as "archive" - id: quicknode-archive vendor: quicknode settings: # must be a DIFFERENT apiKey than the realtime group — # same apiKey + different tagLabels still shares one endpoint snapshot apiKey: \${QN_ARCHIVE_KEY} tagLabels: archive # fast tip-of-chain endpoints on a separate key - id: quicknode-realtime vendor: quicknode settings: apiKey: \${QN_REALTIME_KEY} tagLabels: realtime ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", providers: [ { id: "quicknode-archive", vendor: "quicknode", // must be a DIFFERENT apiKey than the realtime group settings: { apiKey: process.env.QN_ARCHIVE_KEY, tagLabels: "archive" }, }, { id: "quicknode-realtime", vendor: "quicknode", settings: { apiKey: process.env.QN_REALTIME_KEY, tagLabels: "realtime" }, }, ], }], }); ``` ### Best practices - Use **URL shorthands** (`alchemy://KEY`) for the common case — they are equivalent to a full `providers[]` entry with a `"*"` override and avoid boilerplate. - Use **`onlyNetworks`** to restrict expensive vendors to the chains you actually need; it also prevents the vendor's `SupportsNetwork` from being called for irrelevant chains. - Use **exact `evm:` keys** in `overrides` — never mix a catch-all `"*"` with more-specific patterns in the same map. Go map iteration is nondeterministic; overlapping keys produce different results across restarts. - For **QuickNode** with multiple logical endpoint groups, use a separate `apiKey` per group (provisioned in the QuickNode dashboard). Sharing one `apiKey` with different `tagIds`/`tagLabels` shares one endpoint snapshot due to the apiKey-only cache key. - **`recheckInterval` cannot be set from YAML or TypeScript config.** The type assertion `.(time.Duration)` fails on YAML strings and JSON numbers. Use programmatic Go config (`common.VendorSettings{"recheckInterval": 12 * time.Hour}`) if you need a custom freshness window. - Vendors with no static fallback (conduit, superchain, tenderly, quicknode, chainstack, repository) return `ErrRemoteCacheCold` on cold start. The initializer retries with backoff, but first requests for those networks will see `ErrNetworkInitializing` until the remote catalog fetches. Pair these vendors with a fallback provider that has a static map if cold-start latency matters. - **Do not use `providers: []` to "disable" auto-injection** — an explicit empty providers list still triggers default injection if upstreams is also empty. Provide at least one upstream or one provider to take full control. ### Edge cases & gotchas 1. **`recheckInterval` from YAML is silently ignored** — every vendor reads it with `.(time.Duration)`. YAML scalars decode to `string`/`int64` so the assertion fails and the vendor default applies. Only Go programmatic config can set it. [`thirdparty/repository.go:L56-59`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L56-L59) 2. **Cold-start contract differs by vendor**: alchemy/drpc/willow fall back to built-in maps; conduit/superchain/tenderly/quicknode/chainstack/repository return `ErrRemoteCacheCold` and block until the first remote fetch lands. [`thirdparty/remote_cache.go:L85`](https://github.com/erpc/erpc/blob/main/thirdparty/remote_cache.go#L85) 3. **drpc and willow replace their fallback after a successful fetch** (no merge); alchemy merges fetched data with its static defaults (API wins on conflict, static fills gaps). [`thirdparty/drpc.go:L269-283`](https://github.com/erpc/erpc/blob/main/thirdparty/drpc.go#L269-L283) [`thirdparty/alchemy.go:L628-633`](https://github.com/erpc/erpc/blob/main/thirdparty/alchemy.go#L628-L633) [`thirdparty/willow.go:L90-104`](https://github.com/erpc/erpc/blob/main/thirdparty/willow.go#L90-L104) 4. **Missing-apiKey behavior is inconsistent**: pimlico/routemesh/thirdweb `SupportsNetwork` return an error (provider task retries forever); quicknode/chainstack return `(false, nil)` and are silently skipped. [`thirdparty/pimlico.go:L120-123`](https://github.com/erpc/erpc/blob/main/thirdparty/pimlico.go#L120-L123) 5. **blockdaemon requires `apiKey` even with a preset endpoint** — static upstreams pointing at `svc.blockdaemon.com` fail at `NewUpstream` because `GenerateConfigs` is called with `settings=nil`. [`thirdparty/blockdaemon.go:L85-88`](https://github.com/erpc/erpc/blob/main/thirdparty/blockdaemon.go#L85-L88) 6. **Impossible range conditions in alchemy/conduit error mapping**: alchemy's `code >= -32099 && code <= -32599` can never be true; only the message-match and code-3 branches actually fire. [`thirdparty/alchemy.go:L275-326`](https://github.com/erpc/erpc/blob/main/thirdparty/alchemy.go#L275-L326) 7. **infura's Avalanche `/ext/bc/C/rpc` branch is unreachable** — map keys are `avalanche-mainnet`/`avalanche-fuji` but branch tests `ava-mainnet`/`ava-testnet`. [`thirdparty/infura.go:L90-93`](https://github.com/erpc/erpc/blob/main/thirdparty/infura.go#L90-L93) 8. **`overrides` first-match is Go map-iteration order** (nondeterministic for overlapping patterns). Pattern-match errors are silently skipped. [`thirdparty/provider.go:L81-91`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L81-L91) 9. **quicknode cache key is `apiKey` only** — two providers with the same apiKey but different `tagIds`/`tagLabels` share one endpoint snapshot. Chainstack includes filters in its cache key and is safe. [`thirdparty/quicknode.go:L184-205`](https://github.com/erpc/erpc/blob/main/thirdparty/quicknode.go#L184-L205) 10. **`erpc://host:8080` shorthand forces HTTPS** — `buildProviderSettings` hardcodes `https://`. Use `providers[].settings.endpoint` with an explicit URL for non-TLS targets. [`common/defaults.go:L1389-1404`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1389-L1404) 11. **`onlyNetworks`/`ignoreNetworks` are exact string matches** (not wildcards), require `evm:`, and are mutually exclusive. `ignoreNetworks` is dropped from `MarshalJSON`. [`thirdparty/provider.go:L34-49`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L34-L49) 12. **`os.ExpandEnv` runs on every provider-generated endpoint** — a literal `$` in an API key is substituted from the environment (often to empty). Static upstreams do not get this treatment. [`thirdparty/provider.go:L63-71`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L63-L71) 13. **Provider ids must be unique only by convention** — no duplicate-id check; two providers with the same default id both run and may produce upstream-id collisions. [`thirdparty/providers_registry.go:L15-34`](https://github.com/erpc/erpc/blob/main/thirdparty/providers_registry.go#L15-L34) 14. **repository upstream ids embed a redacted endpoint** (`https#redacted=ab12c` = scheme + 5-char sha256 prefix) so dashboards can distinguish public endpoints without exposing them. [`util/redact.go:L10-36`](https://github.com/erpc/erpc/blob/main/util/redact.go#L10-L36) 15. **OP-stack `"sender is over rate limit"` is the only capacity error with `retryableTowardNetwork=false`** — all OP providers proxy the same sequencer, so retrying on a different upstream hits the same limit. Expect this error to surface to clients on OP-stack chains. [`architecture/evm/error_normalizer.go:L125-139`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L125-L139) 16. **Tenderly `"not found"` becomes `ErrEndpointClientSideException`** (retryable), not `ErrEndpointMissingData` — the `"Unsupported"` block in the normalizer intentionally runs after `"Not found"` to avoid misclassifying Tenderly's bare `"not found"`. [`architecture/evm/error_normalizer.go:L394-477`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L394-L477) 17. **dwellir `OwnsUpstream` only matches `dwellir://` prefix** (not `evm+dwellir://`) or `.dwellir.com` domain; the `evm+` shorthand still works because shorthand conversion runs before vendor lookup. [`thirdparty/dwellir.go:L173-180`](https://github.com/erpc/erpc/blob/main/thirdparty/dwellir.go#L173-L180) 18. **Live-probe vendors dial out during routing decisions**: envio/erpc/pimlico/routemesh/thirdweb perform a real `eth_chainId` HTTP call (10 s timeout) on the provider bootstrap path. Probe clients are cached forever in `sync.Map`s keyed by chain id or `"{url}-{chainId}"`. 19. **`PrepareUpstreamsForNetwork` succeeds as soon as one upstream registers** (`minReady=1`). Slow providers continue adding upstreams in the background without blocking the first request. If all provider tasks finish with zero upstreams, there is a 100 ms grace re-check before the retryable `ErrNetworkNotSupported` is returned; if tasks are still running, the caller receives `ErrNetworkInitializing`. [`upstream/registry.go:L188-293`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L188-L293) 20. **`LookupByUpstream` with an explicit but non-existent `vendorName` returns nil** — it does not fall through to `OwnsUpstream` matching. If `upstream.vendorName` is set to an unregistered name, vendor error-mapping is silently lost. Registration order of the 26 vendors determines which vendor wins when multiple `OwnsUpstream` checks return true for the same endpoint. [`thirdparty/vendors_registry.go:L58-75`](https://github.com/erpc/erpc/blob/main/thirdparty/vendors_registry.go#L58-L75) 21. **`llama` and `routemesh` `OwnsUpstream` do not check their own scheme prefixes**: `llama.OwnsUpstream` only matches `.llamarpc.com`; `routemesh.OwnsUpstream` only matches `vendorName=="routemesh"` or endpoint containing `routemes.sh`. Both shorthands (`llama://`, `routemesh://`) work only because shorthand conversion in `common/defaults.go` runs before vendor lookup. [`thirdparty/llama.go:L95-97`](https://github.com/erpc/erpc/blob/main/thirdparty/llama.go#L95-L97) [`thirdparty/routemesh.go:L135-140`](https://github.com/erpc/erpc/blob/main/thirdparty/routemesh.go#L135-L140) 22. **dwellir `SupportsNetwork` returns `(false, nil)` for an unparseable chain id** — unlike every other static-map vendor which propagates the parse error. [`thirdparty/dwellir.go:L109-113`](https://github.com/erpc/erpc/blob/main/thirdparty/dwellir.go#L109-L113) 23. **A willow key enabled for only some chains still gets an upstream on any other catalog chain that eRPC prepares.** Willow answers the other chains with HTTP 403, so their `eth_chainId` detection fails and the initializer keeps retrying them. Set `onlyNetworks` to the key's chains. [`upstream/upstream.go:L1349-1361`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1349-L1361) ### Observability No provider-specific Prometheus metrics exist. The `vendor` label on all upstream-level metrics is populated from the attached vendor's `Name()`, the config's `vendorName`, or `unknown-` for unrecognized endpoints. | metric | type | key labels | when it fires | |---|---|---|---| | `erpc_upstream_request_total` | counter | `project, vendor, network, upstream, category, attempt, composite, finality, user, agent_name` | Every upstream request attempt | | `erpc_upstream_request_duration_seconds` | histogram | `project, vendor, network, upstream, category, composite, finality, user` | Upstream round-trip latency | | `erpc_upstream_request_errors_total` | counter | `project, vendor, network, upstream, category, error, severity, composite, finality, user, agent_name` | Failed upstream requests | Bootstrap task progress is visible in initializer task names: `network//provider/` (scheduling) and `network//upstream/` (per-generated upstream). [`upstream/registry.go:L423-481`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L423-L481) Trace spans: `buildProviderBootstrapTask` emits a detail span per provider task; `buildUpstreamBootstrapTask` emits one for each registered upstream. [`upstream/registry.go:L423-485`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L423-L485) Notable log messages: - warn `no providers or upstreams found in project; will use default 'public' endpoints repository` - debug `attempting to create upstream(s) from provider` / debug `provider does not support network; skipping upstream creation` / info `registering N upstream(s) from provider` - error `failed to execute provider bootstrap tasks` / info `provider bootstrap tasks executed successfully` - warn `vendor remote-data refresh failed; keeping previous snapshot` with `vendor` + `cacheKey` fields - error `panic recovered during vendor remote-data async refresh` - warn `some quicknode chain ID fetches failed; continuing with available data` / warn `failed to fetch chain IDs for some QuickNode endpoints` - warn `some chainstack chain ID fetches failed; continuing with available data` / warn `failed to fetch chain IDs for some Chainstack nodes` - info `successfully fetched dRPC network names` (with count + url) - info `successfully fetched Willow chains` (with count + url) / debug `skipping unreadable Willow chain entry` - debug `generated upstream from alchemy provider` / `generated upstream from conduit provider` / `generated upstreams from repository provider` / `generated upstreams from superchain provider` ### Source code entry points - [`thirdparty/vendors_registry.go:L9-39`](https://github.com/erpc/erpc/blob/main/thirdparty/vendors_registry.go#L9-L39) — global 26-vendor registry; `LookupByName` / `LookupByUpstream` / `SupportedVendors` - [`thirdparty/providers_registry.go:L15-34`](https://github.com/erpc/erpc/blob/main/thirdparty/providers_registry.go#L15-L34) — per-project ProviderConfig → Provider binding; unknown-vendor startup error - [`thirdparty/provider.go:L13-162`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L13-L162) — `SupportsNetwork` gating, `GenerateUpstreamConfigs`, id templating, env expansion - [`thirdparty/remote_cache.go:L13-78`](https://github.com/erpc/erpc/blob/main/thirdparty/remote_cache.go#L13-L78) — `RemoteDataCache[T]` algorithm; request-path safety rationale; `ErrRemoteCacheCold` - [`common/defaults.go:L1113-1241`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1113-L1241) — default-provider injection, shorthand upstream→provider conversion - [`common/defaults.go:L1243-1425`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1243-L1425) — `buildProviderSettings` per-vendor settings derivation - [`upstream/registry.go:L155-293`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L155-L293) — lazy `PrepareUpstreamsForNetwork`, provider task scheduling, readiness wait loop - [`common/validation.go:L780-815`](https://github.com/erpc/erpc/blob/main/common/validation.go#L780-L815) — ProviderConfig validation rules - [`architecture/evm/error_normalizer.go:L878-900`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L878-L900) — vendor-specific error hook invocation ### Related pages - [Upstreams](/config/projects/upstreams.llms.txt) — static upstream entries; providers generate these dynamically. - [Selection policies](/config/projects/selection-policies.llms.txt) — controls which generated upstream handles each request. - [Failsafe](/config/failsafe/retry.llms.txt) — configure retry/hedge/timeout inside `overrides` per network. - [Rate limiters](/config/rate-limiters.llms.txt) — cap per-vendor request rates to stay within API budgets. - [Auth](/config/auth.llms.txt) — protect your eRPC instance when proxying to paid vendor endpoints. --- --- # Selection & scoring > Source: https://docs.erpc.cloud/config/projects/selection-policies > eRPC ranks your upstreams every 15 seconds using live health data — bad actors drop out automatically, the fastest healthy provider goes first, and re-admission is metric-driven, not timer-driven. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Selection & scoring Every 15 seconds eRPC scores all your upstreams using real error rates, latency quantiles, throttle rates, and block-head lag. The worst performers drop out automatically; a shadow prober keeps sampling them in the background so they rejoin the moment their numbers recover — no timer, no manual intervention. Your requests always flow to the fastest healthy provider available. **What you get** - Slow or flapping providers silently demoted without any config change - Fallback tier activates only when healthy upstreams run out - Sticky-primary routing prevents flapping between nearly-equal upstreams - Dry-run `shadowExcludeIf` lets you test new exclusion rules before they bite - Near-zero routing overhead: the request path does a single atomic load ## Quick taste This is the **exact default policy that ships in eRPC** ([`internal/policy/default_policy.js`](https://github.com/erpc/erpc/blob/main/internal/policy/default_policy.js)) — you get this behavior with zero config. It's shown wired explicitly so you can use it as the starting point for your own tweaks: **Config path:** `projects[].networks[].selectionPolicy` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } selectionPolicy: evalFunc: | (upstreams, ctx) => upstreams .removeCordoned() // Errors / throttle: drop upstreams that are clearly broken, gated // on samplesAbove(10) so a single failed call can't evict a fresh- // pod upstream. Thresholds are loose — failsafe (retry/hedge/ // consensus) already absorbs occasional failures. .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) .excludeIf(all(samplesAbove(10), throttleRateAbove(0.4))) // Latency: only exclude when the upstream is BOTH absolutely slow // AND consistently slower than peers across most of what it // serves. Two-stage check: // // 1. \`latencyAbove(3000)\` — absolute-latency floor. Drops the // deviation predicate entirely for upstreams below 3s p70. // Sub-3s upstreams stay in rotation regardless of how they // compare to a faster peer; \`sortByScore(PREFER_FASTEST)\` puts // them later in the ordered list and hedge catches the slack // on the request path. The 3s threshold is the "user-visible // pain" boundary — anything below is recoverable via hedge, // anything above starts hitting tail-latency SLOs. // // 2. \`latencyDeviationAbove(3, majority)\` — only AFTER passing // the absolute floor, also check the upstream is consistently // slower than peers. \`mode: 'majority'\` (more than half of the // per-method comparisons exceed 3×) keeps the predicate robust // against per-tick spikes on a single rare method that // would otherwise push a geomean over the threshold. The // lower multiplier (3 vs the older 10) is intentional — once // we've established the upstream is absolutely slow, a 3× // ratio is a strong "consistently behind peers" signal. // // Outer \`latencyAbove(10_000)\` is the catastrophic safety net // (>10s absolute, unconditional exclusion regardless of peers or // sample count). // // Outer \`samplesAbove(20)\` gates on aggregate counts so the // predicate doesn't even run on cold-start pods. .excludeIf(any(all(samplesAbove(20), latencyAbove(3000), latencyDeviationAbove(3, { mode: 'majority' })), latencyAbove(10_000))) // Block-head lag: drop if behind tip by ≥16 blocks or ≥30s. Not // probed: the state poller refreshes lag, probes cannot. .excludeIf(any(blockNumberLagAbove(16), blockSecondsLagAbove(30)), { probe: false }) // Outage safety net: if everyone failed the health excludes, fall // back to the raw set rather than failing closed. .whenEmpty(() => upstreams) // Tier split: prefer non-fallback; fall back to tier:fallback if no // primary survives. .preferTag('!tier:fallback', { minHealthy: 1, fallback: 'tier:fallback' }) // Rank survivors by p70 latency. .sortByScore(PREFER_FASTEST) // Hold the primary stable across ticks unless a meaningfully better // option exists for ≥30s. .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: '30s' }) // Shadow-mirror sampled real traffic to upstreams excluded for // errors, throttling or latency, in the background, so they // accumulate fresh tracker samples without touching real user // traffic. Per-upstream opt-out via \`routing.probe: off\`. .probeExcluded({ sampleRate: 0.1, minSamples: 10, minSamplesWindow: '60s', maxConcurrent: 4, timeout: '10s' }) ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, selectionPolicy: { evalFunc: (upstreams, ctx) => upstreams .removeCordoned() // Errors / throttle: drop upstreams that are clearly broken, gated // on samplesAbove(10) so a single failed call can't evict a fresh- // pod upstream. Thresholds are loose — failsafe (retry/hedge/ // consensus) already absorbs occasional failures. .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) .excludeIf(all(samplesAbove(10), throttleRateAbove(0.4))) // Latency: two-stage check — absolute floor (3s p70) AND consistently // slower than peers (3× majority), with a catastrophic >10s safety net. // samplesAbove(20) gates cold-start pods. (Full rationale: see the // shipped default_policy.js.) .excludeIf(any(all(samplesAbove(20), latencyAbove(3000), latencyDeviationAbove(3, { mode: "majority" })), latencyAbove(10_000))) // Block-head lag: drop if behind tip by ≥16 blocks or ≥30s. Not // probed: the state poller refreshes lag, probes cannot. .excludeIf(any(blockNumberLagAbove(16), blockSecondsLagAbove(30)), { probe: false }) // Outage safety net: fall back to the raw set rather than failing closed. .whenEmpty(() => upstreams) // Tier split: prefer non-fallback; use tier:fallback when no primary survives. .preferTag("!tier:fallback", { minHealthy: 1, fallback: "tier:fallback" }) // Rank survivors by p70 latency. .sortByScore(PREFER_FASTEST) // Hold the primary stable unless a meaningfully better option exists ≥30s. .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: "30s" }) // Background-probe excluded upstreams with sampled real traffic. .probeExcluded({ sampleRate: 0.1, minSamples: 10, minSamplesWindow: "60s", maxConcurrent: 4, timeout: "10s" }), }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure selection policy from scratch** ```text I need to set up a smart upstream selection policy for my eRPC config so that slow or erroring providers are demoted automatically and my fastest healthy upstreams always serve traffic. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/projects/selection-policies.llms.txt ``` **Prompt Example #2: tune my exclusion thresholds without outages** ```text Audit the selectionPolicy in my eRPC config and tell me if my errorRateAbove / throttleRateAbove / latencyAbove thresholds are too aggressive (would exclude upstreams spuriously) or too loose (would keep broken upstreams in rotation too long). Also show me how to use shadowExcludeIf to validate a tighter rule safely before promoting it. Reference: https://docs.erpc.cloud/config/projects/selection-policies.llms.txt ``` **Prompt Example #3: debug why an upstream is stuck excluded** ```text One of my upstreams is stuck excluded and never re-admits even after the outage clears. Help me diagnose using erpc_selection_position, erpc_selection_exclusion_total, and erpc_selection_probe_requests_total, and fix the policy or routing.probe setting so re-admission is metric-driven. Config in my eRPC config. Reference: https://docs.erpc.cloud/config/projects/selection-policies.llms.txt ``` **Prompt Example #4: add a cost-tier fallback upstream** ```text I want to add an expensive archival node to my eRPC setup that only receives traffic when all my free-tier upstreams are unhealthy. Wire it up with scoreMultipliers overall demotion and a preferTag tier:fallback split so it stays on standby. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/selection-policies.llms.txt ``` **Prompt Example #5: switch to per-method ranking for eth_getLogs** ```text My eRPC setup uses the default evalScope: network which means all methods share one upstream ranking. I want eth_getLogs to rank upstreams by freshness (PREFER_FRESHEST) while reads use speed (PREFER_FASTEST). Walk me through switching evalScope and any scoreMultipliers.method gotchas I need to know. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/projects/selection-policies.llms.txt ``` --- ### Selection & scoring — full agent reference ### How it works The entry point is `policy.Engine`, which owns a map of `*Slot` values keyed by `(network, method, finality)`. Each slot has its own ticker goroutine; the request path reads `slot.cache` via `atomic.Pointer.Load()` — completely wait-free. On every tick the engine takes a metric snapshot from the health tracker, builds an `EvalContext`, acquires a pooled Sobek JS runtime, calls the compiled eval function, materializes the ordered result, and atomically swaps the cache. The whole cycle completes in under a millisecond for typical policy chains. When `Engine.RegisterNetwork` is called at network bootstrap it: 1. Upgrades the placeholder `evalFunc` to `default_policy.js` (embedded at compile time). 2. Creates the wildcard `("*","*")` slot and runs a **synchronous** initial tick — the first request always sees a populated cache. 3. Starts the slot's ticker goroutine. The default `evalScope: "network"` creates one slot per network. Setting `evalScope: "network-method"` lazy-creates additional slots on first request for each distinct method, enabling per-method primary divergence. `evalScope: "network-finality"` splits on finality bucket; `"network-method-finality"` is the most granular. Narrow slots fall back to the wildcard slot cache during cold-start until their first tick completes. **Score inputs (health tracker).** Every metric available to `evalFunc` comes from the health tracker's rolling window. The tracker maintains 10 atomic sub-buckets per `(upstream, method, finality)` tuple; one bucket rotates out every `windowSize / 10`, so data drips out with no cliff. A DDSketch per bucket (1% relative accuracy) produces p50/p70/p90/p95/p99 latency quantiles. `errorRate` counts only genuine upstream-quality failures: connection refused, 5xx, genuine timeouts. EVM reverts, rate-limit 429s, oversized-request rejections (`ErrEndpointRequestTooLarge`), client disconnects, and hedge cancellations are deliberately excluded so a misbehaving caller or aggressive hedger cannot inflate a healthy upstream's error rate. `throttledRate` counts remote 429 responses specifically — vendor quota exhaustion. `misbehaviorRate` tracks upstreams returning semantically wrong data. Latency quantiles come from successful responses plus cancelled primary attempts (another attempt won the hedge race, or the client gave up), which count at their elapsed time as a lower bound. Deadlines count as errors, not latency. An upstream that never answers before the hedge or the client gives up therefore reads at least that elapsed time, not `0`. A client that cancels early (one that races several providers and drops the loser) caps the bound at its own wait: the order of upstreams holds, but an absolute bar such as `latencyAbove(1000)` trips only when clients wait longer than the bar. A fast-failing upstream that rejects connections in 1ms has empty quantile sketches and reports `p70 = 0` (unknown quality, not ultra-fast). A well-written policy should guard `latencyAbove` with `samplesAbove(N)`. `blockHeadLag` and `finalizationLag` are atomic point-in-time state, not rolling counters. They persist across window rotations and stay non-zero until the upstream catches up to the network tip. `blockHeadLagSeconds` and `finalizationLagSeconds` multiply the block count by the tracker's EMA-estimated block time (alpha 0.1, minimum 3 samples before publishing). Until the EMA is warm, both seconds fields are `0` — pair `blockSecondsLagAbove` with `blockNumberLagAbove` for cold-start coverage. **The default policy chain.** Omitting `evalFunc` applies the production-hardened default embedded at compile time: ```js (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) .excludeIf(all(samplesAbove(10), throttleRateAbove(0.4))) .excludeIf(any( all(samplesAbove(20), latencyAbove(3000), latencyDeviationAbove(3, { mode: 'majority' })), latencyAbove(10_000) )) .excludeIf(any(blockNumberLagAbove(16), blockSecondsLagAbove(30)), { probe: false }) .whenEmpty(() => upstreams) .preferTag('!tier:fallback', { minHealthy: 1, fallback: 'tier:fallback' }) .sortByScore(PREFER_FASTEST) .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: '30s' }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, minSamplesWindow: '60s', maxConcurrent: 4, timeout: '10s' }) ``` Each `excludeIf` step records per-leaf attribution into `erpc_selection_exclusion_total{reason}`. The `whenEmpty` safety net prevents fail-closed behavior during a widespread outage. `stickyPrimary` prevents flapping: the challenger must score more than 30% above the incumbent AND the last switch must be at least 30 seconds ago. `probeExcluded` shadow-mirrors 10% of real traffic to upstreams excluded for errors, throttling or latency, so re-admission happens the moment their metrics recover. Lag exclusions are not probed: the state poller re-admits them as soon as the upstream catches up. **Probe eligibility (which excluded upstreams get shadow traffic).** Not every exclusion benefits from probing, so exclude-family steps record a per-upstream probe verdict: `excludeIf(...)` defaults to probe-**eligible** (the predicate reads traffic metrics that freeze without traffic — probes are how the upstream proves recovery), while `excludeTag(...)` and `removeCordoned()` default to probe-**blocking** (static/admin exclusions don't reverse via traffic data, so probing them only burns quota). Each accepts an override: `excludeTag('tier:reserve', { probe: true })`, `excludeIf(blockNumberLagAbove(16), { probe: false })` — the default policy uses the latter for its lag rule, because the state poller refreshes lag regardless of traffic and probes cannot. Verdicts combine order-insensitively across the whole chain: every exclude step judges every upstream it *would* drop (including upstreams already dropped by earlier steps), and an excluded upstream is probed iff at least one probe-eligible step excludes it **and** no probe-blocking step does — so an upstream that is both erroring and tag-excluded is not probed, regardless of step order. Upstreams excluded only by untracked means (raw `filter`, `take`, …) default to probing. `routing.probe: 'off'` remains the per-upstream hard veto on top. The resolved verdict is visible per upstream in the decision output (`ProbeEligible`). **Scoring formula and presets.** `sortByScore` ranks surviving upstreams by: ``` score(u) = overall / (1 + errorRate×w₁ + respLatency×w₂ + throttledRate×w₃ + blockHeadLag×w₄ + finalizationLag×w₅ + misbehaviors×w₆) ``` A clean upstream with no penalties scores `1.0`; every unit of penalty divides the score. A lag term counts blocks, but never more than seconds of lag: `min(blockHeadLag, blockHeadLagSeconds)`, and the same for `finalizationLag`. On chains with blocks of 1 s or slower, and while the block-time EMA is cold, it is the block count; on sub-second chains it is seconds, so 0.4 s behind costs 0.4, not the 4 blocks it is at 10 blocks/s. Three built-in weight presets: | Preset | errorRate | respLatency | throttledRate | blockHeadLag | finalizationLag | misbehaviors | |---|---|---|---|---|---|---| | `PREFER_FASTEST` | 4 | 15 | 4 | 1 | 0 | 2 | | `PREFER_FRESHEST` | 4 | 2 | 2 | 15 | 8 | 3 | | `PREFER_LEAST_ERRORS` | 15 | 2 | 6 | 2 | 1 | 12 | Per-upstream `routing.scoreMultipliers` on the upstream config merge with the chosen preset. The default merge mode (`"merge"`) lets individual multiplier keys override the base weight; `overall` multiplies the final score and is the simplest way to strongly prefer or demote a specific upstream without touching weight shapes. **Circuit-breaker interplay.** The selection policy and the [circuit breaker](/config/failsafe/circuit-breaker.llms.txt) are complementary layers that act at different points and timescales. The policy runs per eval tick and excludes upstreams from the ranked list via `excludeIf` predicates over rolling-window metrics. The circuit breaker is a per-upstream state machine *inside the upstream executor*: it is checked only after the sweep has already dispatched to that upstream (selection runs first). When the breaker is open, `TryAcquirePermit()` fails the attempt immediately with `ErrFailsafeCircuitBreakerOpen` — no transport call is made — and the sweep advances to the next upstream in the policy's ordered list. So an upstream can sit at position 0 in the policy list with an open breaker: each request burns one cheap fast-fail attempt there before moving on, until the policy's own metrics demote it on a later tick. Neither mechanism reads the other's state (breaker-open does not cordon or exclude); they only interact through outcomes. If the split bothers you, align breaker thresholds with the policy's `errorRateAbove` so both layers agree on what "broken" means. Source: [`upstream/upstream_executor.go:L345-L366`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L345-L366). **`shadowExcludeIf` — dry-run exclusion rules.** `shadowExcludeIf(predicate)` is the non-destructive counterpart of `excludeIf`. The predicate runs every tick; would-have-been-excluded upstreams stay in the ordered list but each trip increments `erpc_selection_shadow_exclusion_total{upstream, reason}` with the same leaf-slug attribution. Use it to measure a new rule's blast radius before promoting it to `excludeIf`. **`blockMethods` — per-method exclusion.** `blockMethods({ match, when, probe? })` skips an upstream for single methods while it keeps serving all others. For each upstream and each method with samples that matches `match` (glob or array), `when` runs with `u.metrics` set to that method's numbers (`requestsTotal`, `latencyP`), so `samplesAbove` and `latencyAbove` work; rate predicates do not trip. A trip removes the upstream from that method's list at request time. If blocks would leave a method no upstream, all stay. Blocked upstreams receive probe traffic for that method unless `probe: false`. Each block increments `erpc_selection_method_block_total{method, upstream, reason}`. The step works at `evalScope: 'network'`. **`includeIf` — conditional re-admission (pool-level quantifiers).** `includeIf(target, condition)` is the dual of `excludeIf`: it ADDS upstreams from the full universe back into the chain when an aggregate condition over the *surviving pool* holds — it never removes anyone. `target` comes first ("include *these* if *condition*"): a tag pattern (`'tier:reserve'`, `!` negation supported) or a selector object `{id, tag, vendor, type, position}` whose facets AND together; an object with no concrete facet (`{}`, `{position:'head'}`) is a deliberate no-op so it can never accidentally admit the entire universe. Admitted upstreams land at the tail by default (`position: 'head'` available in object form), are never duplicated by id, and are ranked by the subsequent `sortByScore` like everyone else. `condition` is a boolean or `(pool, ctx) => boolean` receiving the current chain — which is what enables pool-level ("network-level") questions via native array methods over the per-upstream predicate factories: `p.every(blockSecondsLagAbove(30))`, `p.length < 2`. Mind that native `every` is `true` on an empty array — guard with `p.length > 0 &&` when the empty pool should be handled by a separate explicit `p.length < 1` line. Malformed arguments and throwing conditions degrade to a no-op rather than sinking the eval. Source: [`internal/policy/stdlib/stdlib.js:L1023-L1116`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L1023-L1116); tests: [`internal/policy/stdlib/include_if_test.go`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/include_if_test.go). **Additional stdlib chain methods.** Beyond `excludeIf` / `includeIf`, the JS stdlib installs the following chainable `Array.prototype` methods (source: [`internal/policy/stdlib/stdlib.js`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js)): - **Identity/label filters**: `byId(id)`, `excludeId(id)`, `byTag(pat)`, `excludeTag(pat)`, `byVendor(name)`, `excludeVendor(name)`, `byType(t)`, `where(fn)`, `whereNot(fn)`. - **Health filters** (higher-level wrappers): `removeCordoned()`, `removeByErrorRate(threshold)`, `removeByThrottling(threshold)`, `removeByMisbehavior(threshold)`, `removeByLag(blocks)`, `removeByLatency(ms)`, `keepHealthy()`, `removeByMinRequests(n)`. - **Tier selection**: `preferTag(pat, opts?)`, `preferVendor(name, opts?)`. - **Diversity**: `spreadAcrossTags(prefix)` — interleaves the sorted list so adjacent positions come from different tag-partitions (e.g. `"region:"`). - **Safety net**: `whenEmpty(fn)` — falls back to `fn()` if the array is empty. - **Conditional/finality branching**: `when(mask, fn)`, `byFinality(handlers)`, `if(cond, fn)`, `unless(cond, fn)`, `fallbackTo(fn)`, `ensureMin(n, fn)`. **`hasMatchingTag` semantics** (used by `byTag`, `excludeTag`, `preferTag`, `includeIf` string targets — [`internal/policy/stdlib/stdlib.js:L267-293`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L267-L293)): - Positive pattern (`"tier:main"`, `"region:us-*"`): matches if ANY tag on the upstream matches. - Negated pattern (`"!tier:fallback"`): matches if NO tag matches the un-negated pattern. - Array of patterns: positives are OR'd; negations are AND'd. Upstream matches iff (no positives OR at least one positive matches) AND (all negations hold). **`preferTag` step semantics** ([`internal/policy/stdlib/stdlib.js:L854-865`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L854-L865)): 1. Filter to upstreams matching the primary pattern. 2. If ≥ `minHealthy` match → return that subset. 3. Else if `fallback` pattern is set → filter to the fallback pattern. 4. Else → return the input unchanged. **Upstream JS object shape** (built by `buildJSUpstreams` at [`internal/policy/eval.go:L312`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L312)): | Field | Type | Source | |---|---|---| | `id` | `string` | `u.Id()` | | `vendor` | `string` | `u.VendorName()` | | `type` | `string` | `cfg.Type` | | `tags` | `string[]` | `cfg.Tags` | | `hasTag(tag)` / `is(tag)` | `(tag: string) => boolean` | Shared VM singleton | | `metrics` | `UpstreamMetrics` | Slot-local metrics snapshot | | `metricsAcrossMethods` | `UpstreamMetrics` | Wildcard aggregate `("*", All)` | | `metricsByMethod` | `{[method]: {requestsTotal, p50ms, p70ms, p90ms, p95ms, p99ms}}` | Per-method, all-finalities | | `scoreMultipliers` | `{[key]: float64}` or absent | From `resolveScoreMultipliers` | | `score` | `float64` (set by `sortByScore`) | `overall / (1 + penalty)`; higher = better | **`UpstreamMetrics` object shape** (`u.metrics` and `u.metricsAcrossMethods` — [`internal/policy/eval.go:L283`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L283)): | Field | Type | Notes | |---|---|---| | `errorRate` | `float64` | EMA rolling error rate | | `errorsTotal` | `int64` | Cumulative error count | | `requestsTotal` | `int64` | Cumulative request count (window-bounded) | | `throttledRate` | `float64` | EMA rolling throttle (429) rate | | `misbehaviorRate` | `float64` | EMA rolling misbehavior rate | | `blockHeadLag` | `int64` | Blocks behind network tip | | `finalizationLag` | `int64` | Finalization blocks behind tip | | `blockHeadLagSeconds` | `float64` | `blockHeadLag × networkBlockTime`; `0` until EMA warms | | `finalizationLagSeconds` | `float64` | `finalizationLag × networkBlockTime`; `0` until EMA warms | | `p50ResponseSeconds` | `float64` | p50 latency in seconds | | `p70ResponseSeconds` | `float64` | p70 latency in seconds | | `p90ResponseSeconds` | `float64` | p90 latency in seconds | | `p95ResponseSeconds` | `float64` | p95 latency in seconds | | `p99ResponseSeconds` | `float64` | p99 latency in seconds | | `cordonedReason` | `string` or absent | Set when upstream is cordoned | | `latencyP(q)` | `(q: number) => ms` | Snaps to nearest pre-computed bucket; input 0–1 or 0–100 | The block-time EMA used to compute `blockHeadLagSeconds`/`finalizationLagSeconds` has sanity bounds: values outside `[10ms, 120s]` are rejected and the internal EMA is reset to the last published value to prevent post-halt spikes. **`EvalContext` (`ctx`) shape** ([`internal/policy/eval.go:L17`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L17)): | Field | Notes | |---|---| | `network` | Network ID string | | `method` | Slot method (`"*"` for wildcard slots) | | `finality` | Slot finality (`"unknown"` default for wildcard; real value for per-finality slots) | | `now` | Unix milliseconds | | `previousOrder` | `string[]` upstream IDs from the last tick | | `lastSwitchAt` | `int64` unix-ms or `null` | | `tickCount` | `uint64` monotonic tick counter | Global JS helpers available inside every `evalFunc`: - `methodMatches(pat)` — tests `ctx.method` against a pattern - `isFinalityRequest()` — `ctx.finality === 'finalized'` - Preset globals: `PREFER_FASTEST`, `PREFER_FRESHEST`, `PREFER_LEAST_ERRORS` - Finality bit-flag constants: `REALTIME` (1), `UNFINALIZED` (2), `FINALIZED` (4), `UNKNOWN` (8) — used with `.when(mask, fn)` inside eval; NOT for `scoreMultipliers.finality` config fields **Exclusion attribution leaf slugs.** `excludeIf` records which leaf predicate actually tripped per upstream. Bounded-cardinality slugs emitted by `erpc_selection_exclusion_total{reason}`: `error_rate_above`, `error_rate_below`, `throttle_rate_above`, `throttle_rate_below`, `misbehavior_rate_above`, `credit_pace_above`, `credit_pace_below`, `credit_remaining_above`, `credit_remaining_below`, `latency_p_above`, `latency_p_deviation_above`, `block_head_lag_above`, `finalization_lag_above`, `block_head_lag_seconds_above`, `finalization_lag_seconds_above`, `samples_below`, `samples_above` (guard — not a failure slug), `not_`, `custom`. **Prepaid credit pacing.** For an upstream with `creditAllowance`, `u.creditPace` is the vendor account's credits used this billing period over the allowance pro-rated to now (`1.0` spends exactly the allowance by period end), and `u.creditRemaining` is allowance minus credits used. Predicates: `creditPaceAbove(x)`, `creditPaceBelow(x)`, `creditRemainingAbove(n)`, `creditRemainingBelow(n)`. Both fields are absent with no allowance, before the first usage reading, or when the reading is over 30 minutes old; every credit predicate is then false, so the policy keeps its usual order. Fill a prepaid vendor ahead of per-call vendors while behind pace, and stop it near the allowance. Only upstreams whose endpoint is on the allowance account get the fields: ```js const live = upstreams.excludeIf(creditRemainingBelow(4e9), { probe: false }); const hangs = all(samplesAbove(20), latencyAbove(1000, 90), latencyDeviationAbove(3, { mode: 'veto', quantile: 90 })); return live.filter(all(creditPaceBelow(1.0), not(hangs))).union(live); ``` `hangs` keeps a prepaid upstream out of the fill while its p90 is over 1 s and over 3× a peer's on some method; it then ranks by score like the rest. Without it, the fill puts an upstream that hangs some reads first even when a peer answers them in a fraction of the time. Size the `creditRemainingBelow` margin above the credits the account bills during the vendor's usage-reporting lag (QuickNode: 2-3 h of hourly buckets; Alchemy: about 1 minute) plus the 5-minute refresh and the stale window. Note: `samplesAbove`/`samplesBelow` predicates are marked `isGuard=true` so they do not appear as primary exclusion reasons when they do NOT trip; they only appear when they are the leaf that fires. **Log messages emitted by the selection engine:** - `WARN "selection policy eval failed; retaining previous cache"` — tick error; fields: `network`, `method`, `tick_id`, `error`. - `DEBUG "policy step"` — one line per stdlib step when step-logging is enabled; fields: `network`, `method`, `tick_id`, `idx`, `step`, `in`, `out`, `dropped`, `added`, `reordered`, `args`. Disabled by default in production (zero overhead: no allocation when disabled). - `DEBUG "policy excluded upstream"` — one per excluded upstream when step-logging is enabled; fields: `network`, `method`, `tick_id`, `upstream`, `step`, `reason`, `leaf_reasons`. **Legacy upstream tag keys.** Upstream-level `group: ` and `cohort: ` YAML keys are rewritten as `tier:` and `cohort:` tags at config-load time by `mergeLegacyLabelKeysIntoTags`. They are not valid in new configs. ### Config schema #### `selectionPolicy` (`networks[].selectionPolicy`) Full YAML path: `projects[].networks[].selectionPolicy` Config struct: `SelectionPolicyConfig` at [`common/config.go:L2352-2430`](https://github.com/erpc/erpc/blob/main/common/config.go#L2352-L2430) Defaults: [`common/defaults.go:L2512-2609`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2512-L2609) | Field | Type | Default | Footguns | |---|---|---|---| | `evalInterval` | `Duration` | `15s` ([`common/defaults.go:L2532`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2532)) | `0` disables the ticker (frozen cache); tests only. Should be ≥ 3× `scoreMetricsWindowSize / 10` for stable quantile reads. An upstream that registers after its network started is evaluated at once, not at the next tick. | | `evalTimeout` | `Duration` | `100ms` ([`common/defaults.go:L3125-3126`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L3125-3126)) | Exceeded → warning logged and `timeout` counted; the eval cannot be interrupted, so its result is still applied. Must be `< evalInterval`. | | `evalScope` | `EvalScope` enum | `"network"` ([`common/defaults.go:L2556-2583`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2556-2583)) | `"network"` \| `"network-method"` \| `"network-finality"` \| `"network-method-finality"`. Narrower scopes multiply goroutines and JS evals. `scoreMultipliers.method`-specific entries **never match** in `"network"` scope because `ctx.method == "*"`. | | `evalPerMethod` | `*bool` | `nil` — **deprecated** | Pointer-bool alias for the method axis. `SetDefaults` nils it unconditionally and derives `evalScope` instead. Excluded from TS surface (`tstype:"-"`). | | `evalPerFinality` | `*bool` | `nil` — **deprecated** | Same mechanics as `evalPerMethod` for the finality axis. Niled by `SetDefaults`. | | `evalFunc` | `string` (JS source) | `DefaultSelectionPolicySource` placeholder → upgraded to `default_policy.js` at engine register | Full JS function `(upstreams, ctx) => Upstream[]`. In TS configs, a real arrow function is stringified via `Function.prototype.toString()` at load time. | **EvalScope slot cardinality:** | `evalScope` | Slots per network | Goroutines | Notes | |---|---|---|---| | `"network"` (default) | 1 | 1 | `ctx.method` always `"*"`; method-specific `scoreMultipliers` never match. | | `"network-method"` | 1 per observed method, lazy-created | N methods | Slots evicted after 1h idle. `scoreMultipliers.method` works correctly here. | | `"network-finality"` | Up to 4 (one per finality bucket) | Up to 4 | `ctx.method` still `"*"`; method-specific multipliers still never match. | | `"network-method-finality"` | Up to `methods × 4` | N × 4 | Highest granularity. Both `scoreMultipliers.method` and `.finality` match. | **Legacy fields (accepted, never survive to runtime):** | YAML key | Behavior | |---|---| | `evalFunction` | Old `(upstreams, method) => Upstream[]` shape. Wrapped into the new signature if no canonical `evalFunc` is also set. Emits `WarnLegacySelectionPolicy()`. | | `resampleExcluded` | When `true` AND `resampleInterval > 0`, appends `.probeExcluded({ sampleRate: 1.0, maxConcurrent: 1, timeout: '10s' })` to the synthesized eval. | | `resampleInterval` | Legacy polling cadence. The actual duration value is **ignored**; only its presence gates `probeExcluded` synthesis. | | `resampleCount` | No behavioral mapping. Checked in `hasSemanticLegacy` but never used in synthesized output. | #### `upstream.routing` (`upstreams[].routing`) | Field | YAML key | Type | Default | Notes | |---|---|---|---|---| | `ScoreMultipliers` | `scoreMultipliers` | `[]*ScoreMultiplierConfig` | `nil` | First matching entry wins. | | `ScoreLatencyQuantile` | `scoreLatencyQuantile` | `float64` | `0` (inherits policy default p70) | Declared; not yet wired into the scoring engine. | | `Probe` | `probe` | `ProbeMode` | `"on"` ([`common/config.go:L773`](https://github.com/erpc/erpc/blob/main/common/config.go#L773)) | `"off"` = never mirror probe traffic; upstream stays excluded until metrics naturally recover or operator uncordons. | #### `ScoreMultiplierConfig` fields | Field | YAML key | Type | Notes | |---|---|---|---| | `Network` | `network` | `string` | Glob; empty = any. | | `Method` | `method` | `string` | Glob; empty = any. **Specific methods never match in `evalScope: "network"` wildcard slots.** | | `Finality` | `finality` | `[]DataFinalityState` | Integer enum: `"finalized"` (0), `"unfinalized"` (1), `"realtime"` (2), `"unknown"` (3). **Not the same as JS bit-flag constants** `FINALIZED=4`, `REALTIME=1`, `UNFINALIZED=2` used in `evalFunc` bodies. | | `Overall` | `overall` | `*float64` | Multiplies final score. `>1` = prefer, `<1` = demote. `nil` = unset (inherit base). | | `ErrorRate` | `errorRate` | `*float64` | Weight override for error-rate term. `0.0` = removes contribution. | | `RespLatency` | `respLatency` | `*float64` | Weight override for latency term. | | `ThrottledRate` | `throttledRate` | `*float64` | Weight override for throttle-rate term. | | `BlockHeadLag` | `blockHeadLag` | `*float64` | Weight override for block-head-lag term. | | `FinalizationLag` | `finalizationLag` | `*float64` | Weight override for finalization-lag term. | | `Misbehaviors` | `misbehaviors` | `*float64` | Weight override for misbehavior-rate term. | | `TotalRequests` | `totalRequests` | `*float64` | **Accepted silently; has zero runtime effect.** Never read by any scoring code. Kept for backward YAML compatibility. | Merge modes (set via `sortByScore({ multipliers: 'merge' | 'override' | 'off' })`): - `"merge"` (default): per-upstream keys override matching base-weight keys; `overall` lifts final score multiplicatively. - `"override"`: configured upstreams rank by their weights only; unconfigured fall back to base. - `"off"`: ignore `u.scoreMultipliers` entirely. #### `probeExcluded` options (JS) Defaults from [`internal/policy/eval.go:L793-799`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L793-L799) and [`internal/policy/stdlib/stdlib.js:L999-1009`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L999-L1009). | Option | Default | Notes | |---|---|---| | `sampleRate` | `0.1` | 0.0–1.0 probability per `(request, excluded-upstream)`. Bypassed when `count < minSamples`. | | `minSamples` | `10` | Per-upstream floor within `minSamplesWindow`. Below this, every request is a probe candidate. Should be ≥ `samplesAbove(N)` in the chain. | | `minSamplesWindow` | `"60s"` | Rolling window for `minSamples`. | | `maxConcurrent` | `4` | In-flight probe cap per excluded upstream. | | `timeout` | `"10s"` | Per-probe deadline. Overrun records a failure in the tracker. | #### `stickyPrimary` options (JS) Defaults from [`internal/policy/stdlib/stdlib.js:L725-727`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L725-L727). | Option | Default | Notes | |---|---|---| | `hysteresis` | `0.10` (default policy uses `0.30`) | Challenger must exceed incumbent score by this fraction to trigger switch. | | `minSwitchInterval` | `"30s"` | Cooldown after a switch. No switching during cooldown regardless of score gap. | | `scope` | `"network"` | `"network"` \| `"network-method"` \| `"network-finality"` \| `"network-method-finality"`. Coarser scopes share the sticky register across slots. | #### `latencyDeviationAbove` options (JS) Defaults from [`internal/policy/stdlib/stdlib.js:L1343-1358`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L1343-L1358). | Option | Default | Notes | |---|---|---| | `quantile` | `70` | p50/p70/p90/p95/p99. | | `mode` | `"geomean"` | `"geomean"` \| `"majority"` \| `"veto"`. | | `minMethodSamples` | `50` | Per-method sample floor; methods below this are skipped. | | `dampingMs` | `30` | Exponential damping scale. Ratio is multiplied by `1 - exp(-myLatency / dampingMs)`. Set to `0` to disable. | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Production default: the full default policy chain with scoreMetricsWindowSize.** In production every project sets `scoreMetricsWindowSize` explicitly — this controls how fast exclusion decisions react to upstream changes. Shorter windows react faster but are noisier; `4m` is the production-proven sweet spot. The default `evalFunc` is omitted here (eRPC loads `default_policy.js` automatically), so only the project-level window and `upstreamDefaults.routing` matter: **Config path:** `projects[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main # 4-minute rolling window for health tracker metrics — fast enough to react # to a flapping upstream without being too jittery on cold-start pods. scoreMetricsWindowSize: 4m scoreMetricsMode: compact networkDefaults: # selectionPolicy omitted → eRPC loads the embedded default_policy.js failsafe: - matchMethod: "*" hedge: quantile: 0.95 maxCount: 1 minDelay: 500ms maxDelay: 10s upstreamDefaults: routing: scoreMultipliers: # Realtime/unfinalized: heavily weight latency AND block-head lag — # a lagging upstream on tip-of-chain traffic is worse than a slow one. - finality: [realtime, unfinalized] respLatency: 10 errorRate: 2 misbehaviors: 5 blockHeadLag: 15 finalizationLag: 2 # Finalized/unknown: latency matters more than lag for archive queries. - finality: [unknown, finalized] respLatency: 15 errorRate: 2 misbehaviors: 10 blockHeadLag: 10 finalizationLag: 2 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", // 4-minute rolling window for health tracker metrics. scoreMetricsWindowSize: "4m", scoreMetricsMode: "compact", upstreamDefaults: { routing: { scoreMultipliers: [ { // Realtime/unfinalized: heavily weight latency AND block-head lag. finality: [DataFinalityStateRealtime, DataFinalityStateUnfinalized], respLatency: 10, errorRate: 2, misbehaviors: 5, blockHeadLag: 15, finalizationLag: 2, }, { // Finalized/unknown: latency matters most for archive queries. finality: [DataFinalityStateUnknown, DataFinalityStateFinalized], respLatency: 15, errorRate: 2, misbehaviors: 10, blockHeadLag: 10, finalizationLag: 2, }, ], }, }, }] ``` **2. Vendor demotion with `overall` multiplier (real provider pattern).** Some vendors are less reliable or more expensive — instead of hard-excluding them, apply a fractional `overall` multiplier so they serve as implicit fallbacks. Production uses `0.2` for Alchemy and `0.3` for QuickNode across all networks: **Config path:** `upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: my-alchemy-node endpoint: https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_API_KEY} evm: { chainId: 1 } routing: scoreMultipliers: # overall: 0.2 pushes this upstream to position 3–4 behind free-tier # nodes. It still serves traffic when primaries are excluded; a hard # exclude would waste the paid capacity entirely. - overall: 0.2 - id: my-quicknode-node endpoint: https://example.quiknode.pro/\${QUICKNODE_API_KEY}/ evm: { chainId: 1 } routing: scoreMultipliers: # 0.3 keeps QuickNode as a mid-tier — ahead of Alchemy (0.2) but # behind free-tier primaries (no multiplier = score 1.0 baseline). - overall: 0.3 ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [ { id: "my-alchemy-node", endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_API_KEY}", evm: { chainId: 1 }, routing: { scoreMultipliers: [ // 0.2 puts Alchemy at the back of the pack, preserving capacity // without removing it from rotation when primaries are down. { overall: 0.2 }, ], }, }, { id: "my-quicknode-node", endpoint: "https://example.quiknode.pro/\${QUICKNODE_API_KEY}/", evm: { chainId: 1 }, routing: { scoreMultipliers: [{ overall: 0.3 }], }, }, ] ``` **3. Latency-sensitive API with preferred upstream and tier:fallback.** A latency-sensitive use case (MEV, trading) uses one high-quality primary with a `overall: 1.5` multiplier to keep it at position 0, and a paid archival node tagged `tier:fallback` that only activates when no primary survives: **Config path:** `projects[].networks[].selectionPolicy` **YAML — `erpc.yaml`:** ```yaml selectionPolicy: evalScope: network evalFunc: | (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.5))) // Drop upstreams >8 blocks behind tip — stale state is dangerous for // trading. Pair with blockNumberLagAbove for cold-start coverage since // blockSecondsLagAbove is 0 until the block-time EMA warms (>=3 pairs). .excludeIf(any(blockNumberLagAbove(8), blockSecondsLagAbove(15))) .whenEmpty(() => upstreams) .preferTag('!tier:fallback', { minHealthy: 1, fallback: 'tier:fallback' }) .sortByScore(PREFER_FASTEST) // Lower hysteresis (0.20) than default: switch primaries faster when // the challenger is 20%+ better — acceptable for low-latency routing. .stickyPrimary({ hysteresis: 0.20, minSwitchInterval: '15s' }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, timeout: '5s' }) ``` **TypeScript — `erpc.ts`:** ```typescript selectionPolicy: { evalScope: "network", evalFunc: (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.5))) .excludeIf(any(blockNumberLagAbove(8), blockSecondsLagAbove(15))) .whenEmpty(() => upstreams) .preferTag("!tier:fallback", { minHealthy: 1, fallback: "tier:fallback" }) .sortByScore(PREFER_FASTEST) .stickyPrimary({ hysteresis: 0.20, minSwitchInterval: "15s" }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, timeout: "5s" }), } ``` **4. Freshness-critical workload (indexer / subgraph node).** A subgraph node or NFT indexer queries finalized blocks and needs the freshest data. `PREFER_FRESHEST` ranks by block-head lag and finalization lag instead of raw latency. Tighter lag guards (`blockNumberLagAbove(3)`) drop a node the moment it falls behind, and `probeExcluded` ensures re-admission is immediate when it catches up: **Config path:** `projects[].networks[].selectionPolicy` **YAML — `erpc.yaml`:** ```yaml selectionPolicy: evalScope: network evalFunc: | (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) // Finalization lag guard: drop upstreams that haven't finalized recent // blocks — crucial for indexers reading finalized state only. .excludeIf(any(blockNumberLagAbove(3), finalizationLagAbove(2))) .whenEmpty(() => upstreams) // PREFER_FRESHEST: weights blockHeadLag×15 and finalizationLag×8 vs // PREFER_FASTEST's respLatency×15. Use this when stale data is worse // than slow data. .sortByScore(PREFER_FRESHEST) .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: '30s' }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, timeout: '10s' }) ``` **TypeScript — `erpc.ts`:** ```typescript selectionPolicy: { evalScope: "network", evalFunc: (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) .excludeIf(any(blockNumberLagAbove(3), finalizationLagAbove(2))) .whenEmpty(() => upstreams) // PREFER_FRESHEST weights blockHeadLag and finalizationLag over latency. .sortByScore(PREFER_FRESHEST) .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: "30s" }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, timeout: "10s" }), } ``` **5. Auditing a new exclusion rule without risk (`shadowExcludeIf`).** Before tightening a throttle-rate guard on production, run it in shadow mode: the predicate fires and increments a metric, but no upstream is actually dropped. Watch `erpc_selection_shadow_exclusion_total{reason="throttle_rate_above"}` for a few hours, then promote to `excludeIf` when the fire rate looks acceptable: ```js (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) // Shadow dry-run: fires the metric without excluding — safe to deploy first. // Check erpc_selection_shadow_exclusion_total{reason="throttle_rate_above"}. .shadowExcludeIf(all(samplesAbove(10), throttleRateAbove(0.2))) .whenEmpty(() => upstreams) .sortByScore(PREFER_FASTEST) .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: '30s' }) .probeExcluded({ sampleRate: 0.1, minSamples: 10, timeout: '10s' }) ``` **5b. Blocking one slow method on one upstream (`blockMethods`).** Keep an upstream for `eth_call` and logs, but skip it for traces while its trace p99 is over 5s: ```js (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) .blockMethods({ match: ['debug_trace*', 'trace_*'], when: all(samplesAbove(20), latencyAbove(5000, 99)), }) .whenEmpty(() => upstreams) .sortByScore(PREFER_FASTEST) .probeExcluded({ sampleRate: 0.05, minSamples: 10, timeout: '10s' }) ``` **6. Reserve tier — break-glass inclusion (`includeIf`).** Keep a pricier or rate-limited provider (tagged `tags: ["tier:reserve"]`) out of normal rotation, and bring it in only when the serving pool is *collectively* unfit — every survivor lagging or slow, or none left. Because `includeIf` adds rather than evicts, a single degraded primary never pulls the reserve in by itself; once admitted, `sortByScore` ranks reserve and survivors together. Keep both halves of the pattern: `excludeTag` declares the tier is out of normal rotation, `includeIf` declares the only conditions under which it returns — reading the pair top-to-bottom documents why the reserve exists. Pair with `routing.probe: off` on the reserve upstreams to also keep shadow-probe traffic off them while benched: ```js (upstreams, ctx) => upstreams .removeCordoned() .excludeIf(all(samplesAbove(10), errorRateAbove(0.7))) // Reserve stays out of normal rotation... .excludeTag('tier:reserve') // ...and returns ONLY when survivors are collectively lagging or slow. // The `length > 0 &&` guard matters: native `every` is true on an empty // pool, so the empty case is handled by its own explicit line below. .includeIf('tier:reserve', (p) => p.length > 0 && p.every(blockSecondsLagAbove(30))) .includeIf('tier:reserve', (p) => p.length > 0 && p.every(latencyAbove(2000, 99))) .includeIf('tier:reserve', (p) => p.length < 1) .sortByScore(PREFER_FASTEST) .stickyPrimary({ hysteresis: 0.30, minSwitchInterval: '30s' }) ``` ### Request/response behavior - The ordered upstream list is set on `req` via `req.SetUpstreams(upsList)`; the failsafe layer (hedge/retry) walks through it sequentially, never selecting the same upstream twice per execution. `req.ConsumedUpstreams` and `req.ErrorsByUpstream` sync.Maps track what has been tried. [`erpc/networks.go:L1023-L1074`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1023-L1074) - If `policyEngine == nil` or `GetOrdered` returns an empty list (engine not yet ticked), the network falls back to raw upstream registry order. [`erpc/networks.go:L1032-1038`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1032-L1038) - `RegisterNetwork` fires a **synchronous initial tick** before returning, so in practice the first request always sees a populated cache. [`internal/policy/engine.go:RegisterNetwork:L305`](https://github.com/erpc/erpc/blob/main/internal/policy/engine.go#L305) - On any tick error (`timeout`, `throw`, `invalid_return`), the **previous cache is retained unchanged** — routing continues on the last-good order. [`internal/policy/slot.go:L250-L263`](https://github.com/erpc/erpc/blob/main/internal/policy/slot.go#L250-L263) - An OpenTelemetry span `"PolicyEngine.GetOrdered"` wraps the `GetOrdered` call in the request path. Attributes: `upstreams.count`, `upstreams.sorted` (detailed tracing only). ### Best practices - **Pair `samplesAbove(N)` with every rate predicate.** `errorRateAbove(0.7)` on an upstream with 2 samples (1 failure → 50% rate) will exclude it spuriously. `all(samplesAbove(10), errorRateAbove(0.7))` waits for a statistically meaningful window. The default policy uses `samplesAbove(10)` for error/throttle and `samplesAbove(20)` before the latency-deviation check. - **Use `blockNumberLagAbove(N)` as the primary lag guard, not `blockSecondsLagAbove`.** The seconds variant is `0` until the block-time EMA warms (requires ≥3 block pairs). On cold start, `blockNumberLagAbove(16)` fires correctly; `blockSecondsLagAbove(30)` silently no-ops. - **Keep `evalScope: "network"` unless you genuinely need per-method ranking.** Each additional scope dimension multiplies ticker goroutines and JS eval cycles. If you need method-specific `scoreMultipliers`, set `evalScope: "network-method"` — without it, method-specific entries silently no-op. - **Don't set `routing.probe: "off"` on upstreams you care about recovering.** With probing off, an excluded upstream accumulates no shadow samples and only recovers when structural signals (lag clearing, etc.) naturally drive re-admission. Probing is what makes re-admission fast. - **Let `whenEmpty(() => upstreams)` stay in every policy.** Without it, a simultaneous spike in error rates across all upstreams returns `ErrUpstreamsExhausted` rather than degraded-but-working traffic. Fail-open is almost always better than fail-closed for RPC routing. - **Use `overall` multipliers rather than custom weight shapes for simple up/down-ranking.** A `scoreMultipliers: [{overall: 0.1}]` on a backup upstream cleanly demotes it without changing the scoring formula for everyone else. - **`stickyPrimary` hysteresis of `0.30` is conservative; lower it for faster recovery.** At `0.30`, a challenger must score 30% better than the incumbent. For setups with very similar upstreams, `0.15` may be more responsive without causing flapping. ### Edge cases & gotchas 1. **`scoreMultipliers.method` silently no-ops in `evalScope: "network"`.** `WildcardMatch("eth_getLogs", "*")` returns `false`. Entries with a specific `Method` field are only applied in per-method or per-method-finality slots. [`internal/policy/eval.go:resolveScoreMultipliers:L442`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L442) 2. **`blockHeadLagSeconds` / `finalizationLagSeconds` are `0` until block-time EMA warms.** The EMA requires ≥3 `(blockNumber, blockTimestamp)` pairs with differing timestamps. Predicates like `blockSecondsLagAbove(30)` silently no-op until then. Use `blockNumberLagAbove(16)` as the primary guard. [`internal/policy/eval.go:L89-96`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L89-L96) 3. **`whenEmpty(() => upstreams)` prevents fail-closed.** If every `excludeIf` rule fires simultaneously (project-wide outage), the safety net restores the full unfiltered set. The network sends traffic to degraded upstreams rather than returning `ErrUpstreamsExhausted`. [`internal/policy/default_policy.js:L46`](https://github.com/erpc/erpc/blob/main/internal/policy/default_policy.js#L46) 4. **No time-based re-admission.** An excluded upstream stays excluded until its tracker metrics actually improve. `probeExcluded` accelerates re-admission by feeding fresh samples; arbitrary time passage does not. [`erpc/networks_selection_policy_test.go:TestNetworkPolicy_NoTimeBasedReadmit_OnlyMetricsHeal`](https://github.com/erpc/erpc/blob/main/erpc/networks_selection_policy_test.go) 5. **`routing.probe: "off"` permanently excludes from probing.** The upstream accumulates no shadow samples and stays excluded until structural signals (e.g. lag clearing) naturally drive re-admission, or an operator manually uncordons. [`common/config.go:L784-788`](https://github.com/erpc/erpc/blob/main/common/config.go#L784-L788) 6. **`stickyPrimary` with method-disagreement escape hatch.** If the previous primary is excluded in THIS method's slot but not others, the slot returns the current sort order WITHOUT updating the shared sticky register. Other slots that still have the upstream in their survivor set keep it as primary. [`internal/policy/stdlib/stdlib.js:L795-802`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L795-L802) 7. **`scoreMultipliers.finality` YAML integer vs JS bit-flag confusion.** The config field uses the Go `DataFinalityState` enum (`"finalized"=0`, `"unfinalized"=1`, `"realtime"=2`, `"unknown"=3`). The JS globals `FINALIZED=4`, `REALTIME=1`, `UNFINALIZED=2`, `UNKNOWN=8` are bitmasks for `.when(mask, fn)` inside `evalFunc` bodies — they are not valid in the YAML config field. Setting `finality: [4]` in YAML fails to match any request. [`common/data.go:L10-L27`](https://github.com/erpc/erpc/blob/main/common/data.go#L10-L27), [`internal/policy/stdlib/install.go:L74-77`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/install.go#L74-L77) 8. **`latencyDeviationAbove` is constructed fresh per tick.** The closure captures `topByMethod` at factory time. Do NOT put `latencyDeviationAbove` in a variable and reuse across ticks — it would use stale peer data. The default policy is safe because the chain is a stateless expression evaluated fresh each tick. [`internal/policy/stdlib/stdlib.js:L1228-1324`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L1228-L1324) 9. **Bug #907 regression.** With per-finality tracking enabled, block-head-lag writes must fan out to both the specific-finality bucket AND the `{*, All}` rollup. Pre-fix, `blockNumberLagAbove` read the starved rollup and silently no-oped. Fixed and covered by `TestNetworkPolicy_RealPoll_LaggingUpstreamExcluded`. [`erpc/networks_selection_policy_realpoll_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_selection_policy_realpoll_test.go) 10. **Alphabetical tiebreak in `sortByScore`.** When two upstreams have identical scores (e.g. both clean on cold start), the lexicographically earlier ID wins. Test assertions are order-sensitive until metrics diverge. [`internal/policy/stdlib/stdlib.js:L656`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L656) 11. **`upstreamDefaults.routing` is all-or-nothing.** If `upstream.routing` is non-nil (even empty), the default routing block is NOT applied. [`erpc/eval_multipliers_test.go:TestApplyDefaults_InheritsRouting`](https://github.com/erpc/erpc/blob/main/erpc/eval_multipliers_test.go) 12. **`p70 = 0` means unknown quality, not ultra-fast.** Fast-failing upstreams that reject connections in 1ms have empty quantile sketches. A predicate like `latencyAbove(500)` sees `0 < 500` = false and does NOT exclude such an upstream. Pair latency predicates with `samplesAbove(N)` or treat `p70 == 0` as a warning signal. [`internal/policy/eval.go:L89-96`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go#L89-L96) 13. **`probeExcluded` is a no-op array transform.** It does NOT modify the upstream list. Its only effect is depositing `__probeConfig` for the Go-side Prober. Probe traffic never blocks the request path; channel overflow increments `erpc_selection_probe_dropped_total` and drops the probe silently. The probe feed channel size is 256 (`probeFeedBufferSize = 256` in [`internal/policy/prober.go:L102`](https://github.com/erpc/erpc/blob/main/internal/policy/prober.go#L102)). [`internal/policy/stdlib/stdlib.js:L999-1010`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js#L999-L1010) 14. **Step-log is disabled by default in production.** Per-step chain trail logging (`DEBUG "policy step"`) is only active when `Engine.SetStepLogEnabled(true)` is called — by the simulator or when log level is DEBUG. In production there is zero overhead beyond one function-call indirection per stdlib step; no log entries and no per-step allocations are created. [`internal/policy/engine.go:L679-695`](https://github.com/erpc/erpc/blob/main/internal/policy/engine.go#L679-L695) 15. **`ErrUpstreamExcludedByPolicy` error code exists but has no production call site.** Defined at [`common/errors.go:L1823-L1836`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1823-L1836); error code string: `"ErrUpstreamExcludedByPolicy"`. The health tracker silently ignores it (does NOT penalize the upstream's error rate). The policy engine achieves exclusion structurally — upstreams absent from the ordered list are never attempted by `NextUpstream` — rather than by returning this error. The error type is forward-compatible scaffolding. 16. **Idle slot eviction sweep runs every 1 minute.** The engine's `sweepIdleSlots` fires every `engineSweepInterval = 1 minute`. A narrow slot with `idleEvictionAfter = 1 h` may persist for up to 1 h + 1 min after its last access. The health tracker's own idle eviction threshold is separate and shorter: `DefaultIdleEvictionAfter = 30 minutes` for per-`(upstream, method, finality)` metric entries. [`internal/policy/engine.go:engineSweepInterval:L208`](https://github.com/erpc/erpc/blob/main/internal/policy/engine.go#L208) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_selection_position` | Gauge | `project, network, method, upstream` | Every tick; `0`=primary, `1+`=runner-up, `-1`=excluded. | | `erpc_selection_score` | Gauge | `project, network, method, upstream` | Every tick; value is `u.score` from `sortByScore`. | | `erpc_selection_eligible_upstreams` | Gauge | `project, network, method` | Every successful tick; count of in-rotation upstreams. | | `erpc_selection_eval_duration_seconds` | Histogram | `project, network, method` | Every tick; JS eval wall-clock time. | | `erpc_selection_eval_errors_total` | Counter | `project, network, method, kind` | Tick failure; `kind` ∈ `{timeout, throw, invalid_return}`. | | `erpc_selection_rejection_total` | Counter | `project, network, method, upstream, step` | Per tick × excluded upstream; `step` = first stdlib primitive that dropped the upstream. | | `erpc_selection_exclusion_total` | Counter | `project, network, method, upstream, reason` | Per tick × excluded upstream × leaf predicate slug. | | `erpc_selection_shadow_exclusion_total` | Counter | `project, network, method, upstream, reason` | `shadowExcludeIf` would-have-excluded; upstream stays in rotation. | | `erpc_selection_method_block_total` | Counter | `project, network, method, upstream, reason` | Per tick × `blockMethods` block; `method` is the blocked method. Upstream stays in rotation for other methods. | | `erpc_selection_excluded_seconds` | Gauge | `project, network, method, upstream` | Seconds continuously excluded; reset to `0` on readmit. | | `erpc_selection_readmit_total` | Counter | `project, network, method, upstream` | Excluded → in-rotation transition. | | `erpc_selection_readmit_age_seconds` | Histogram | `project, network, method` | Distribution of exclusion age at readmit. | | `erpc_selection_primary_switch_total` | Counter | `project, network, method, from, to` | Primary upstream ID changes. | | `erpc_selection_sticky_hold_total` | Counter | `project, network, method, upstream` | Ticks where `stickyPrimary` held the primary against a challenger. | | `erpc_selection_probe_requests_total` | Counter | `network, upstream, method` | Shadow-probe request fired to excluded upstream. | | `erpc_selection_probe_errors_total` | Counter | `network, upstream, method, reason` | Probe errored; `reason` ∈ `{timeout, throttled, auth, skipped, error}`. | | `erpc_selection_probe_skipped_total` | Counter | `network, reason` | Probe skipped; `reason` ∈ `{write_method, opt_out, sampled_out, max_concurrent, no_method}`. | | `erpc_selection_probe_dropped_total` | Counter | `network, reason` | Probe publish dropped (feed channel full); request path never blocks. | **`erpc_selection_position` value semantics** (assigned at [`internal/policy/slot.go:L477`](https://github.com/erpc/erpc/blob/main/internal/policy/slot.go#L477)): - `0` — primary upstream (first element of the JS result array); serves the next request when no failover occurs. - `1` — first runner-up; tried if the primary fails or is consumed by a concurrent hedge. - `2`, `3`, … — third, fourth choices in ranked order. - `-1` — excluded from rotation; all excluded upstreams share `-1` regardless of how many or which predicate dropped them. An upstream can have `position=0` in the wildcard slot and `position=1` in a per-method slot simultaneously (positions are per-slot). **`erpc_selection_eval_errors_total` `kind` values** (classified at [`internal/policy/slot.go:L460-L467`](https://github.com/erpc/erpc/blob/main/internal/policy/slot.go#L460-L467)): - `"timeout"` — JS eval exceeded `evalTimeout` (default 100 ms); its result is still applied. - `"throw"` — uncaught JS exception (runtime error, user-thrown error). - `"invalid_return"` — eval completed but returned a non-array, null/undefined, entries without `id`, or unknown upstream IDs. Note: `"fallback_default"` appears in the metric Help string and in simulator types as a comment, but **no production code path currently emits this value**. Treat it as forward-compatible documentation only. **`erpc_selection_shadow_exclusion_total` vs `erpc_selection_exclusion_total` semantics:** - `erpc_selection_exclusion_total` — upstream **was removed** from the ordered list; `erpc_selection_position` becomes `-1`. - `erpc_selection_shadow_exclusion_total` — upstream **was NOT removed** and remains in rotation; `shadowExcludeIf` predicate fired for monitoring only. Same leaf-slug attribution as `excludeIf`. Key dashboarding tip: `erpc_selection_position{upstream="X"} == -1` sustained over time means `X` is stuck excluded — check `erpc_selection_exclusion_total{upstream="X"}` for the leaf reason slug, then `erpc_selection_probe_requests_total{upstream="X"}` to confirm probing is running. ### Source code entry points - [`internal/policy/engine.go`](https://github.com/erpc/erpc/blob/main/internal/policy/engine.go) — `Engine` struct; `RegisterNetwork`, `GetOrdered`, `GetExcluded`, `PublishRequest`; idle slot eviction; probe config reconciliation. - [`internal/policy/slot.go`](https://github.com/erpc/erpc/blob/main/internal/policy/slot.go) — `tickOnce` full eval cycle; `snapshotMetrics`; `materializeOrder`; atomic cache swap at [L308-311](https://github.com/erpc/erpc/blob/main/internal/policy/slot.go#L308-L311). - [`internal/policy/eval.go`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go) — `runEval`; `buildJSUpstreams`; `readUpstreamMetrics`; `resolveScoreMultipliers`; `extractOrderedResult`. - [`internal/policy/default_policy.js`](https://github.com/erpc/erpc/blob/main/internal/policy/default_policy.js) — embedded default policy chain; upgraded from placeholder at register time. - [`internal/policy/stdlib/stdlib.js`](https://github.com/erpc/erpc/blob/main/internal/policy/stdlib/stdlib.js) — all chainable `Array.prototype` methods; predicate factories; `sortByScore`; `stickyPrimary`; `probeExcluded`; `latencyDeviationAbove` algorithm. - [`internal/policy/prober.go`](https://github.com/erpc/erpc/blob/main/internal/policy/prober.go) — `Prober`; shadow-mirror request dispatch; `windowCounter` for `minSamples` floor; per-upstream in-flight cap. - [`erpc/networks.go:L1023-L1074`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1023-L1074) — request path: `GetOrdered` call, raw-registry fallback, `PublishRequest` to probe bus. - [`common/defaults.go:L2512-2609`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2512-L2609) — `SelectionPolicyConfig.SetDefaults`; all field defaults. - [`telemetry/metrics.go:L174-291`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L174-L291) — all `MetricSelection*` Prometheus vars. - [`erpc/networks_selection_policy_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_selection_policy_test.go) — integration tests: slow/erroring/lagging/throttled exclusion, fallback tier, safety-net, sticky primary, no-time-based readmit. ### Related pages - [Hedge](/config/failsafe/hedge.llms.txt) — uses the ordered upstream list; each hedge leg gets the next upstream in selection order. - [Retry](/config/failsafe/retry.llms.txt) — walks the same ordered list sequentially on each retry attempt. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — complementary per-upstream state machine checked after selection dispatches to an upstream; open breakers fail fast and the sweep advances down the ranked list. - [Rate limiters](/config/rate-limiters.llms.txt) — caps traffic per upstream independent of selection scoring. - [Upstream config](/config/projects/upstreams.llms.txt) — where `routing.scoreMultipliers` and `routing.probe` are set. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the outcome this feature primarily enables. --- --- # Shadow upstreams > Source: https://docs.erpc.cloud/config/projects/shadow-upstreams > Dark-launch a new RPC provider by mirroring live traffic to it in the background — zero latency impact, automatic response comparison, and Prometheus counters to prove it's ready. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Shadow upstreams Promote a new RPC provider with confidence: mark it as a shadow upstream and eRPC mirrors every live request to it after the primary response is already on the wire. Shadow calls are fire-and-forget — latency and reliability are untouched. eRPC compares responses by content hash and logs every divergence, so you have hard evidence before flipping the switch. **What you get:** - Zero-latency-impact dark launch for new providers or chain configs - Automatic content-hash comparison with configurable field ignores - Per-outcome Prometheus counters (identical / mismatch / error) per upstream - Panic-isolated goroutines — a shadow crash never reaches the client ## Quick taste Illustrative, not a tuned production config — shadow 10% of traffic to a new provider: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: new-provider-shadow endpoint: https://new-provider.example.com shadow: enabled: true # mirror 10% of live traffic; zero latency impact on the primary path sampleRate: 0.1 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreams: [{ id: "new-provider-shadow", endpoint: "https://new-provider.example.com", shadow: { enabled: true, // mirror 10% of live traffic; zero latency impact on the primary path sampleRate: 0.1, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: dark-launch a new provider** ```text I want to evaluate a new RPC provider for my chain before promoting it to production. Set up a shadow upstream in my eRPC config that mirrors 10% of live traffic to the new provider with zero latency impact, and configure ignoreFields to suppress false mismatches on volatile fields like timestamp. Read the full reference first: https://docs.erpc.cloud/config/projects/shadow-upstreams.llms.txt ``` **Prompt Example #2: add ignoreFields for an L2 chain** ```text My shadow upstream for an L2 chain keeps logging mismatch errors on eth_getLogs and eth_getBlockReceipts for L1 fee fields (l1Fee, l1GasPrice, l1BaseFeeScalar, etc.) that legitimately differ between providers. Update the shadow config in my eRPC config to ignore those fields so only real data divergence is flagged. Reference: https://docs.erpc.cloud/config/projects/shadow-upstreams.llms.txt ``` **Prompt Example #3: validate a new node with blockAvailability + shadow** ```text I have a new archive node that only has data from block 18820001 onward. Add it as a shadow upstream in my eRPC config scoped to that block range so the comparison only fires on requests that the node can actually serve. Reference: https://docs.erpc.cloud/config/projects/shadow-upstreams.llms.txt ``` **Prompt Example #4: interpret mismatch metrics before promoting** ```text I've been running a shadow upstream in my eRPC config for 24 hours and I'm seeing erpc_shadow_response_mismatch_total incrementing. Walk me through which metric labels (finality, emptyish, larger) to check to tell apart expected divergence from real provider discrepancies, and what zero-mismatch criteria to use before promoting. Reference: https://docs.erpc.cloud/config/projects/shadow-upstreams.llms.txt ``` --- ### Shadow upstreams — full agent reference ### How it works **Registration.** An upstream becomes a shadow by setting `shadow.enabled: true`. The registry (`upstream/registry.go:L574-L584`) routes it into `networkShadowUpstreams[networkId]` instead of `networkUpstreams[networkId]`. Shadow upstreams are never offered to the selection policy, never scored by the health tracker, and never returned by `GetNetworkUpstreams`. The normal routing path cannot reach them. **Trigger point.** After `p.doForward` returns in `PreparedProject.Forward` (`erpc/projects.go:L135-L163`), if the network has shadow upstreams and the primary response is non-nil, eRPC first parses the primary response as a JSON-RPC object — if parsing fails it logs and skips shadow entirely. On success it clones both the response and request — full byte copies, not references — copying fields including `upstream`, `fromCache`, `attempts`, `retries`, `hedges`, `evmBlockRef`, and `evmBlockNumber` — then launches `executeShadowRequests` as a goroutine. The primary response is already committed to the caller before the goroutine starts. **Goroutine safety.** The shadow goroutine receives cloned objects, not live references. Original request body is byte-copied with `append([]byte(nil), body...)`; if the body is nil, the JSON-RPC object is marshalled to bytes and a new `NormalizedRequest` is constructed. Request directives and HTTP context are also copied. The JSON-RPC response is deep-copied into a new `NormalizedResponse`. No races between primary and shadow are possible. **Context lifecycle.** The shadow goroutine derives its context from `p.networksRegistry.appCtx` (not the inbound request context). Client disconnects do not cancel shadow requests. **Per-upstream loop.** For each shadow upstream, eRPC launches a dedicated goroutine with a fresh context derived from `appCtx`: (1) `ShouldHandleMethod` check — skip silently if the upstream's allow/ignore lists reject the method; (2) **block-availability check** — if the request names a CONCRETE block height the upstream states it does not hold (`maxAvailableRecentBlocks`, or an explicit `blockAvailability` bound), skip with debug log; (3) sample rate check — if `rand.Float64() >= sampleRate`, skip with debug log; (4) forward with `byPassMethodExclusion=true` (`upstream/upstream.go:L410-L450`) so the selection-engine's `shouldSkip` guard doesn't block it; (5) compare responses; (6) call `shadowResp.Release()` to free the cloned response. **Comparison algorithm.** eRPC computes a content hash of both the primary and shadow responses. If `ignoreFields` is configured for the method, both hashes are computed with those JSON keys masked before comparison. Result is one of three outcomes: **Identical** (hashes match, or both emptyish) — logged at Trace; **Mismatch** (hashes differ) — logged at Error with full request, both responses, both hashes, and the ignored fields list; **Error** (shadow request failed or hash computation failed) — counter incremented with stable error fingerprint. **Panic isolation.** A `defer recover()` in `executeShadowRequests` catches any panic, logs it, and increments `erpc_unexpected_panic_total{type="shadow-upstreams"}`. Shadow panics never propagate to the caller. ### Config schema All fields live under `projects[*].upstreams[*].shadow`. Struct at [`common/config.go:L982-986`](https://github.com/erpc/erpc/blob/main/common/config.go#L982-L986). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `shadow.enabled` | `bool` | `false` | When `true`, this upstream is registered into `networkShadowUpstreams` and excluded from all normal routing. Must be `true` for any shadow behavior to activate. Source: [`common/config.go:L983`](https://github.com/erpc/erpc/blob/main/common/config.go#L983), [`upstream/registry.go:L574`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L574) | **Block availability.** Shadow honours the upstream's declared block range, the same question the real routing path asks (`EvmAssertBlockAvailability`). Without it a recent-window upstream — a replica configured with `maxAvailableRecentBlocks`, or an explicit `blockAvailability` lower bound — was mirrored archive-depth traffic it can only refuse: every such request burns the shadow upstream's capacity on work it cannot do, and then registers as a shadow *mismatch*, polluting the very comparison the shadow exists to produce. The check **fails open**, deliberately and in the same places the real path does: a block tag (`latest`, `pending`), an unparseable reference, or an errored assertion all mirror exactly as before. Only a concrete height the upstream states it does not have is skipped. | `shadow.sampleRate` | `*float64` | `nil` → `1.0` (always fire) | Fraction of eligible shadow requests to execute. `0.5` fires 50% at random. Check is `rand.Float64() >= sampleRate` — setting `0.0` suppresses all traffic; setting `nil` or `1.0` fires every request. Source: [`common/config.go:L984`](https://github.com/erpc/erpc/blob/main/common/config.go#L984), [`erpc/shadow.go:L65-75`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L65-L75) | | `shadow.ignoreFields` | `map[string][]string` | `nil` (no fields ignored) | Keys are JSON-RPC method names; values are JSON field names to mask before hash comparison. Both the primary and shadow response are hashed with the same mask. Prevents false mismatches for fields that legitimately differ (e.g., clock-skewed `timestamp`). Source: [`common/config.go:L985`](https://github.com/erpc/erpc/blob/main/common/config.go#L985), [`erpc/shadow.go:L167-191`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L167-L191) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Archive node dark-launch with block-range scoping.** A common production pattern: a new archive node only has data above a certain block, so `blockAvailability.lower` gates which requests can reach it — shadowing only fires on requests the node can actually answer, avoiding a flood of spurious error-total increments: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: new-archive-shadow endpoint: https://rpc.example.com vendorName: my-vendor evm: chainId: 1 blockAvailability: lower: # only shadow requests for blocks at or above this height; # below it the node doesn't have data, so comparison is meaningless exactBlock: 18820001 failsafe: - timeout: duration: 5s # adaptive timeout: p95 of node's own latency distribution, clamped # to [2s, 5s] so slow nodes don't hold the shadow goroutine open forever quantile: 0.95 minDuration: 2s maxDuration: 5s shadow: enabled: true # nil sampleRate = always fire; start here and tune down if shadow load is high ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "new-archive-shadow", endpoint: "https://rpc.example.com", vendorName: "my-vendor", evm: { chainId: 1, blockAvailability: { lower: { // only shadow requests for blocks at or above this height exactBlock: 18820001, }, }, }, failsafe: [{ timeout: { duration: "5s", // adaptive timeout: p95 clamped to [2s, 5s] quantile: 0.95, minDuration: "2s", maxDuration: "5s", }, }], shadow: { enabled: true, // no sampleRate = always fire; reduce to 0.1 on high-QPS fleets }, }] ``` **2. Low-rate background validation — standard provider comparison.** 10% sample rate is the typical starting point on busy fleets: shadow goroutines share outbound connection pools with normal upstreams so 100% shadow can double load on the candidate provider. Ignore `timestamp` on block methods to suppress clock-skew false positives: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: candidate-shadow endpoint: https://rpc.example.com shadow: enabled: true # 10% gives statistically meaningful coverage without doubling upstream load sampleRate: 0.1 ignoreFields: # providers differ on timestamp by ±1s due to clock skew — not a real mismatch eth_getBlockByNumber: ["timestamp"] eth_getBlockByHash: ["timestamp"] ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "candidate-shadow", endpoint: "https://rpc.example.com", shadow: { enabled: true, // 10% gives coverage without doubling upstream load sampleRate: 0.1, ignoreFields: { // providers differ on timestamp by ±1s — not a real mismatch eth_getBlockByNumber: ["timestamp"], eth_getBlockByHash: ["timestamp"], }, }, }] ``` **3. L2 chain with many volatile L1 fee fields.** OP-stack and Arbitrum chains embed L1 fee data in receipts that can differ between providers depending on which L1 oracle snapshot they use. The `ignoreFields` wildcard `*.fieldName` masks the field at every depth of an array response — critical for `eth_getLogs` and `eth_getBlockReceipts` where each entry in the array carries L1 fee metadata: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: l2-node-shadow endpoint: https://rpc.example.com shadow: enabled: true sampleRate: 0.1 ignoreFields: # array-level wildcard: masks the field at every element of the logs array eth_getLogs: - "*.blockTimestamp" # receipts carry multiple L1 fee sub-fields that differ by L1 oracle snapshot eth_getBlockReceipts: - "*.blockTimestamp" - "*.l1BaseFeeScalar" - "*.l1BlobBaseFee" - "*.l1BlobBaseFeeScalar" - "*.l1BlockNumber" - "*.l1Fee" - "*.l1GasPrice" - "*.l1GasUsed" - "*.logs.*.blockTimestamp" ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "l2-node-shadow", endpoint: "https://rpc.example.com", shadow: { enabled: true, sampleRate: 0.1, ignoreFields: { // array wildcard masks the field at every element eth_getLogs: ["*.blockTimestamp"], // receipts carry L1 fee sub-fields that differ by L1 oracle snapshot eth_getBlockReceipts: [ "*.blockTimestamp", "*.l1BaseFeeScalar", "*.l1BlobBaseFee", "*.l1BlobBaseFeeScalar", "*.l1BlockNumber", "*.l1Fee", "*.l1GasPrice", "*.l1GasUsed", "*.logs.*.blockTimestamp", ], }, }, }] ``` **4. Method-scoped shadow for log-indexing validation.** When the only concern is whether a new node's event indexing matches production, scope the shadow to `eth_getLogs` only. The `allowMethods` list on the upstream ensures the shadow goroutine never attempts other methods (the `ShouldHandleMethod` pre-check silently skips them), keeping shadow traffic narrow and noise-free: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: logs-specialist-shadow endpoint: https://rpc.example.com # only shadow eth_getLogs — ShouldHandleMethod skips everything else silently allowMethods: - eth_getLogs shadow: enabled: true sampleRate: 0.2 ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "logs-specialist-shadow", endpoint: "https://rpc.example.com", // only shadow eth_getLogs — ShouldHandleMethod skips everything else silently allowMethods: ["eth_getLogs"], shadow: { enabled: true, sampleRate: 0.2 }, }] ``` **5. Pause shadow without removing config.** Setting `sampleRate: 0` suppresses all shadow traffic while preserving the full config. Flip to `0.1` to resume — no config restructuring, no deployment diff noise: ```yaml shadow: enabled: true sampleRate: 0 # all traffic suppressed; rand.Float64() >= 0.0 is always true # change to 0.1 to resume 10% shadowing ``` ### Request/response behavior - Shadow requests run asynchronously after the primary response is committed to the client. They add zero latency to the client-visible path. - Shadow goroutines use `appCtx` — client disconnect does not cancel them. They always run to completion. - `byPassMethodExclusion=true` is passed to `ups.Forward` so the shadow goroutine bypasses the `shouldSkip` selection-engine check. Method exclusion from the upstream config is still enforced by the pre-call `ShouldHandleMethod` check in the shadow layer itself. [[`erpc/shadow.go:L54-61`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L54-L61)] - A shadow response that errors or returns nil increments `erpc_shadow_response_error_total` — no mismatch is recorded. The error label is a stable fingerprint, not the raw error string. - Mismatch log level is **Error** — these will appear in error-rate dashboards and alert on any divergence. [[`erpc/shadow.go:L253-261`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L253-L261)] - OTel trace span `"Project.executeShadowRequest"` is emitted per shadow goroutine, enabling independent shadow latency measurement in your tracing backend. [[`erpc/shadow.go:L82`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L82)] ### Best practices - Start with `sampleRate: 0.05–0.1` on high-QPS deployments. Shadow goroutines share outbound connection pools with normal upstreams on the same host; 100% shadow on a busy fleet can double upstream load. - Use `ignoreFields` aggressively for volatile fields (`timestamp`, `gasPrice`, `nonce` on pending). False mismatches from clock skew will drown out real divergence signals. - Watch `erpc_shadow_response_mismatch_total` segmented by `finality` label: mismatches on `finality="unfinalized"` are often expected (different block propagation timing); mismatches on `finality="finalized"` are signal for a real provider discrepancy. - Use `larger="true"` on the mismatch metric to detect shadow upstreams that return extra undocumented fields — a common source of application-level bugs if you switch providers. - Combine `allowMethods` on the upstream config with `ignoreFields` to narrow shadow scope per use-case (e.g., validate `eth_getLogs` only, ignore timestamp on block methods). - Set `sampleRate: 0` (not `enabled: false`) when you want to pause shadows temporarily — this preserves the config and makes re-enabling a one-field change. - Shadow upstreams are not in the health-tracker scoring pool. Their error rate does not affect routing decisions; monitor them separately via `erpc_shadow_response_error_total`. ### Edge cases & gotchas 1. **Shadow fires on cached responses.** The trigger checks `resp != nil`; it does not distinguish cache hits from upstream hits. Cache-served finalized responses usually match; unfinalized ones may not — monitor `mismatch_total{finality="unfinalized"}` separately. 2. **`sampleRate: 0` suppresses all shadow traffic.** The check is `rand.Float64() >= sampleRate`; since `rand.Float64()` is always `>= 0.0`, zero suppresses every request. 3. **`sampleRate: nil` and `sampleRate: 1.0` are equivalent.** Both fire every request. 4. **Both hashes are recomputed when `ignoreFields` is set.** Masking is applied to both sides before comparison — a field masked on one side is masked on both. 5. **Hash error increments `erpc_shadow_response_error_total{error="hash_error"}`.** No mismatch is recorded when hash computation fails. 6. **`ErrUpstreamShadowing` is an internal guard, not a client-visible error.** It fires inside `shouldSkip` only when a shadow upstream is reached through the normal forward path (misconfiguration). It carries a `details` field set to the shadow upstream's `upstreamId`. It has no `ErrorStatusCode()` method — there is no HTTP status override. The caller wraps it in `ErrUpstreamRequestSkipped`, which eRPC retries on a different upstream rather than surfacing to the client. The health tracker exempts `ErrCodeUpstreamShadowing` from `ErrorsTotal` so it does not degrade upstream scoring. [[`common/errors.go:L1416-1430`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1416-L1430)] [[`health/tracker.go:L970-983`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L970-L983)] 7. **The `larger` mismatch label identifies shadow returning more data than primary.** `shadowSize > originalSize` sets `larger="true"`. Useful for detecting shadow upstreams that return extra fields in receipts or traces. 8. **Shadow upstreams with no healthy primary are still dispatched.** If `p.doForward` returns a response object (even an error response), the shadow trigger fires. Only `resp == nil` suppresses it. 9. **Panic isolation is complete.** A panic inside any shadow goroutine is caught by `recover()`, logged, and counted; the primary goroutine stack is unaffected. 10. **Method allow/ignore lists on the shadow upstream are fully enforced.** `ShouldHandleMethod` is called before each shadow request; rejected methods are silently skipped. [[`erpc/shadow.go:L54-61`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go#L54-L61)] ### Observability | Metric | Type | Labels | Fires when | |---|---|---|---| | `erpc_shadow_response_identical_total` | counter | `project`, `vendor`, `network`, `upstream`, `category` | Shadow hash matches primary, or both responses are emptyish | | `erpc_shadow_response_mismatch_total` | counter | `project`, `vendor`, `network`, `upstream`, `category`, `finality`, `emptyish`, `larger` | Shadow hash differs from primary | | `erpc_shadow_response_error_total` | counter | `project`, `vendor`, `network`, `upstream`, `category`, `error` | Shadow request errored, returned nil, or hash computation failed | | `erpc_unexpected_panic_total` | counter | `type=shadow-upstreams`, `context`, `fingerprint` | Panic recovered inside `executeShadowRequests` | **Label notes:** - `vendor` — `ups.VendorName()`, e.g. `"alchemy"`, `"quicknode"`. - `category` — JSON-RPC method name, e.g. `"eth_getBlockByNumber"`. - `finality` — `shadowResp.Finality().String()` on mismatch: `"finalized"`, `"unfinalized"`, or `"n/a"`. - `emptyish` — `"true"` when shadow returned `null`/`""`/`[]`/`{}`. - `larger` — `"true"` when shadow byte size exceeded primary byte size. - `error` — `common.ErrorFingerprint(err)`: a stable short error-type string; prevents label cardinality explosion. **Log messages emitted:** - Error: `"shadow response hash mismatch"` — with full `request`, `originalResponse`, `shadowResponse`, `expectedHash`, `shadowHash`, `ignoredFields`. - Debug: `"shadow request returned error"`, `"shadow request returned nil response"`, `"shadow request skipped due to sampling"`, `"method not allowed for shadow upstream"`. - Trace: `"shadow response identical to primary response"`. ### Source code entry points - [`erpc/shadow.go`](https://github.com/erpc/erpc/blob/main/erpc/shadow.go) — `executeShadowRequests`: request cloning, per-upstream loop, sample rate check, method check, forward, hash comparison, metric emit. - [`erpc/projects.go:L135-L163`](https://github.com/erpc/erpc/blob/main/erpc/projects.go#L135-L163) — `PreparedProject.Forward`: trigger point after `doForward`, response cloning, goroutine launch. - [`upstream/registry.go:L574-L603`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L574-L603) — shadow vs. normal upstream registration split; `GetNetworkShadowUpstreams` accessor at L295–L298. - [`erpc/networks.go:L302-L303`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L302-L303) — `Network.ShadowUpstreams()` accessor delegating to the registry. - [`upstream/upstream.go:L410-L450`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L410-L450) — `Forward` method; `byPassMethodExclusion` parameter that allows shadow goroutines to skip the `shouldSkip` block. - [`common/config.go:L982-L986`](https://github.com/erpc/erpc/blob/main/common/config.go#L982-L986) — `ShadowUpstreamConfig` struct definition. - [`common/errors.go:L1416-L1430`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1416-L1430) — `ErrUpstreamShadowing` / `ErrCodeUpstreamShadowing` definition. - [`upstream/upstream.go:L1505-L1508`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1505-L1508) — `shouldSkip` first check: returns `NewErrUpstreamShadowing` for shadow-enabled upstreams on the normal path. - [`health/tracker.go:L970-L983`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L970-L983) — exemption: `ErrCodeUpstreamShadowing` does not increment `ErrorsTotal`. - [`telemetry/metrics.go:L640-L656`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L640-L656) — `MetricShadowResponseIdenticalTotal`, `MetricShadowResponseMismatchTotal`, `MetricShadowResponseErrorTotal` definitions. - [`health/tracker_test.go:L765`](https://github.com/erpc/erpc/blob/main/health/tracker_test.go#L765) — test asserting `ErrUpstreamShadowing` keeps `ErrorsTotal=0` and `ErrorRate=0`. ### Related pages - [Upstreams](/config/projects/upstreams.llms.txt) — upstream configuration, `allowMethods`/`ignoreMethods`, and health tracking. - [Selection policies](/config/projects/selection-policies.llms.txt) — how upstreams are scored and chosen; shadow upstreams are excluded from this entirely. - [Rate limiters](/config/rate-limiters.llms.txt) — cap outbound load to the shadow upstream if it's a metered provider. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — complementary resilience pattern: shadow before promoting, then failover after. --- --- # Static responses > Source: https://docs.erpc.cloud/config/projects/static-responses > Return hardcoded JSON-RPC replies instantly for specific method+params pairs — no upstream contact, zero quota consumed, microsecond latency. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Static responses Some chains deviate from standard EVM assumptions — a genesis block at a non-zero number, a hardcoded `eth_chainId`, a known-null receipt for a synthetic transaction. Sending those requests upstream returns errors or inconsistent data. Static responses short-circuit the entire pipeline and return your configured answer in microseconds, consuming zero upstream quota. **What you get** - Matched requests never touch an upstream or the cache - Any JSON-RPC shape: success result, typed error, or `null` - Full param matching with YAML/JSON type tolerance built in - One Prometheus counter to confirm every match ## Quick taste Illustrative, not a tuned production config — serve block 0 from config: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } staticResponses: # short-circuit: matched requests never reach an upstream - method: eth_blockNumber params: [] response: result: "0x0" ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, staticResponses: [{ // short-circuit: matched requests never reach an upstream method: "eth_blockNumber", params: [], response: { result: "0x0" }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: stub a chain that has no real genesis block** ```text Some EVM chains don't have a real block at number 0x0 — querying it returns an error or times out. Add a staticResponse to my eRPC network config that returns a synthetic, well-formed genesis block object for eth_getBlockByNumber("0x0", false) so clients never hit the upstream for this. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/projects/static-responses.llms.txt ``` **Prompt Example #2: hardcode eth_chainId across all providers** ```text Some of my upstream providers return inconsistent or wrong eth_chainId values for a custom network. Pin eth_chainId to the correct hex value in my eRPC config in my eRPC config using a staticResponse so no upstream is ever consulted for this method. Reference: https://docs.erpc.cloud/config/projects/static-responses.llms.txt ``` **Prompt Example #3: return a typed error for unsupported methods** ```text Certain JSON-RPC methods (e.g. eth_newFilter, debug_traceTransaction) are not supported by my network and return garbage from upstreams. Add staticResponse entries in my eRPC config that return a proper JSON-RPC -32601 methodNotFound error for each of those methods instead of forwarding to upstreams. Reference: https://docs.erpc.cloud/config/projects/static-responses.llms.txt ``` **Prompt Example #4: debug why a static rule isn't matching** ```text I configured a staticResponse in my eRPC config but requests are still reaching my upstream — the erpc_network_static_response_served_total counter stays at zero. Help me diagnose the mismatch: explain hex-string normalization gotchas, YAML int vs JSON float64 equivalence, and how to confirm the exact param form my client sends. Reference: https://docs.erpc.cloud/config/projects/static-responses.llms.txt ``` --- ### Static responses — full agent reference ### How it works `Network.Forward` checks for a static-response match immediately after extracting the JSON-RPC method — before multiplexing, cache reads, and upstream selection ([`erpc/networks.go:L973-981`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L973-L981)). A hit short-circuits the entire pipeline and returns the configured reply in microseconds. A miss falls through to the normal path unmodified. A static response also takes precedence over eRPC's built-in local answers (`eth_chainId`, `net_version`, `web3_clientVersion`, ...): the local-answer hook runs earlier, at project pre-forward, and steps aside when a static response matches the method and params ([`architecture/evm/local_answer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/local_answer.go)). Matching is performed by `FindStaticResponseMatch` ([`common/static_response.go:L14-24`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L14-L24)), which iterates the `staticResponses` slice in declaration order and returns the first entry whose `method` equals the request method (exact, case-sensitive string match) AND whose `params` deep-equal the inbound params. First match wins; subsequent entries are never evaluated. On a hit, `tryServeStaticResponse` ([`erpc/networks_static_responses.go:L15-63`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L15-L63)) builds a `JsonRpcResponse` with the inbound request's `id` (not any stored value), the configured `result` or `error` object, and `jsonrpc: "2.0"`. The response carries no upstream metadata — `Upstream()` is nil and `FromCache()` is false. **Numeric type tolerance.** YAML config deserializes integers as Go `int`; inbound JSON deserializes them as `float64`. `valueEqual` normalizes both to `float64`, so a config param of `0` matches an inbound `0` (or `0.0`) without any special handling. All numeric types (float32/64, int/8/16/32/64, uint/8/16/32/64) are converted to float64 before comparison. Maps are compared key-count-first then recursively, order-independently. Other types fall back to `reflect.DeepEqual`. **Hex strings are not normalized.** `"0x0"` and `"0x00"` are different values. If your client sends `"0x00"` but your config uses `"0x0"`, no match occurs and the request falls through to an upstream. Use the exact form your client sends. **No params wildcard.** Every element in `params` must match exactly. To match a method regardless of its params, configure an entry with an empty `params` array (which also matches inbound `null` params and omitted params, since all three have `len == 0`). **No defaults applied.** Neither `StaticResponseConfig` nor its sub-structs have any `SetDefaults` wiring — all fields are fully explicit. The list itself defaults to nil (feature off). ### Config schema All fields live under `networks[*].staticResponses[*]`. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[*].staticResponses` | `[]*StaticResponseConfig` | `nil` (feature off) | Checked in declaration order; first match wins. Source: [`common/config.go:L2005`](https://github.com/erpc/erpc/blob/main/common/config.go#L2005) | | `networks[*].staticResponses[*].method` | `string` | required | Exact JSON-RPC method name; case-sensitive string equality. Empty string rejected at startup. Source: [`common/config.go:L2015`](https://github.com/erpc/erpc/blob/main/common/config.go#L2015), [`common/validation.go:L1282-1284`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1282-L1284) | | `networks[*].staticResponses[*].params` | `[]interface{}` | `nil` | Params to match; nil and empty-slice are equivalent in matching (both `len == 0`). Omitting the key yields nil; `params: []` yields non-nil empty slice — irrelevant to matching. Supports numbers, strings, booleans, arrays, maps. Source: [`common/config.go:L2016`](https://github.com/erpc/erpc/blob/main/common/config.go#L2016) | | `networks[*].staticResponses[*].response` | `*StaticResponseBodyConfig` | required | Exactly one of `result` or `error` must be set; nil rejected at startup. Source: [`common/config.go:L2017`](https://github.com/erpc/erpc/blob/main/common/config.go#L2017), [`common/validation.go:L1285-1298`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1285-L1298) | | `networks[*].staticResponses[*].response.result` | `interface{}` | `nil` | Any JSON-serializable value; set to serve a successful response. Mutually exclusive with `error`. `result: null` YAML is treated as set (non-nil interface wrapping nil). Source: [`common/config.go:L2023`](https://github.com/erpc/erpc/blob/main/common/config.go#L2023) | | `networks[*].staticResponses[*].response.error` | `*StaticResponseErrorConfig` | `nil` | Set to return a JSON-RPC error response. Mutually exclusive with `result`. Requires `message` to be non-empty. Source: [`common/config.go:L2024`](https://github.com/erpc/erpc/blob/main/common/config.go#L2024) | | `networks[*].staticResponses[*].response.error.code` | `int` | `0` (no range enforced) | JSON-RPC error code. Typical values: `-32700` parse error, `-32600` invalid request, `-32601` method not found, `-32602` invalid params, `-32603` internal error. **Footgun:** code `0` passes validation but is omitted from wire JSON because `ErrJsonRpcExceptionExternal.Code` uses `json:"code,omitempty"`. Always set a non-zero value. Source: [`common/config.go:L2029`](https://github.com/erpc/erpc/blob/main/common/config.go#L2029), [`common/errors.go:L2226`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2226) | | `networks[*].staticResponses[*].response.error.message` | `string` | required when `error` is set | Human-readable error description. Empty string rejected at startup with `"response.error.message is required"`. Source: [`common/config.go:L2030`](https://github.com/erpc/erpc/blob/main/common/config.go#L2030), [`common/validation.go:L1296-1298`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1296-L1298) | | `networks[*].staticResponses[*].response.error.data` | `interface{}` | `nil` | Optional extra data in the JSON-RPC error object. Any JSON-serializable value. Omitted from wire JSON when nil (`omitempty`). Source: [`common/config.go:L2031`](https://github.com/erpc/erpc/blob/main/common/config.go#L2031) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Synthetic genesis block (canonical production pattern).** HyperEVM, LightLink, Sei testnet, and several other EVM chains have no real state at block 0x0 — their node RPCs return an error or an empty response for `eth_getBlockByNumber("0x0", false)`. Indexers and client libraries assume a valid block always exists at that slot. The fix is a fully-formed synthetic block object served straight from config; zero upstream calls are made: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml staticResponses: - method: eth_getBlockByNumber # match the exact hex form clients send — "0x00" would NOT match "0x0" params: ["0x0", false] response: result: baseFeePerGas: "0x0" difficulty: "0x1" extraData: "0x" # gasLimit should be plausible for the chain; 10M is a safe default gasLimit: "0x989680" gasUsed: "0x0" # zero hash signals "synthetic" to any tooling that inspects it hash: "0x0000000000000000000000000000000000000000000000000000000000000000" logsBloom: "0x000...000" miner: "0x0000000000000000000000000000000000000000" mixHash: "0x0000000000000000000000000000000000000000000000000000000000000000" nonce: "0x0000000000000000" number: "0x0" parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000" receiptsRoot: "0x0000000000000000000000000000000000000000000000000000000000000000" sha3Uncles: "0x0000000000000000000000000000000000000000000000000000000000000000" size: "0x1d01" stateRoot: "0x0000000000000000000000000000000000000000000000000000000000000000" timestamp: "0x0" totalDifficulty: "0x1" transactions: [] transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" uncles: [] ``` **TypeScript — `erpc.ts`:** ```typescript staticResponses: [{ method: "eth_getBlockByNumber", // match the exact hex form clients send — "0x00" would NOT match "0x0" params: ["0x0", false], response: { result: { baseFeePerGas: "0x0", difficulty: "0x1", extraData: "0x", // gasLimit should be plausible for the chain; 10M is a safe default gasLimit: "0x989680", gasUsed: "0x0", // zero hash signals "synthetic" to any tooling that inspects it hash: "0x0000000000000000000000000000000000000000000000000000000000000000", logsBloom: "0x000...000", miner: "0x0000000000000000000000000000000000000000", mixHash: "0x0000000000000000000000000000000000000000000000000000000000000000", nonce: "0x0000000000000000", number: "0x0", parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000", receiptsRoot: "0x0000000000000000000000000000000000000000000000000000000000000000", sha3Uncles: "0x0000000000000000000000000000000000000000000000000000000000000000", size: "0x1d01", stateRoot: "0x0000000000000000000000000000000000000000000000000000000000000000", timestamp: "0x0", totalDifficulty: "0x1", transactions: [], transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", uncles: [], }, }, }] ``` **2. Hash-addressed genesis (pair with block-number entry).** Some clients look up genesis by its known zero hash (`0x000...000`) rather than by number. HyperEVM production adds a second static entry for `eth_getBlockByHash` using the same synthetic object — declaration order means the hash lookup is served before the catch-all, no upstream contact either way: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml staticResponses: - method: eth_getBlockByNumber params: ["0x0", false] response: result: { number: "0x0", hash: "0x000...000" } # full block object - method: eth_getBlockByHash # clients that cache "genesis hash = all zeros" hit this instead of falling through params: ["0x0000000000000000000000000000000000000000000000000000000000000000", true] response: result: { number: "0x0", hash: "0x000...000" } # same synthetic block, with txs ``` **TypeScript — `erpc.ts`:** ```typescript staticResponses: [ { method: "eth_getBlockByNumber", params: ["0x0", false], response: { result: { number: "0x0", hash: "0x000...000" } }, }, { method: "eth_getBlockByHash", // clients that cache "genesis hash = all zeros" hit this instead of falling through params: ["0x0000000000000000000000000000000000000000000000000000000000000000", true], response: { result: { number: "0x0", hash: "0x000...000" } }, }, ] ``` **3. Hardcoded chain identity.** Some chains return inconsistent `eth_chainId` values across providers (e.g. decimal vs hex, or different values on archive vs realtime nodes). Serve it from config to guarantee determinism — upstreams are never consulted for this method, which also eliminates a round-trip on every new client connection: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml staticResponses: - method: eth_chainId # empty params matches inbound null params, [], and omitted params — all equivalent params: [] response: # use the canonical hex form your chain uses; 0x539 = 1337 (local devnet) result: "0x539" ``` **TypeScript — `erpc.ts`:** ```typescript staticResponses: [{ method: "eth_chainId", // empty params matches inbound null params, [], and omitted params — all equivalent params: [], response: { // use the canonical hex form your chain uses; 0x539 = 1337 (local devnet) result: "0x539", }, }] ``` **4. Typed error for unsupported or dangerous methods.** Return a proper JSON-RPC error instead of forwarding to an upstream that will reject the call anyway. Declaration order matters — put specific error stubs BEFORE any catch-all entries: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml staticResponses: - method: eth_getBlockByNumber params: ["0x0", false] response: error: # -32602 = invalid params (genesis not available is a client input problem) code: -32602 message: "genesis block not available on this network" # optional structured data surfaced in the JSON-RPC error.data field data: { reason: "chain does not expose pre-migration history" } ``` **TypeScript — `erpc.ts`:** ```typescript staticResponses: [{ method: "eth_getBlockByNumber", params: ["0x0", false], response: { error: { // -32602 = invalid params (genesis not available is a client input problem) code: -32602, message: "genesis block not available on this network", // optional structured data surfaced in the JSON-RPC error.data field data: { reason: "chain does not expose pre-migration history" }, }, }, }] ``` **5. Known-null receipt for a synthetic transaction.** Some bridge or L2 networks produce transaction hashes that will never appear on-chain. Instead of falling through to an upstream that returns an error, return `null` explicitly — sets `result: null` in the wire JSON, which is the correct "not found" shape for receipt lookups: **Config path:** `projects[].networks[].staticResponses` **YAML — `erpc.yaml`:** ```yaml staticResponses: - method: eth_getTransactionReceipt params: ["0xdeadbeef000000000000000000000000000000000000000000000000deadbeef"] response: # result: null is treated as "result is set to null" — valid wire JSON result: null ``` **TypeScript — `erpc.ts`:** ```typescript staticResponses: [{ method: "eth_getTransactionReceipt", params: ["0xdeadbeef000000000000000000000000000000000000000000000000deadbeef"], response: { result: null }, }] ``` ### Request/response behavior - Static responses short-circuit `Network.Forward` before cache reads and upstream selection. The only things that run earlier are method extraction and OTel span setup. [[`erpc/networks.go:L973-981`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L973-L981)] - The inbound request's `id` is always echoed in the response — not any stored value. String ids work correctly. [[`erpc/networks_static_responses.go:L45`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L45)] - The response carries no upstream metadata: `Upstream()` is nil and `FromCache()` is false. [[`erpc/networks_static_responses.go:L15`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L15)] - `result` and `error` are mutually exclusive. Setting both or neither causes a startup validation error. - If `req.JsonRpcRequest()` fails (malformed request), the function returns `(nil, false)` and the request falls through to normal handling — it is not aborted. [[`erpc/networks_static_responses.go:L23`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L23)] - If `NewJsonRpcResponse` fails during response construction (rare — only if result/error marshaling panics), the function logs an error (`"failed to build static response"`) and returns `(nil, false)`, falling through to normal handling. [[`erpc/networks_static_responses.go:L48`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L48)] - OTel span attribute `static_response.hit=true` is set on the `Network.Forward` span on every hit. [[`erpc/networks.go:L978`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L978)] ### Best practices - **Match the exact param form your client sends.** Hex strings are not normalized: `"0x0"` and `"0x00"` are different. Run a quick test request and confirm the exact serialization before committing to config. - **Use `params: []` (empty array) to catch any params.** There is no wildcard — the only way to match a method regardless of its params is an empty params array, which also matches `null` and omitted params. - **Always set a non-zero error code.** Error code `0` passes startup validation but is silently dropped from the wire JSON due to `json:"code,omitempty"`. Clients will see no `code` field. Use standard JSON-RPC codes like `-32602` for invalid params. - **Declaration order is priority order.** If two entries could match the same request, put the more specific one first. The second entry is never evaluated once the first matches. - **Do not expect static responses to populate the cache.** Matched requests bypass cache reads and writes entirely. If you also cache the same method, those entries come from real upstream responses, not your static config. - **Verify coverage with the Prometheus counter.** `erpc_network_static_response_served_total` increments on every match. If a counter you expect stays at zero, the params form in your config likely does not match what the client is sending. ### Edge cases & gotchas 1. **Hex string case-sensitivity.** `"0x0"` and `"0x00"` are different param values — no hex normalization occurs. Match the exact form your clients send. [`common/static_response_test.go:L84`](https://github.com/erpc/erpc/blob/main/common/static_response_test.go#L84) explicitly documents this. 2. **YAML int vs JSON float64 tolerance.** YAML `params: [0]` stores `int(0)`; inbound JSON stores `float64(0)`. `valueEqual` normalizes via `toFloat64` — the match succeeds. [`common/static_response_test.go:L59`](https://github.com/erpc/erpc/blob/main/common/static_response_test.go#L59) 3. **nil and empty params are equivalent in matching.** All three forms — omitted params key (nil), `params: []` (non-nil empty), inbound `"params":null` — have `len == 0` and match each other. The nil vs non-nil distinction only affects re-serialization via `omitempty`. 4. **Declaration order matters.** If two entries share the same (method, params), only the first is served. The second is never evaluated. 5. **No params wildcard.** There is no glob or `*` support. To match a method regardless of params, add an entry with `params: []`. 6. **Static responses bypass the cache.** A matched static response never reads from or writes to the cache. The cache is not populated even if caching is configured for the same method. 7. **Static responses bypass multiplexing.** Matched requests never enter the mux leader/follower logic. 8. **Inbound id is always echoed.** The `Params` slice in config does not store an id. The id in the response comes from `req.ID()` at build time. String ids work correctly. 9. **Exactly one of result/error enforced at startup.** Setting both or neither causes a startup validation error. `result: null` YAML is treated as "result set" (non-nil interface). 10. **Error code 0 omitted from wire JSON.** Code `0` passes `Validate()` but `json:"code,omitempty"` causes it to be silently dropped during serialization. Clients see no `code` field. Always use a non-zero code. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_static_response_served_total` | counter | `project`, `network`, `category` | A request matched a static entry and was served without upstream contact; `category` = the JSON-RPC method name | - OTel span attribute `static_response.hit=true` is set on the `Network.Forward` span on a hit. [[`erpc/networks.go:L978`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L978)] - Debug log: `"served static response (no upstream contacted)"` emitted with the matched `method` field. [[`erpc/networks_static_responses.go:L60-63`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L60-L63)] - Debug log on match-check failure: `"skipping static response: cannot inspect request"`. [[`erpc/networks_static_responses.go:L23`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L23)] - Error log: `"failed to build static response"` on `NewJsonRpcResponse` failure (rare). [[`erpc/networks_static_responses.go:L48`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L48)] ### Source code entry points - [`erpc/networks_static_responses.go:L15-L63`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses.go#L15-L63) — `tryServeStaticResponse`: params extraction, match call, response construction, metric emission - [`common/static_response.go:L14-L71`](https://github.com/erpc/erpc/blob/main/common/static_response.go#L14-L71) — `FindStaticResponseMatch`, `paramsEqual`, `valueEqual`, `mapEqual`, `sliceEqual`, `toFloat64`: pure matching logic - [`erpc/networks.go:L973-L981`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L973-L981) — call site in `Network.Forward`; placement relative to multiplexer and cache - [`common/config.go:L2005-L2032`](https://github.com/erpc/erpc/blob/main/common/config.go#L2005-L2032) — `StaticResponseConfig`, `StaticResponseBodyConfig`, `StaticResponseErrorConfig` struct definitions - [`common/validation.go:L1270-L1300`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1270-L1300) — `NetworkConfig` iterates entries; `StaticResponseConfig.Validate()` enforces field requirements - [`common/errors.go:L2225-L2231`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2225-L2231) — `ErrJsonRpcExceptionExternal`; `Code` field uses `json:"code,omitempty"` causing zero code to be dropped from wire JSON - [`telemetry/metrics.go:L419-L423`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L419-L423) — `MetricNetworkStaticResponseServedTotal` counter definition - [`common/static_response_test.go`](https://github.com/erpc/erpc/blob/main/common/static_response_test.go) — unit tests encoding hex case-sensitivity, numeric equivalence, nil/empty params, map ordering, validation rules - [`erpc/networks_static_responses_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_static_responses_test.go) — integration tests: upstream not contacted on match, params fall-through, error-shaped stubs, string id echo ### Related pages - [Networks](/config/projects/networks.llms.txt) — `staticResponses` is configured per network under `projects[].networks[]`. - [Cache](/config/database/evmcache.llms.txt) — static responses fire before and bypass the cache entirely; they do not populate it. - [Failsafe](/config/failsafe/timeout.llms.txt) — static matches skip failsafe processing; no retry or timeout applies. - [Rate limiters](/config/rate-limiters.llms.txt) — matched static responses never consume upstream quota or rate-limit slots. --- --- # Upstreams > Source: https://docs.erpc.cloud/config/projects/upstreams > Add any RPC endpoint — Alchemy, a self-hosted node, a gRPC feed — and eRPC figures out what it can serve, heals it when it breaks, and routes around it when it can't. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Upstreams Point eRPC at any RPC endpoint and it handles the rest: auto-detects chain ID, starts a background health poller, blocks archive queries from reaching pruned full nodes, and heals broken providers back into rotation automatically. When you need a manual kill switch, one admin call cordons an upstream instantly — no config change, no restart. ## Quick taste Illustrative, not a tuned production config — a minimal upstream definition: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - # chain ID auto-detected; state poller starts automatically. # http(s) and ws(s) schemes are supported; use ws:// or wss:// # for WebSocket upstreams (required for eth_subscribe support). endpoint: https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreams: [{ // chain ID auto-detected; state poller starts automatically endpoint: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add and tune a new upstream from scratch** ```text I want to add a new RPC upstream to my eRPC project — a self-hosted archive node plus a QuickNode fallback. Wire them up in my eRPC config with the right block-availability windows, a shared upstreamDefaults for failsafe timeouts and rateLimitAutoTune, and ignoreMethods for filter methods my nodes don't support. Read the full reference first: https://docs.erpc.cloud/config/projects/upstreams.llms.txt ``` **Prompt Example #2: audit my upstream routing and fix block-window gaps** ```text Audit the upstreams in my eRPC config: check that every full/pruned node has an explicit evm.blockAvailability.lower.latestBlockMinus set (not the deprecated nodeType field), that archive nodes have no lower bound, and that no upstream uses allowMethods without a matching ignoreMethods. Flag any gotchas and apply fixes. Reference: https://docs.erpc.cloud/config/projects/upstreams.llms.txt ``` **Prompt Example #3: debug why an upstream keeps getting skipped** ```text Requests to one of my upstreams in my eRPC config are returning ErrUpstreamRequestSkipped with reason ErrUpstreamMethodIgnored. Walk me through the shouldSkip pipeline and help me figure out whether the problem is ignoreMethods, allowMethods injection, or a use-upstream directive mismatch. Reference: https://docs.erpc.cloud/config/projects/upstreams.llms.txt ``` **Prompt Example #4: add a gRPC cache upstream scoped to read methods only** ```text I have an internal gRPC cache service I want to wire into my eRPC project as a high-priority upstream that only handles eth_getLogs, eth_getBlockByNumber, eth_getBlockByHash, eth_getTransactionByHash, and eth_getTransactionReceipt. It should get a high scoreMultipliers.overall so eRPC prefers it, a tight per-upstream timeout failsafe, and explicit blockAvailability bounds matching the cache window. Config is in my eRPC config. Reference: https://docs.erpc.cloud/config/projects/upstreams.llms.txt ``` **Prompt Example #5: configure rateLimitBudget and auto-tune for a paid vendor** ```text I want to add a rate-limit budget for my Alchemy upstream in my eRPC config and enable rateLimitAutoTune so eRPC backs off when error rate climbs above 10% and ramps back up on healthy minutes. Also set a per-network scoreMultipliers.overall of 0.2 so Alchemy is used as a fallback rather than the primary path. Reference: https://docs.erpc.cloud/config/projects/upstreams.llms.txt ``` --- ### Upstreams — full agent reference ### How it works **Config-time pipeline.** When eRPC loads a project, each upstream in `upstreams[]` first runs `ApplyDefaults` against `upstreamDefaults` — only-if-unset for scalar fields; all-or-nothing for `tags`, `failsafe`, and `routing`; per-field merge for EVM sub-fields; wholesale-then-per-field for SVM sub-fields — then `SetDefaults` fills remaining gaps: deriving an `id` if empty, defaulting `type` to `evm` **only when it was omitted** (so an SVM upstream must say `type: svm`), injecting `ignoreMethods: ["*"]` when `allowMethods` is set without an explicit `ignoreMethods`. Endpoints using a vendor shorthand (`alchemy://KEY`, `drpc://KEY`, and 20+ other prefixes) are converted into provider configs at this stage; the rest of the upstream block travels as a `"*"` override. ([`common/defaults.go:L1152-1241`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1152-L1241)) **Runtime bootstrap.** Every upstream registers as a named background `BootstrapTask` (`upstream/`) so service startup never blocks. The initializer retries with exponential backoff (3 s → 130 s, factor 1.5) unless the task returns a `TaskFatal` error. Bootstrap calls `eth_chainId`, stores the detected value, derives `networkId = evm:`, and starts the EVM state poller. A chain ID mismatch against a configured `evm.chainId` is fatal (no retry). A state-poller startup failure is not fatal — the upstream registers and availability checks fail-open until the poller recovers. ([`upstream/registry.go:L95-104`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L95-L104)) **Request path.** Before forwarding, `shouldSkip` runs in order: shadow upstreams skip real traffic → `evm.skipWhenSyncing` with a syncing poller → `ShouldHandleMethod` (ignore → allow with wildcard patterns, result cached per method forever) → `use-upstream` directive matching (upstream ID first, then tags for purely-positive patterns). Block-availability gating is deliberately deferred to the network layer so a "block slightly ahead" is classified retryable rather than short-circuited. ([`upstream/upstream.go:L1505-1548`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1505-L1548)) **Block availability.** An upstream can declare the block window it serves via `evm.blockAvailability`. Bounds can be relative to the chain tip (`latestBlockMinus`), relative to the detected earliest block (`earliestBlockPlus`), or fixed (`exactBlock`). When a request targets a block outside the window, eRPC skips the upstream and tries the next rather than failing the request. The network layer turns an unavailable-block skip into `ErrUpstreamBlockUnavailable`. An upper-bound skip is retried only when the bound moves (`latestBlockMinus`, `earliestBlockPlus` with `updateRate`), the block is a fixed number, and it sits within 128 blocks of the bound (configurable via `networks[].evm.maxRetryableBlockDistance`); otherwise the skip is final and the request fails at once. SVM applies the same rule; an open `getBlocks` end or a `getBlocksWithLimit` follows the tip, so its skip is always final. ([`erpc/networks.go:L1919-1987`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1919-L1987)) **SVM slot availability.** Solana upstreams declare the same kind of window as `svm.blockAvailability`, with slot-native bound names (`exactSlot`, `latestSlotMinus`, `firstAvailableSlotPlus`). Only what the operator declares is enforced. The upstream's oldest stored block, probed with `getBlocksWithLimit(0, 1)`, anchors a `firstAvailableSlotPlus` bound, like EVM's `earliestBlockPlus`; it is probed for every upstream. The network-level `svm.enforceBlockAvailability` switch gates the declared window. ([`architecture/svm/slot_bounds.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/slot_bounds.go)) ([`erpc/networks.go:L3105-3148`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L3105-L3148)) Set it once for a whole project under `upstreamDefaults` instead of repeating it on every upstream — useful when a pool is uniformly pruned (e.g. nodes started with a retention window). An upstream that declares its own `blockAvailability` **or** the deprecated `maxAvailableRecentBlocks` keeps its own value; the project default only fills upstreams that declare neither, and it takes precedence over the 128-block window otherwise derived from `nodeType: full`. ([`common/defaults.go:L2029-2042`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2029-L2042)) ```yaml projects: - id: main upstreamDefaults: evm: blockAvailability: lower: latestBlockMinus: 604800 # serve only the most recent ~604800 blocks ``` When every upstream skips the block, the client receives a JSON-RPC error with code `-32014` ("block not available") rather than a generic internal error, so a pruned range is distinguishable from eRPC itself failing. ([`common/json_rpc.go:L1715-1740`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1715-L1740)) Every upstream must agree. If one of them instead timed out or returned a server error, that upstream never answered, so the request falls back to a generic retryable error rather than claiming the block is definitively absent. ([`common/json_rpc.go:L1588-1606`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1588-L1606)) **Cordoning.** Cordon state lives on the health tracker as an explicit flag — it is NOT a rolling-window metric and survives window rotation and idle eviction. Admin RPCs via the [Admin API](/operation/admin.llms.txt): `erpc_cordonUpstream`, `erpc_uncordonUpstream`, `erpc_listCordoned`. The selection-policy engine exposes `cordonedReason` to the JS policy; the default policy's `removeCordoned()` step drops cordoned upstreams from routing. ([`health/tracker.go:L793-849`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L793-L849)) **HTTP client and proxy pools.** Each HTTP upstream gets a pre-warmed `http.Transport` with up to 256 idle connections per host (unlimited active), TCP keepalive at 15-second intervals, and a 60-second end-to-end call timeout. Proxy pools let you route outbound traffic through SOCKS5 or HTTP proxies, round-robined by an atomic counter. Fixed transport parameters (not user-configurable; same values for direct and proxy transports): | Parameter | Value | |---|---| | `MaxIdleConns` | `1024` | | `MaxIdleConnsPerHost` | `256` | | `MaxConnsPerHost` | `0` (unlimited) — prevents connection queuing under high RPS / high latency | | `IdleConnTimeout` | `90s` | | `ResponseHeaderTimeout` | `30s` | | `TLSHandshakeTimeout` | `10s` | | `ExpectContinueTimeout` | `1s` | | `http.Client.Timeout` (end-to-end) | `60s` | | Dial timeout | `10s` | | TCP keepalive interval | `15s` | ([`clients/http_json_rpc_client.go:L109-128`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L109-L128); proxy transports: [`clients/proxy_pool_registry.go:L82-98`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L82-L98)) ### Config schema All paths relative to `projects[*]`. "Default" = value after `SetDefaults`/`ApplyDefaults`. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `upstreams[*].id` | string | Derived: native-scheme endpoint → `-`; non-native → `-`; if `vendorName` set → `-` ([`common/defaults.go:L1596-1615`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1596-L1615)) | Used in task names, metrics labels, `use-upstream` matching, admin cordon RPCs. | | `upstreams[*].type` | `UpstreamType` | `"evm"` when omitted ([`common/defaults.go:L1715-1718`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1715-L1718)) | `evm` and `svm` are both supported at runtime. The `evm+` shorthand schemes are normalized to `"evm"` at defaults time. **Footgun**: `svm` is never inferred — an upstream serving Solana that omits `type` silently becomes an EVM upstream and fails to bootstrap. Always write `type: svm` explicitly. | | `upstreams[*].endpoint` | string | `""` (required) | Native schemes: `http://`, `https://`, `ws://`, `wss://`, `grpc://`, `grpc+bds://`. Non-native (e.g. `alchemy://KEY`) converts the upstream into a provider. `ws://`/`wss://` create a persistent WebSocket client (auto-reconnect, keepalive) that serves regular requests and `eth_subscribe` — see [WebSocket](/operation/websocket.llms.txt). Redacted in JSON/YAML output. | | `upstreams[*].tags` | `[]string` | nil; all-or-nothing inheritance from `upstreamDefaults.tags` ([`common/defaults.go:L1505-1510`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1505-L1510)) | `:` convention. Matched by `use-upstream` and policy stdlib. **Footgun**: one tag on the upstream drops ALL defaults tags. | | `upstreams[*].vendorName` | string | `""`; at runtime filled by URL pattern match or `guessVendorName()` | When non-empty, forces name-lookup only — `OwnsUpstream` URL matching is skipped. Mismatch silently applies the wrong error normalizer. No warning is logged. | | `upstreams[*].ignoreMethods` | `[]string` | nil; **forced to `["*"]` when `allowMethods` set and `ignoreMethods` nil** ([`common/defaults.go:L1706-1712`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1706-L1712)) | Evaluated first in `ShouldHandleMethod`. Glob wildcards + `\|` OR + `&` AND + `!` NOT. Result cached per method forever. | | `upstreams[*].allowMethods` | `[]string` | nil | Evaluated after `ignoreMethods`; a match forces support to true. Setting this alone implicitly blocks all other methods via injected `ignoreMethods: ["*"]`. | | `upstreams[*].autoIgnoreUnsupportedMethods` | `*bool` | nil (no global default); `true` for repository-provider upstreams ([`thirdparty/repository.go:L89-91`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L89-L91)) | When true, an `ErrCodeEndpointUnsupported` reply ignores that method on this upstream for 10 min. An `allowMethods` entry for the method wins over it. | | `upstreams[*].failsafe[]` | `[]*FailsafeConfig` | nil; deep-copied from `upstreamDefaults.failsafe` when absent (all-or-nothing) | Per-entry `matchMethod` defaults to `"*"`. Match priority: method+finality > method > finality > catch-all. `consensus` rejected at upstream scope. | | `upstreams[*].rateLimitBudget` | string | `""` | References `rateLimiters.budgets[].id`. Checked before each `Forward`; trips `ErrUpstreamRateLimitRuleExceeded`. | | `upstreams[*].rateLimitCountMode` | `"request"` \| `"credit"` | `"request"` | How the upstream's `rateLimitBudget` counts a call. `"request"` charges a flat 1 hit; `"credit"` charges the request's resolved vendor credit-unit cost (same table as `X-ERPC-Credits`), so a heavy `eth_getLogs` drains the budget faster than a cheap `eth_blockNumber` — a `0`-CU method consumes nothing. Uses the pre-flight table estimate (real cost isn't known until after the call). In `"credit"` the budget is one pool shared by all methods rather than a counter per method. The referenced budget must not define its own `creditUnits` or rule-level `countMode`, which is a second cost source for the same counter and fails validation; budgets outside the upstream scope use those instead. | | `upstreams[*].creditUnits` | `map[string]int64` | `nil` | Per-method credit-unit overrides for the cost accounting behind `X-ERPC-Credits` (`server.costHeaders`) and `rateLimitCountMode: credit`, merged over the vendor's built-in `CreditUnitsProvider` table (`"*"` = fallback for unlisted methods). Usually set once per provider via `providers[].settings.creditUnits` instead of per upstream. | | `upstreams[*].creditAllowance` | `{credits: int64, apiKey: string}` | `nil` | Prepaid credits per billing period of the vendor account behind `apiKey` (that account's admin key). For vendors that report account usage, exposes `u.creditPace` and `u.creditRemaining` to the selection policy: account-wide credits used this period ÷ allowance pro-rated to now, and allowance − used. Readers, all off the request path: QuickNode reads `GET /v0/usage/rpc` every 5m and the account's endpoint list from `GET /v0/endpoints` hourly; Alchemy reads the team's `monthToDate` CU from `GET /v1/usage/summary` every 5m and the team's app keys from `GET /v1/apps` hourly (access key with Usage read and App Management read). Fields are set only when the upstream's endpoint is on that account (Alchemy: its `/v2/` is a team app); an endpoint on another account bills elsewhere and is never paced. Pair with the `creditPace*` / `creditRemaining*` predicates. `apiKey` is redacted in config dumps. | | `upstreams[*].rateLimitAutoTune.enabled` | `*bool` | `true` ([`common/defaults.go:L2490-2492`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2490-L2492)) | Auto-created when `rateLimitBudget != ""`. | | `upstreams[*].rateLimitAutoTune.adjustmentPeriod` | Duration | `1m` ([`common/defaults.go:L2493-2495`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2493-L2495)) | Tuning cadence. | | `upstreams[*].rateLimitAutoTune.errorRateThreshold` | float64 | `0.1` ([`common/defaults.go:L2496-2498`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2496-L2498)) | Error-rate trigger for decrease. | | `upstreams[*].rateLimitAutoTune.increaseFactor` | float64 | `1.05` ([`common/defaults.go:L2499-2501`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2499-L2501)) | Multiplier on healthy periods. | | `upstreams[*].rateLimitAutoTune.decreaseFactor` | float64 | `0.95` ([`common/defaults.go:L2502-2504`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2502-L2504)) | Multiplier on unhealthy periods. | | `upstreams[*].rateLimitAutoTune.minBudget` | int | `0` | Floor for tuned budget. | | `upstreams[*].rateLimitAutoTune.maxBudget` | int | `100000` ([`common/defaults.go:L2505-2507`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2505-L2507)) | Ceiling for tuned budget. | | `upstreams[*].jsonRpc.supportsBatch` | `*bool` | nil (false) | Enables outbound JSON-RPC batching in the HTTP client. | | `upstreams[*].jsonRpc.batchMaxSize` | int | `0` | Max requests per batch. `0` with `supportsBatch: true` fires instantly on first queued request — use a value ≥ 2 to actually coalesce. | | `upstreams[*].jsonRpc.batchMaxWait` | Duration | `0` | `time.AfterFunc(0, ...)` fires immediately; set a non-zero value (e.g. `10ms`) to coalesce. | | `upstreams[*].jsonRpc.enableGzip` | `*bool` | nil (false) | Compresses outbound request body. Client always sends `Accept-Encoding: gzip` and decompresses responses regardless. | | `upstreams[*].jsonRpc.headers` | `map[string]string` | nil | Static headers on every outbound request. Applied via `Header.Set` (overwrites defaults for matching keys). | | `upstreams[*].jsonRpc.proxyPool` | string | `""` | References `proxyPools[].id`. Error at startup if pool not found. | | `upstreams[*].grpc.headers` | `map[string]string` | nil | Applied as gRPC metadata on every outbound request. | | `upstreams[*].shadow.enabled` | bool | `false` | Registers into `networkShadowUpstreams`; never serves real traffic; receives async mirrored traffic post-response. | | `upstreams[*].shadow.sampleRate` | `*float64` | nil → effective `1.0` | Probability a real response triggers a mirror to this upstream. | | `upstreams[*].shadow.ignoreFields` | `map[string][]string` | nil | Per-method response fields ignored during shadow comparison. | | `upstreams[*].routing` | object | nil; cloned wholesale from `upstreamDefaults.routing` when absent (all-or-nothing) | Routing hints for the selection-policy engine. | | `upstreams[*].routing.scoreMultipliers[].overall` | `*float64` | unset = 1 | Scales the upstream's final score. `2` = twice as preferred. | | `upstreams[*].routing.scoreMultipliers[].errorRate` / `respLatency` / `throttledRate` / `blockHeadLag` / `finalizationLag` / `misbehaviors` | `*float64` | unset = inherit preset | Per-dimension weight overrides for `sortByScore`. `0` removes contribution. | | `upstreams[*].routing.scoreLatencyQuantile` | float64 | `0` → policy default p70 | Which response-time quantile feeds the score. | | `upstreams[*].routing.probe` | `"on"` \| `"off"` | `""` → `on` | `off` opts this upstream out of probe-excluded shadow-mirror traffic. | | `upstreams[*].evm.chainId` | int64 | `0` → auto-detected via `eth_chainId` at bootstrap | Mismatch against detected value is **fatal** (no retry). Must be `0` for vendor-shorthand endpoints. | | `upstreams[*].evm.statePollerInterval` | Duration | `30s` ([`common/defaults.go:L1718-1724`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1718-L1724)) | Background latest/finalized poll cadence. Non-zero required. | | `upstreams[*].evm.statePollerDebounce` | Duration | `0` → inferred from chain block time | Minimum spacing between forced polls. | | `upstreams[*].evm.skipWhenSyncing` | `*bool` | `false` ([`common/defaults.go:L1766-1772`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1766-L1772)) | Skip requests with `ErrUpstreamSyncing` while the poller reports syncing state. | | `upstreams[*].evm.skipSyncingCheck` | `*bool` | `false` | Disable `eth_syncing` polling for this upstream and hard-set syncing state to `NotSyncing`. Use for nodes that always return a syncing object (e.g. Pharos/Antora) even when fully caught up, which would otherwise cause permanent circuit-breaker false positives. | | `upstreams[*].evm.pinLatestTag` | `*bool` | `false` (inherits `upstreamDefaults.evm.pinLatestTag`) | For `eth_call`, `eth_getBalance`, `eth_getCode`, `eth_getTransactionCount`, `eth_getStorageAt` asking `"latest"` (or omitting the block): this upstream receives the network head as a hex number; other upstreams, the cache and the response keep `"latest"`. Skipped when the head is above its `blockAvailability.upper` bound or unknown. For an upstream whose own head lags the network: a block it lacks fails as missing data and the next upstream answers. Never applies to a request whose tag reaches upstreams as is (`translateLatestTag: false`, `skip-interpolation`): this upstream gets the tag too. | | `upstreams[*].evm.subscriptionSource` | `off` \| `onDemand` \| `always` | unset: `onDemand` for `ws://` / `wss://` endpoints, `off` otherwise | When this WebSocket upstream pushes `newHeads` to the network's [chain tracker](/operation/websocket.llms.txt#how-heads-reach-subscribers). `onDemand`: while a client needs every block (`eth_subscribe` `newHeads` or `logs`, a gRPC block stream), and 60s after the last one leaves. `always`: from network init, for nodes that push for free. `off`: never. Without pushes the block clock fetches the upstream's head, as for an HTTP upstream, and a pushed head spares the upstream's own latest poll. `onDemand` or `always` on any other endpoint is refused at load: the block clock fetches every upstream's head, source or not. A source that refuses `newHeads` as unsupported is fetched by the clock until a subscribe succeeds. Every upstream the selection policy routes to votes on the head whether or not it is a source. | | `upstreams[*].evm.multicall3` | object | nil = off (inherits `upstreamDefaults.evm.multicall3`) | Packs `eth_call`s sent to this upstream for the same block into one [Multicall3](https://github.com/mds1/multicall3) `aggregate3` call at `0xcA11…CA11`, so a vendor billed per request bills once per pack. Below retries, hedging, consensus and cache: each call keeps its own. Packed: `{to, data\|input, gas?}` calls with no `from`, `value` or state override; a call with `gas` packs only with calls of the same `gas`, which the multicall carries. A call is sent alone, exactly as without packing, when no other call joins its pack, the multicall fails or is malformed, its inner call reverts, runs out of gas or returns no data, or its block predates Multicall3 on this upstream. Not invisible: a packed call runs with `msg.sender` = Multicall3 instead of the zero address and with less gas left, so a view that returns data based on `msg.sender` or `gasleft()` can answer differently; enable it where the callers' calls do not depend on either. Metrics: `erpc_upstream_multicall3_calls_total{outcome}`, `erpc_upstream_multicall3_batch_size`; requests saved = `packed` − batches. | | `upstreams[*].evm.multicall3.maxWait` | Duration | `10ms` | A pack is sent this long after its first call. | | `upstreams[*].evm.multicall3.maxCalls` | int | `20` (min `2`) | A pack is sent at once when it holds this many calls. | | `upstreams[*].evm.multicall3.bypassContracts` | `[]string` | `[]` | Target addresses never packed: contracts that answer differently, without reverting, when the caller is Multicall3 (`msg.sender` or caller-code checks). A contract whose call reverts inside a pack but succeeds alone is learned at runtime (logged once, for the process lifetime) and needs no entry. | | `upstreams[*].evm.blockAvailability.lower` / `.upper` | object | nil = unbounded side | Each bound sets exactly one of `exactBlock`, `latestBlockMinus`, `earliestBlockPlus`. Cross-bound validation: `latestBlockMinus` lower value must be ≥ upper value. | | `upstreams[*].evm.blockAvailability.{lower,upper}.latestBlockMinus` | `*int64` | nil | Bound = latest − N. Recomputed on each check from state poller. | | `upstreams[*].evm.blockAvailability.{lower,upper}.earliestBlockPlus` | `*int64` | nil | Bound = detected earliest block + N via probe. Earliest `0` before detection computes `0+N`. | | `upstreams[*].evm.blockAvailability.{lower,upper}.exactBlock` | `*int64` | nil | Fixed block bound. `probe` and `updateRate` must be unset/zero. | | `upstreams[*].evm.blockAvailability.{lower,upper}.probe` | enum | `""` → `blockHeader` | One of `blockHeader`, `eventLogs`, `callState`, `traceData`. Only relevant for `earliestBlockPlus`. | | `upstreams[*].evm.blockAvailability.{lower,upper}.updateRate` | Duration | `0` = freeze at first evaluation | Recompute cadence for `earliestBlockPlus` bounds. Ignored for `latestBlockMinus`. | | `upstreams[*].evm.nodeType` | enum | `""` → `"unknown"` | **Deprecated.** `full` synthesizes `blockAvailability.lower.latestBlockMinus: 128` if no explicit `blockAvailability` is set. Migrate to explicit `blockAvailability`. | | `upstreams[*].evm.maxAvailableRecentBlocks` | int64 | `0` | **Deprecated.** Synthesized as `blockAvailability.lower.latestBlockMinus: N` when `blockAvailability` is nil. Migrate to explicit `blockAvailability`. | | `upstreams[*].evm.getLogsAutoSplittingRangeThreshold` | int64 | `0` | Proactive `eth_getLogs` range splitting at upstream scope. Details in [getLogs splitting](/reference/evm/getlogs-splitting.llms.txt). | | `upstreams[*].evm.traceFilterAutoSplittingRangeThreshold` | int64 | `0` | Same for `trace_filter` / `arbtrace_filter`. | | `upstreams[*].evm.integrity.eth_getBlockReceipts.enabled` | bool | `false` | Per-upstream receipt integrity checking. | | `upstreams[*].evm.integrity.eth_getBlockReceipts.checkLogIndexStrictIncrements` | `*bool` | nil | Sub-check: verify log indices strictly increment within a block. | | `upstreams[*].evm.integrity.eth_getBlockReceipts.checkLogsBloom` | `*bool` | nil | Sub-check: verify logs bloom filter consistency. | | `upstreams[*].evm.getLogsMaxAllowedRange` / `getLogsMaxAllowedAddresses` / `getLogsMaxAllowedTopics` / `getLogsSplitOnError` / `getLogsMaxBlockRange` | int64 / int64 / int64 / `*bool` / int64 | all zero/nil | **Deprecated and ignored at runtime.** Tagged `json:"-"` so invisible in JSON config dumps. A WARN is logged at registration if any `maxAllowed*` value `> 0` or `getLogsSplitOnError != nil`. Migrate to `networks[*].evm.*` equivalents. ([`upstream/registry.go:L107-118`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L107-L118)) | | `upstreams[*].evm.queryShim.*` | object | all zero/nil | MIP-16 `eth_query*` shim: `enabled` and `allowedMethods` (this upstream may serve the shim's sub-requests for those methods), `maxBlocksPerPage` (default `1000`) and `maxPageDuration` (default `10s`), the page budget. The old `concurrency`, `maxBlockRange`, `maxLimit` and `defaultLimit` fields are gone: MIP-16 pages by `target` and budget, with no `limit` or `cursor`. See the [method handlers reference](/reference/evm/method-handlers.llms.txt). | | `upstreams[*].svm.cluster` | string | `""`; inherited from `upstreamDefaults.svm.cluster` | The cluster this upstream serves. Must match the network-level `svm.cluster` for the upstream to be eligible for that network. Unlike the network side, cluster **is** inherited here — on an upstream it only says "which cluster do I serve", and a pool homogeneous across one cluster is the common case. | | `upstreams[*].svm.chain` | string | `""` → treated as `"solana"`; inherited from `upstreamDefaults.svm.chain` | Which SVM chain this upstream serves. Must match the network-level `svm.chain`. | | `upstreams[*].svm.checkGenesisHash` | bool | `false` | Opts an **unknown** `(chain, cluster)` pair into `getGenesisHash` validation at bootstrap. Known Solana clusters (`mainnet-beta`, `devnet`, `testnet`) are always validated regardless of this flag: a mismatch **or a fetch failure** fails the upstream, catching nodes mis-pointed at the wrong cluster and refusing to register one that could not be verified. For unknown clusters the same check (with no table comparison) runs only when this flag is set, so private and local clusters with no published genesis hash still work. | | `upstreams[*].svm.statePollerDebounce` | Duration | `0` / omit → inherit `networks[*].svm.statePollerDebounce`; also filled from `upstreamDefaults.svm.statePollerDebounce` when the upstream omits it | Hard per-upstream override for the SVM poll fan-out gate (same precedence as `upstreams[*].evm.statePollerDebounce`). Non-zero short-circuits the network debounce for this upstream only; zero/omit inherits. Does **not** disable the poller. Prefer setting it on individual archive/tip-excluded vendors (e.g. `5s`), not via `upstreamDefaults.svm` — a raised default ages every shred snapshot while `tipStalenessMargin` stays on the network value. The upstream still votes in the majority served tip (`blockAvailability` tip-exclusion is routing-only); whenever slow pollers are ≥ half the pool the advertised head can follow them. Dead-detection counts polls (`deadPollsBeforeUnhealthy = 2`), so a 5s gate cordons after ~10s. Details: [SVM slot tracking](/reference/svm/slot-tracking.llms.txt). | | `upstreams[*].svm.blockAvailability.lower` / `.upper` | object | nil = unbounded side | Operator restriction on the slot window this upstream may serve. Each bound sets exactly one of `exactSlot`, `latestSlotMinus`, `firstAvailableSlotPlus`. Only declared bounds are enforced; the observed floor is probed for every upstream but skips nothing unless a bound uses `firstAvailableSlotPlus`. Gated by `networks[*].svm.enforceBlockAvailability`. ([`common/config.go:L2660-2699`](https://github.com/erpc/erpc/blob/main/common/config.go#L2660-L2699)) | | `upstreams[*].svm.blockAvailability.{lower,upper}.exactSlot` | `*int64` | nil | Fixed slot bound. Must be ≥ 0. | | `upstreams[*].svm.blockAvailability.{lower,upper}.latestSlotMinus` | `*int64` | nil | Bound = poller's `LatestSlot()` − N. Recomputed on each check. Cold poller (latest ≤ 0) fail-opens that side. | | `upstreams[*].svm.blockAvailability.{lower,upper}.firstAvailableSlotPlus` | `*int64` | nil | Bound = oldest stored block (`getBlocksWithLimit(0, 1)`) + N. Unobserved floor fail-opens that side — unknown is not slot 0. | | `upstreams[*].svm.blockAvailability.{lower,upper}.updateRate` | Duration | `0` = freeze after first observation | Floor re-probe cadence, as EVM's `earliestBlockPlus`. Until the first observation the floor retries every `30s`. `firstAvailableSlotPlus` bounds only; the smaller of `lower`/`upper` wins. | | `upstreamDefaults` | `*UpstreamConfig` | nil | Project-level template. Gets its own `SetDefaults(nil)` first. Each upstream runs `ApplyDefaults` then `SetDefaults`. | | `proxyPools[*].id` | string | required | Pool name referenced by `upstreams[*].jsonRpc.proxyPool`. | | `proxyPools[*].urls` | `[]string` | required, min 1 | Proxy URLs. Accepted schemes: `http://`, `https://`, `socks5://` (case-insensitive prefix check — `socks4://` rejected at startup). | | `networks[*].evm.enforceBlockAvailability` | `*bool` | nil → enabled by default | Network-level override for block availability enforcement. | | `networks[*].evm.maxRetryableBlockDistance` | `*int64` | nil → `128` | Distance above a moving upper bound within which `ErrUpstreamBlockUnavailable` is retryable vs final. | **`upstreamDefaults` inheritance semantics — scalar vs composite fields differ critically:** - **Scalar fields** (`endpoint`, `type`, `vendorName`, `rateLimitBudget`, `autoIgnoreUnsupportedMethods`): inherited individually when the upstream's own value is zero. - **`tags`**: all-or-nothing — if the upstream declares even one tag, no defaults tags are inherited. - **`failsafe`**: all-or-nothing — any `failsafe` entry on the upstream means none from defaults apply. - **`routing`**: all-or-nothing — same rule. - **EVM sub-fields** (`statePollerInterval`, `statePollerDebounce`, `maxAvailableRecentBlocks`, auto-splitting thresholds, `integrity`): per-field merge when both sides are non-nil. - **SVM sub-fields** (`chain`, `cluster`, `checkGenesisHash`, `statePollerDebounce`, `blockAvailability`): an upstream with no `svm` block inherits `upstreamDefaults.svm` **wholesale** (copied, not pointer-shared); one with a partial block fills only its empty fields, including copying `blockAvailability` when the upstream omitted it and filling `statePollerDebounce` when the upstream left it at zero. This is the field set that lets a homogeneous pool declare `chain`/`cluster` (and a shared slot window / debounce) once instead of repeating it per upstream. - **`jsonRpc`**: shallow-copied from defaults only when the upstream has no `jsonRpc` block at all; even `jsonRpc: {}` blocks inheritance. **Block-availability bound kinds and probe types** (for `earliestBlockPlus` bounds): | Probe | Method called | Use when | |---|---|---| | `blockHeader` (default) | `eth_getBlockByNumber` | Uniform data availability; most nodes | | `eventLogs` | `eth_getLogs` (requires ≥1 log) | Log-only archives with pruned state | | `callState` | `eth_getBalance` | State-availability gates on archive nodes | | `traceData` | `trace_block` / `debug_traceBlockByHash` / `trace_replayBlockTransactions` | Gating trace/debug method routing | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Full node + archive node pool with explicit block windows.** Route recent blocks to a cheap full node and archive queries to a dedicated archive node. In production, internal nodes run at a 5-second state-poller cadence for tight head tracking, and `latestBlockMinus: 0` on the upper bound prevents the cache upstream from serving stale-head responses: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: full-node endpoint: https://rpc.example.com evm: chainId: 1 statePollerInterval: 5000ms blockAvailability: # eRPC only sends this upstream blocks it can actually serve lower: latestBlockMinus: 128 upper: # latestBlockMinus: 0 = "no blocks beyond current head" — # prevents sending future/reorg blocks to a lagging node latestBlockMinus: 0 probe: blockHeader - id: archive-node endpoint: https://archive.rpc.example.com evm: chainId: 1 # no lower bound = unbounded archive (serves any historical block) statePollerInterval: 10s ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreams: [ { id: "full-node", endpoint: "https://rpc.example.com", evm: { chainId: 1, statePollerInterval: "5000ms", blockAvailability: { lower: { latestBlockMinus: 128 }, // latestBlockMinus: 0 = cap at current head; prevents stale-head responses upper: { latestBlockMinus: 0, probe: "blockHeader" }, }, }, }, { id: "archive-node", endpoint: "https://archive.rpc.example.com", evm: { chainId: 1, statePollerInterval: "10s" }, }, ], }], }); ``` **2. gRPC cache upstream scoped to read methods only.** Internal deployments wire a gRPC cache service as a high-priority upstream that only handles cacheable read methods. The cache gets a high `scoreMultipliers.overall` (3.5×) so the selection engine prefers it; `earliestBlockPlus` + `updateRate` keeps the lower bound re-evaluated hourly as the cache fills: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: grpc-cache # gRPC cache connector — high score so selection engine prefers it endpoint: grpc://cache.internal.svc.cluster.local:8033 vendorName: internal-cache routing: scoreMultipliers: - network: "" method: "" # 3.5× score: cache hits should almost always be tried first overall: 3.5 evm: chainId: 42161 statePollerInterval: 1000ms blockAvailability: lower: # probe re-runs every 5s so bounds reflect actual cache fill earliestBlockPlus: 0 probe: blockHeader updateRate: 5s upper: latestBlockMinus: 0 probe: blockHeader # only serve the methods the cache actually holds ignoreMethods: - "*" allowMethods: - eth_getLogs - eth_getBlockByHash - eth_getBlockReceipts - eth_getBlockByNumber - eth_getTransactionByHash - eth_getTransactionReceipt failsafe: - matchMethod: "*" timeout: # tight cap: cache reads must be fast or it's not worth it duration: 1s quantile: 0.8 minDuration: 200ms maxDuration: 1s hedge: # race a second cache read quickly — latency is stable enough # for static-style floor here (50ms) quantile: 0.9 maxCount: 1 minDelay: 50ms maxDelay: 100ms ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreams: [{ id: "grpc-cache", endpoint: "grpc://cache.internal.svc.cluster.local:8033", vendorName: "internal-cache", routing: { scoreMultipliers: [{ network: "", method: "", overall: 3.5 }], }, evm: { chainId: 42161, statePollerInterval: "1000ms", blockAvailability: { lower: { earliestBlockPlus: 0, probe: "blockHeader", updateRate: "5s" }, upper: { latestBlockMinus: 0, probe: "blockHeader" }, }, }, ignoreMethods: ["*"], allowMethods: [ "eth_getLogs", "eth_getBlockByHash", "eth_getBlockReceipts", "eth_getBlockByNumber", "eth_getTransactionByHash", "eth_getTransactionReceipt", ], failsafe: [{ matchMethod: "*", timeout: { duration: "1s", quantile: 0.8, minDuration: "200ms", maxDuration: "1s" }, hedge: { quantile: 0.9, maxCount: 1, minDelay: "50ms", maxDelay: "100ms" }, }], }], }], }); ``` **3. Vendor provider as deprioritized fallback with rate-limit auto-tune.** Paid vendors like Alchemy are expensive at volume. Production configs set `scoreMultipliers.overall: 0.2` to deprioritize them behind cheaper nodes, and pair a `rateLimitBudget` with `rateLimitAutoTune` so eRPC backs off automatically when the vendor starts throttling (decreaseFactor 0.7 cuts budget aggressively on errors; increaseFactor 1.1 recovers slowly): **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: alchemy-mainnet endpoint: https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY} vendorName: alchemy evm: chainId: 1 statePollerInterval: 10s rateLimitBudget: alchemy-global rateLimitAutoTune: enabled: true adjustmentPeriod: 30s # start backing off once 10% of requests are errors errorRateThreshold: 0.1 # recover slowly (×1.1 per period), cut fast (×0.7) increaseFactor: 1.1 decreaseFactor: 0.7 minBudget: 1 maxBudget: 100000 routing: scoreMultipliers: - network: "" method: "" # 0.2× score: use Alchemy only when cheaper upstreams are unavailable overall: 0.2 rateLimiters: budgets: - id: alchemy-global rules: - method: "*" maxCount: 500 period: 1s ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreams: [{ id: "alchemy-mainnet", endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", vendorName: "alchemy", evm: { chainId: 1, statePollerInterval: "10s" }, rateLimitBudget: "alchemy-global", rateLimitAutoTune: { enabled: true, adjustmentPeriod: "30s", errorRateThreshold: 0.1, increaseFactor: 1.1, decreaseFactor: 0.7, minBudget: 1, maxBudget: 100000, }, routing: { scoreMultipliers: [{ network: "", method: "", overall: 0.2 }], }, }], }], rateLimiters: { budgets: [{ id: "alchemy-global", rules: [{ method: "*", maxCount: 500, period: "1s" }], }], }, }); ``` **4. Per-upstream method failsafe tiers with `upstreamDefaults`.** Production fleets share a single `upstreamDefaults.failsafe` slice across all upstreams. Heavy methods (`eth_getLogs`, `eth_getBlockReceipts`) get a wide timeout with a high quantile floor to avoid cutting off big-range subgraph backfills; light getters get a tight cap to encourage fast failover. Individual upstreams that need special treatment (like a fast internal gRPC reader) override the whole `failsafe` slice — all-or-nothing: **Config path:** `projects[].upstreamDefaults` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreamDefaults: # shared across all upstreams; one upstream with its own failsafe[] inherits none of this autoIgnoreUnsupportedMethods: false ignoreMethods: - eth_newFilter - eth_newBlockFilter - eth_newPendingTransactionFilter - eth_getFilterChanges - eth_getFilterLogs - eth_uninstallFilter evm: getLogsAutoSplittingRangeThreshold: 5000 rateLimitAutoTune: enabled: true adjustmentPeriod: 30s errorRateThreshold: 0.1 increaseFactor: 1.1 decreaseFactor: 0.7 minBudget: 1 maxBudget: 100000 failsafe: - matchMethod: "eth_getLogs|eth_getBlockReceipts" timeout: # 2s floor: big-range queries legitimately take seconds on archive nodes duration: 15s quantile: 0.9 minDuration: 2s maxDuration: 15s hedge: null retry: null - matchMethod: "eth_get*" timeout: # 200ms floor: light point-lookups should be fast duration: 5s quantile: 0.9 minDuration: 200ms maxDuration: 5s hedge: null retry: null - matchMethod: "*" timeout: duration: 60s quantile: 0.8 minDuration: 500ms maxDuration: 60s hedge: null retry: null upstreams: - id: eth-reader endpoint: grpc://reader.internal.svc.cluster.local:50051 vendorName: internal-reader evm: chainId: 1 ignoreMethods: ["*"] allowMethods: - eth_getBlockByNumber - eth_getLogs - eth_getTransactionByHash - eth_getTransactionReceipt rateLimitBudget: reader-global rateLimitAutoTune: enabled: true minBudget: 10 maxBudget: 10000 # very sensitive: trip at 1% errors, recover slowly (0.98×) errorRateThreshold: 0.01 decreaseFactor: 0.98 increaseFactor: 1.1 adjustmentPeriod: 30s failsafe: # Overrides upstreamDefaults entirely — tight cap so network-level # retry races cheaper upstreams instead of bouncing back to the reader - matchMethod: "*" timeout: duration: 500ms quantile: 0.8 minDuration: 100ms maxDuration: 500ms retry: maxAttempts: 1 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreamDefaults: { autoIgnoreUnsupportedMethods: false, ignoreMethods: [ "eth_newFilter", "eth_newBlockFilter", "eth_newPendingTransactionFilter", "eth_getFilterChanges", "eth_getFilterLogs", "eth_uninstallFilter", ], evm: { getLogsAutoSplittingRangeThreshold: 5000 }, rateLimitAutoTune: { enabled: true, adjustmentPeriod: "30s", errorRateThreshold: 0.1, increaseFactor: 1.1, decreaseFactor: 0.7, minBudget: 1, maxBudget: 100000, }, failsafe: [ { matchMethod: "eth_getLogs|eth_getBlockReceipts", timeout: { duration: "15s", quantile: 0.9, minDuration: "2s", maxDuration: "15s" }, hedge: null, retry: null, }, { matchMethod: "eth_get*", timeout: { duration: "5s", quantile: 0.9, minDuration: "200ms", maxDuration: "5s" }, hedge: null, retry: null, }, { matchMethod: "*", timeout: { duration: "60s", quantile: 0.8, minDuration: "500ms", maxDuration: "60s" }, hedge: null, retry: null, }, ], }, upstreams: [{ id: "eth-reader", endpoint: "grpc://reader.internal.svc.cluster.local:50051", vendorName: "internal-reader", evm: { chainId: 1 }, ignoreMethods: ["*"], allowMethods: [ "eth_getBlockByNumber", "eth_getLogs", "eth_getTransactionByHash", "eth_getTransactionReceipt", ], rateLimitBudget: "reader-global", rateLimitAutoTune: { enabled: true, minBudget: 10, maxBudget: 10000, errorRateThreshold: 0.01, decreaseFactor: 0.98, increaseFactor: 1.1, adjustmentPeriod: "30s", }, // Overrides upstreamDefaults entirely — tight cap so network-level // retry races cheaper upstreams instead of bouncing back to the reader failsafe: [{ matchMethod: "*", timeout: { duration: "500ms", quantile: 0.8, minDuration: "100ms", maxDuration: "500ms" }, retry: { maxAttempts: 1 }, }], }], }], }); ``` **5. Per-chain `getLogsAutoSplittingRangeThreshold` overrides.** High-throughput chains like Arbitrum and Sei have providers that reject `eth_getLogs` queries over large block ranges. Production configs set a tighter threshold on those chains' upstreams (1 000 for Arbitrum, 500 for Sei) while leaving the default 5 000 in `upstreamDefaults.evm` for chains with more forgiving providers: **Config path:** `projects[].upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreamDefaults: evm: # generous default for most chains getLogsAutoSplittingRangeThreshold: 5000 upstreams: - id: arbitrum-mainnet-node endpoint: https://rpc.example.com evm: chainId: 42161 # Arbitrum providers reject ranges >1000 blocks for heavy contracts getLogsAutoSplittingRangeThreshold: 1000 statePollerInterval: 5000ms blockAvailability: upper: latestBlockMinus: 0 probe: blockHeader - id: sei-mainnet-node endpoint: https://sei.rpc.example.com evm: chainId: 1329 # Sei's high block rate makes large ranges expensive for providers getLogsAutoSplittingRangeThreshold: 500 statePollerInterval: 5000ms ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", upstreamDefaults: { evm: { getLogsAutoSplittingRangeThreshold: 5000 }, }, upstreams: [ { id: "arbitrum-mainnet-node", endpoint: "https://rpc.example.com", evm: { chainId: 42161, // Arbitrum providers reject ranges >1000 blocks for heavy contracts getLogsAutoSplittingRangeThreshold: 1000, statePollerInterval: "5000ms", blockAvailability: { upper: { latestBlockMinus: 0, probe: "blockHeader" } }, }, }, { id: "sei-mainnet-node", endpoint: "https://sei.rpc.example.com", evm: { chainId: 1329, // Sei's high block rate makes large ranges expensive for providers getLogsAutoSplittingRangeThreshold: 500, statePollerInterval: "5000ms", }, }, ], }], }); ``` **6. A Solana upstream pool with `upstreamDefaults.svm`.** `type: svm` must be explicit on every upstream — it is never inferred from the endpoint or from the network. `chain` and `cluster` are the two fields that decide network eligibility, and unlike the network side they *are* inheritable, so a pool homogeneous across one cluster declares them once. Each SVM upstream gets its own slot/health poller automatically: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreamDefaults: # type is NOT inferred — declaring it here covers the whole pool type: svm svm: # cluster IS inherited on upstreams (it is network identity only on networks) cluster: mainnet-beta upstreams: - id: solana-labs-mainnet endpoint: https://api.mainnet-beta.solana.com - id: helius-mainnet endpoint: https://mainnet.helius-rpc.com/?api-key=\${HELIUS_KEY} # a fork lives in its own network; checkGenesisHash opts the unknown # (chain, cluster) pair into bootstrap verification - id: fogo-mainnet endpoint: https://mainnet.fogo.io svm: chain: fogo cluster: mainnet checkGenesisHash: true ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreamDefaults: { // type is NOT inferred — declaring it here covers the whole pool type: "svm", // cluster IS inherited on upstreams (it is network identity only on networks) svm: { cluster: "mainnet-beta" }, }, upstreams: [ { id: "solana-labs-mainnet", endpoint: "https://api.mainnet-beta.solana.com" }, { id: "helius-mainnet", endpoint: "https://mainnet.helius-rpc.com/?api-key=\${HELIUS_KEY}" }, // a fork lives in its own network; checkGenesisHash opts the unknown // (chain, cluster) pair into bootstrap verification { id: "fogo-mainnet", endpoint: "https://mainnet.fogo.io", svm: { chain: "fogo", cluster: "mainnet", checkGenesisHash: true }, }, ], }] ``` ### Request/response behavior - `shouldSkip` runs before every `Forward` call. Skip reasons surface as `ErrUpstreamRequestSkipped` (HTTP 406) wrapping the underlying reason: `ErrUpstreamShadowing`, `ErrUpstreamSyncing`, `ErrUpstreamMethodIgnored`, `ErrUpstreamNotAllowed`. ([`upstream/upstream.go:L1505-1548`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1505-L1548)) - Block-availability failures produce `ErrUpstreamBlockUnavailable` (HTTP 503). The network layer classifies them retryable iff `block > latest > 0` and `distance ≤ maxRetryableBlockDistance` (default 128); beyond that they are wrapped as `ErrUpstreamRequestSkipped` to stop retries. ([`erpc/networks.go:L1862-1881`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1862-L1881)) - Computed bounds with finite min > max (e.g. `earliestBlockPlus` before detection completes) log a WARN and fail open — the upstream serves any block rather than incorrectly rejecting all of them. ([`upstream/upstream.go:L1199-1210`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1199-L1210)) - `eth_chainId` detection retries forever on transport errors; non-numeric chainId or configured-vs-detected mismatch is `TaskFatal` — the upstream stops retrying permanently. ([`upstream/upstream.go:L1419-1455`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1419-L1455)) - Cordon state is an explicit flag on the health tracker (NOT a metric). It survives rolling-window rotation and idle-sweep eviction; only `Reset()` (test/admin) clears it. `erpc_listCordoned` only reports wildcard (`"*"`) scope cordons — method-scoped cordons are not listed. ([`health/tracker.go:L598-615`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L598-L615)) ### Best practices - **Declare block windows explicitly.** Use `evm.blockAvailability.lower.latestBlockMinus: 128` for pruned full nodes rather than the deprecated `nodeType: full` — the explicit form is visible in config dumps and survives future refactors. - **Never rely on `allowMethods` alone.** Setting `allowMethods` without `ignoreMethods` silently injects `ignoreMethods: ["*"]`, blocking everything else. When you want a partial allow-list alongside a partial ignore-list, set both fields explicitly. - **List all tags on each upstream when mixing with defaults.** One tag on an upstream drops the entire `upstreamDefaults.tags` slice — there is no additive inheritance. Enumerate every intended tag per upstream explicitly. - **Set `batchMaxWait` to a non-zero value.** `batchMaxWait: 0` fires the batch immediately via `time.AfterFunc(0, ...)` — effectively the same as no batching. Use at least `10ms` to allow real coalescing. - **Use `rateLimitBudget` + `rateLimitAutoTune` together.** Auto-tune adjusts the effective budget based on observed error rate (10% threshold, 1-minute cadence by default). Without a budget, the auto-tuner is never created. - **Cordon instead of removing.** For emergency isolation — provider outage, billing alarm — call `erpc_cordonUpstream` via the Admin API. The cordon state survives metric-window rotation and does not need a config change or restart. - **Pick the right `earliestBlockPlus` probe for your archive node.** Most nodes use `blockHeader` (default). Use `traceData` only when the upstream has separate pruning boundaries for trace methods; `eventLogs` when log indices are available further back than state; `callState` when gating on historical balance/storage availability. ### Edge cases & gotchas 1. **`ws://`/`wss://` upstreams serve regular requests and feed subscriptions, but a plain HTTP `eth_subscribe` is never forwarded to them** (the subscription would have no owner). Clients subscribe through eRPC's own [WebSocket server](/operation/websocket.llms.txt) (`server.webSocket.enabled: true`). 2. **`allowMethods` without `ignoreMethods`** silently blocks all other methods via an injected `ignoreMethods: ["*"]`. To allow specific methods while keeping defaults, use `ignoreMethods` with explicit patterns instead. 3. **All-or-nothing tags inheritance**: one tag on an upstream drops all `upstreamDefaults.tags`. List every intended tag explicitly on each upstream. 4. **`vendorName` typo** returns `nil` from vendor lookup silently — the upstream runs as a bare endpoint without error normalization. No warning is logged. 5. **Repeated `Cordon` calls** update the reason but not the start timestamp (duration accounting survives reason edits). Changing reason creates a new gauge series; old series stays at 1 until a matching uncordon. 6. **`erpc_listCordoned` only reports wildcard (`"*"`) scope cordons** — method-scoped cordons are not listed. 7. **Uncordoning a method-scoped cordon does NOT clear a wildcard cordon** — `IsCordoned` checks `"*"` first. 8. **`maxAvailableRecentBlocks` and `blockAvailability` set simultaneously**: the back-compat synthesis fires only when `blockAvailability == nil`; explicit `blockAvailability` silently wins. 9. **Lower-bound re-poll race**: within 10 blocks of the pruning boundary a fresh poll runs; if the chain advanced, `firstAvailable` moves up and a block that was valid may flip to unavailable mid-check. 10. **`batchMaxWait: 0` fires instantly** — `time.AfterFunc(0, ...)` schedules the flush before additional requests can join. Set at least `10ms` to coalesce. 11. **`batchMaxSize: 0` with `supportsBatch: true`** means the batch fires immediately on the first queued request because `0 >= 0`. Use a value ≥ 2 to actually coalesce. 12. **Proxy URL scheme validation** is a case-insensitive prefix check, not URL parsing. `socks4://` and other schemes fail at startup even though they are syntactically valid URLs. 13. **`UniqueUpstreamKey` is order-unstable with ≥2 `jsonRpc.headers`** — Go map iteration is randomized, so two calls may produce different keys and re-create the client on each call. 14. **Negative or zero block numbers pass block-availability checks** — extracted block ≤ 0 is treated as "block not present in request" and the check is skipped (fail-open). 15. **Method-support results are cached forever per process.** `ShouldHandleMethod` caches per method name; later edits to Ignore/Allow lists don't invalidate existing entries. Only `IgnoreMethod` explicitly writes a `false` entry for its own case. 16. **State-poller bootstrap failure does NOT block registration** — upstream registers and serves; availability checks that need latest-block data error/fail-open until the poller recovers in background. 17. **`earliestBlockPlus` before detection completes computes `0 + N`.** If the probe hasn't run yet, earliest = 0, so bound = N. If N > latest, this can produce an invalid range (min > max) that triggers the fail-open WARN path. 18. **Forwarded headers are NOT sent on batch requests.** `req.ForwardHeaders` is consulted only in `sendSingleRequest`; callers relying on bearer-token forwarding must not use batching for those requests. 19. **Duplicate JSON-RPC IDs within a batch window flush the current batch.** If a second request arrives with the same `id` as one already queued, the pending batch fires immediately and the new request starts a fresh batch. This preserves ID-to-response mapping correctness but reduces batch efficiency for clients that reuse IDs. ([`clients/http_json_rpc_client.go:L255-261`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L255-L261)) 20. **`ErrUpstreamMalformedResponse` is retryable.** Raised when a batch response body is neither a JSON array nor a JSON object. Because it is not in the non-retryable allowlist, eRPC retries on another upstream. If all upstreams return malformed responses the request ends as `ErrUpstreamsExhausted`. HTTP status code on propagation is 400 (method-level), but the JSON-RPC wire response to the caller is still HTTP 200. 21. **`type` is not inferred from the endpoint.** A Solana endpoint without `type: svm` defaults to `evm`, and bootstrap then tries `eth_chainId` against it. Set `type: svm` on the upstream or on `upstreamDefaults`. 22. **An SVM upstream whose `svm.chain`/`svm.cluster` do not match the network's is not eligible for it.** There is no fuzzy match — an upstream with `cluster: mainnet-beta` never serves the `svm:testnet` network. Remember `chain: ""` means `solana`, so an upstream omitting `chain` cannot serve a `chain: fogo` network. 23. **Genesis-hash validation is fail-closed for known clusters.** For Solana `mainnet-beta`/`devnet`/`testnet`, both a hash mismatch **and** a `getGenesisHash` fetch failure fail the upstream — eRPC refuses to register one it could not verify. `checkGenesisHash` only affects *unknown* `(chain, cluster)` pairs. 24. **SVM upstreams are cordoned by their own state poller.** Beyond manual and breaker-driven cordons, two consecutive all-silent state polls or a shred-insert lag above 100 slots removes an SVM upstream from selection until it recovers. See [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt). 25. **SVM never gates on a vendor-reported floor by default.** An upstream's floor is probed, but skips nothing unless it declares `firstAvailableSlotPlus`. Otherwise every slot-named read reaches the upstream; `exactSlot: 0` explicitly declares full history. ([`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go)) 26. **SVM declared bounds fail-open when state is unknown.** A cold poller, an unobserved floor, or a computed min>max range treats that window as unbounded rather than refusing traffic. `firstAvailableSlotPlus` with an unobserved floor is unbounded — unlike EVM's `earliestBlockPlus`, unknown is not slot 0. 27. **`svm.blockAvailability` inherits from `upstreamDefaults.svm`.** Wholesale copy when the upstream omits its `svm` block; per-field copy of `blockAvailability` when the upstream has a partial `svm` block and left the field unset. Copies are deep — two upstreams must not alias the same pointer. ([`common/defaults.go:L1850-1877`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1850-L1877)) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_total` | counter | project, vendor, network, upstream, category, attempt, composite, finality, user, agent_name | Every attempt including hedges | | `erpc_upstream_request_errors_total` | counter | project, vendor, network, upstream, category, error, severity, composite, finality, user, agent_name | Attempt errors except skipped/missing-data/cancelled | | `erpc_upstream_request_skipped_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | `ErrUpstreamRequestSkipped` returned | | `erpc_upstream_request_missing_data_error_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | `ErrCodeEndpointMissingData` response | | `erpc_upstream_request_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Successful but emptyish result | | `erpc_upstream_response_size_bytes` | histogram | project, network, category, finality | Decoded result size of successful responses (buckets 4 KiB … 100 MiB) | | `erpc_upstream_attempt_outcome_total` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | Once per attempt at classification | | `erpc_upstream_selection_total` | counter | project, network, upstream, category, reason, finality | Once per attempt start; reason = primary/retry/hedge | | `erpc_upstream_breaker_state_change_total` | counter | project, upstream, transition | Breaker state transition | | `erpc_upstream_cordoned` | gauge | project, vendor, network, upstream, category, reason | 1 on cordon, 0 on uncordon | | `erpc_upstream_cordon_event_total` | counter | project, network, upstream, action | Edge transitions (cordon/uncordon) only | | `erpc_upstream_cordon_duration_seconds` | histogram (1 s … 86 400 s) | project, network, upstream | Observed on each uncordon | | `erpc_upstream_stale_upper_bound_total` | counter | project, vendor, network, upstream, category, confidence | Block/slot above upper bound. SVM `confidence` is `"configured"` for declared `svm.blockAvailability.upper`. | | `erpc_upstream_stale_lower_bound_total` | counter | project, vendor, network, upstream, category, confidence | Block/slot below lower bound. SVM `confidence` is `"configured"` (declared `svm.blockAvailability`). | ### Source code entry points - [`upstream/upstream.go:L136`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L136) — `Upstream` type: construction, bootstrap, `detectFeatures`, `Forward` hot path, `shouldSkip`, `ShouldHandleMethod`, block-availability assertions, cordon pass-throughs. - [`upstream/registry.go:L95`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L95) — `UpstreamsRegistry`: background bootstrap tasks, per-network upstream maps + atomic snapshots, `PrepareUpstreamsForNetwork` wait algorithm, shadow registration. - [`common/defaults.go:L1152`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1152) — `ApplyDefaults` (upstreamDefaults inheritance) + `SetDefaults` chain (id derivation, `allowMethods`→`ignoreMethods` injection, EVM defaults, legacy `nodeType`→`blockAvailability` synthesis, vendor shorthand conversion). - [`erpc/networks.go:L1919`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1919) — `checkUpstreamBlockAvailability`, `resolveEnforceBlockAvailability`, `handleBlockSkip` — single enforcement point for block availability at network layer. - [`health/tracker.go:L793`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L793) — cordon state storage, `Cordon`/`Uncordon`/`IsCordoned`/`CordonedReason`, idle-sweep protection. - [`clients/http_json_rpc_client.go:L109`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L109) — `GenericHttpJsonRpcClient` transport construction, batch aggregation, gzip pools, error normalization. - [`clients/proxy_pool_registry.go:L23`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L23) — `ProxyPool` round-robin selection via atomic counter. - [`upstream/upstream_block_availability_test.go`](https://github.com/erpc/erpc/blob/main/upstream/upstream_block_availability_test.go) — exhaustive availability edge cases: negative/zero blocks, reorgs, pruning races, poll-count assertions. ### Related pages - [Selection policies](/config/projects/selection-policies.llms.txt) — how upstreams are scored and ordered for each request. - [Rate limiters](/config/rate-limiters.llms.txt) — budget-based throttling bound to upstream IDs. - [Failsafe](/config/failsafe/retry.llms.txt) — per-upstream retry, hedge, timeout, and circuit-breaker config. - [Matcher / use-upstream](/config/matcher.llms.txt) — directive that pins a request to a specific upstream or tag. - [Admin API](/operation/admin.llms.txt) — cordon/uncordon RPCs and listing cordoned upstreams. - [getLogs splitting](/reference/evm/getlogs-splitting.llms.txt) — auto-splitting thresholds for `eth_getLogs` and `trace_filter`. - [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) — the per-upstream Solana slot/health poller and its cordoning behavior. - [SVM commitment & finality](/reference/svm/commitment.llms.txt) — how requests are normalized before they reach an SVM upstream. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — how upstreams + failsafe combine to keep requests flowing. --- --- # Rate Limiters > Source: https://docs.erpc.cloud/config/rate-limiters > Stop a runaway caller or a misbehaving provider from affecting everyone else — eRPC applies independent request budgets at four layers and self-tunes outbound limits automatically. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Rate Limiters Protect your infrastructure from runaway callers and prevent a misbehaving provider from eating your whole quota. eRPC applies named **budget** rules at four independent layers — auth, project, network, upstream — so you can cap inbound traffic per user, per IP, or globally, while a built-in **auto-tuner** silently backs off when upstreams send 429s and recovers when they clear up. ## Quick taste Illustrative, not a tuned production config — 100 req/s per IP on all inbound methods: **Config path:** `rateLimiters` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: - id: inbound rules: - method: "*" maxCount: 100 period: second # give each client IP its own counter, not a shared global pool perIP: true ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [{ id: "inbound", rules: [{ method: "*", maxCount: 100, period: "second", // give each client IP its own counter, not a shared global pool perIP: true, }], }], } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add per-IP and per-user inbound caps** ```text I want to protect my eRPC deployment from runaway callers: cap each client IP at 500 req/min globally, and give authenticated JWT users their own budget based on a claim in their token. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/config/rate-limiters.llms.txt ``` **Prompt Example #2: cap upstream spend with auto-tuning** ```text I'm paying per-request to Alchemy and I'm worried about unexpected bill spikes. Add an upstream-level rate limit budget to each Alchemy upstream in my eRPC config so eRPC never sends more than my target RPS, and enable the auto-tuner to back off automatically when they return 429s. Make sure minBudget is at least 1. Reference: https://docs.erpc.cloud/config/rate-limiters.llms.txt ``` **Prompt Example #3: protect a chain from heavy-method abuse** ```text During a traffic spike one user's eth_getBlockReceipts and trace_* calls filled all my proxy connections and took down the whole chain. Add a network-level rate limit budget in my eRPC config that hard-caps just those heavy methods fleet-wide, while leaving light methods like eth_blockNumber unrestricted. Reference: https://docs.erpc.cloud/config/rate-limiters.llms.txt ``` **Prompt Example #4: switch to Redis for multi-replica shared limits** ```text I'm scaling my eRPC deployment to multiple replicas and the per-process memory store means each instance has its own independent counter — the effective cluster limit is much higher than intended. Migrate my eRPC config rate limiter store to Redis so all replicas share a single counter. Use a distinct cacheKeyPrefix so staging and prod don't collide. Reference: https://docs.erpc.cloud/config/rate-limiters.llms.txt ``` **Prompt Example #5: debug why my upstream budget isn't returning 429** ```text My upstream-level rate limit budget is clearly being exceeded — I can see erpc_rate_limits_total incrementing — but my clients are getting HTTP 200 instead of 429. Explain why upstream-level blocks don't return HTTP 429 on the wire, and tell me which metric or log to watch to confirm the block is working correctly. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/rate-limiters.llms.txt ``` --- ### Rate Limiters — full agent reference ### How it works Every inbound request passes through up to four sequential rate-limit checks in this order: **auth → project → network → upstream**. Each check looks up the budget ID configured at that attachment point, calls `TryAcquirePermit`, and rejects with a layer-specific error if any matching rule is `OVER_LIMIT`. The layers are independent — a budget shared across layers will have its counter incremented once per layer per request, so avoid attaching the same budget ID at both project and network scope. Rule matching uses exact string equality first, then glob (`WildcardMatch`). If multiple rules match a single method, all are evaluated in parallel goroutines; the first `OVER_LIMIT` result short-circuits the rest. The backing store is either an in-process sharded memory cache (64 FNV-1a shards, lazy-expiry cleanup) or a Redis-backed Envoy ratelimit store. In memory mode, each eRPC process has independent counters — the effective cluster limit is `maxCount × instanceCount`. In Redis mode, counters are shared across all instances. When Redis cannot decide a request, `store.onFailure` does. **Over-limit cache.** Once Redis reports a rule's key over its limit, each replica keeps that key in a 4 MiB in-process cache until the window ends, and denies it from there. Other rules in the same request still go to Redis; if every matching key is cached, no Redis call is made, so the denial holds while Redis is down. Source: [`upstream/ratelimiter_registry.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go) **Redis store failures.** Four conditions leave a request undecided by Redis: 1. **`store_unavailable`** — not connected yet (startup, or first connect failed and retries in the background). 2. **`store_error`** — the Redis call failed (envoy panics on Redis errors; eRPC recovers). 3. **`admission_full`** — each budget caps in-flight Redis calls at `max(256, connPoolSize × 32)`. When full, no call or goroutine is started. This cap was added after the 2026-05-07 incident where 25k+ goroutines accumulated during a Redis contention spike. One request takes one slot, however many rules it matches: all matching rules go to Redis in one pipeline. 4. **`limit_timeout`** — no answer within `getTimeout` (default `1s`). The call keeps running and still updates the Redis counter. `store.onFailure` then decides: | `onFailure` | Undecided request | Cost | |---|---|---| | `allow` (default) | Admitted. `erpc_rate_limiter_failopen_total{reason}` increments. | A Redis incident lifts every limit. | | `deny` | Rejected as rate limited. | A Redis incident rejects all limited traffic. | | `local` | Decided by an in-process counter at `maxCount × localLimitFactor`. It counts every request, so it is warm when Redis fails. | One extra in-memory count per request. It counts this replica only, so set `localLimitFactor` near `1/replicas`. | Every undecided request increments `erpc_rate_limiter_store_failure_total{budget, reason, decision}`. **Auto-tuner.** When an upstream has `rateLimitBudget` set and `rateLimitAutoTune` is absent from config, eRPC automatically populates `rateLimitAutoTune` with defaults and sets `enabled: true`. This means **adding `rateLimitBudget` to an upstream implicitly enables the auto-tuner** unless you opt out with `rateLimitAutoTune.enabled: false`. The tuner samples `errorCount / totalCount` over each `adjustmentPeriod` (default 1 minute). If error rate exceeds `errorRateThreshold` (default 10%), `maxCount` is multiplied by `decreaseFactor` (default 0.95). If error rate is exactly 0, `maxCount` is multiplied by `increaseFactor` (default 1.05). Partial error rates in the range `(0, threshold]` produce no change. The tuner adjusts rules on the budget — which may be shared with other upstreams. If two upstreams share a budget and both have auto-tuners, the tuner that fires last wins; there is no coordination. **Envoy status codes.** The Envoy ratelimit library produces three response codes per descriptor. eRPC only inspects `OVER_LIMIT`: | Status | Counter range after increment | eRPC action | Internal stats | |---|---|---|---| | `OK` | `counter ≤ nearLimitThreshold` | Allow | `Stats.WithinLimit` | | `OK` (near limit) | `nearLimitThreshold < counter ≤ maxCount` | Allow | `Stats.WithinLimit` + `Stats.NearLimit` | | `OVER_LIMIT` | `counter > maxCount` | Block | `Stats.OverLimit` | Where `nearLimitThreshold = floor(maxCount × nearLimitRatio)`. Default ratio 0.8: for `maxCount=100`, requests 81–100 are allowed (near-limit stats only); request 101 is blocked. eRPC never surfaces `NEAR_LIMIT` to callers. Source: [`upstream/ratelimiter_budget.go:L306`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L306) **`TryAcquirePermit` flow.** (1) `GetRulesByMethod` returns empty → allow (no rules match). (2) If any matching rule uses `perIP`/`perUser`/`perNetwork` and `req == nil` → return error. (3) Every matching rule becomes one descriptor of a single `DoLimit` call: one Redis pipeline and one admission slot per request. The first `OVER_LIMIT` descriptor blocks. (4) If the store cannot answer, `store.onFailure` decides. Source: [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go) **Credit-weighted counting.** By default each acquisition consumes 1 hit (`HitsAddend: 1`). When an **upstream** sets `rateLimitCountMode: credit`, the upstream layer passes the request's pre-flight vendor credit-unit estimate as the hit weight, so a heavy `eth_getLogs` (e.g. 60 CU on Alchemy) drains the budget 60× faster than a flat request count. A `0`-CU method (e.g. `eth_chainId`) is admitted for free and consumes nothing. This weight rides the standard Envoy `HitsAddend`, so it works on both the memory and Redis stores. Source: [`upstream/upstream.go:L110-133`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L110-L133) **Credit counting at any scope.** A budget outside the upstream scope has no vendor to price its calls, so it prices them itself: set `countMode: credit` on a rule and give the budget a `creditUnits` table. This is how a project- or auth-scoped budget becomes a compute wallet: a per-IP allowance where `eth_getLogs` costs 60 and `eth_chainId` costs nothing, rather than a flat request count. The two sources never mix: an upstream on `rateLimitCountMode: credit` prices from its vendor's table, and pointing it at a budget that also defines `creditUnits` is a config error. Source: [`upstream/ratelimiter_budget.go:L306-332`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L306-L332) **Credit rules pool across methods.** Request counting partitions counters by method: `maxCount: 100` on a `*` rule means 100 requests per method per period. Credit counting does not, because the per-method cost is already carried by the hit weight, so the `method` descriptor entry is omitted and every method draws from **one** shared pool. `maxCount: 300000000` with `period: month` is therefore the provider plan it reads like ("300M CU/month"), not 300M CU for each method independently. Scope entries still apply: a `perIP` credit rule gives each client its own pool. A credit rule with no `creditUnits` at all prices every method at 1, which makes it a total request cap shared across methods, a ceiling that per-method counting cannot express. Source: [`upstream/ratelimiter_budget.go:L314-322`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L314-L322) **Mixing modes in one budget.** `countMode` is per rule, so a budget can hold a pooled credit wallet *and* flat per-method caps. A rule that states its mode keeps it even when the caller counts credits; only an unset mode inherits. This is the pattern for exempting a cheap method from the wallet (`creditUnits: {eth_chainId: 0}`) while still bounding it (`{method: eth_chainId, maxCount: 100, countMode: request}`). Source: [`upstream/ratelimiter_budget.go:L306-332`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L306-L332) **Cache key format.** `{cacheKeyPrefix}{domain}_{descriptor_entries_concatenated}_{time_window_bucket}`. The `erpc_rl_` prefix ensures isolation from other Envoy ratelimit users on the same Redis. Source: [`upstream/ratelimiter_registry.go:L76`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L76) **Memory store eviction.** Each shard prunes lazily: on every `DoLimit` call, if the shard's last-prune timestamp differs from the current unix second, all buckets with `expiry ≤ now` are deleted. This is O(#buckets) per shard — not O(#keys). Source: [`upstream/ratelimiter_mem_cache.go:L91-100`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_mem_cache.go#L91-L100) **Admission cap derivation.** `remoteAdmissionCap = max(256, connPoolSize × 32)`. It caps goroutines, not Redis capacity: each check sends one explicit pipeline and holds one pool connection for one round trip, with radix's implicit pipelining off. Pool of 8 → cap 256 (floor). Pool of 64 → cap 2048. Source: [`upstream/ratelimiter_registry.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go) **Auto-tuner minimum sample floor.** The tuner skips adjustment when `totalCount < 10` — insufficient signal. Counters are reset at the start of `maybeAdjust` regardless, so a sustained pattern of exactly 9 requests per period will perpetually reset the clock. Source: [`upstream/ratelimiter_autotuner.go:L83-142`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_autotuner.go#L83-L142) **Auto-tuner requires a budget.** An upstream without `rateLimitBudget` set never gets an auto-tuner instance, even if `rateLimitAutoTune` is explicitly configured. Source: [`upstream/upstream.go:L1322`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1322) **Shared budgets.** A budget ID is a plain string. Any number of attachment points — across projects, networks, upstreams, and auth strategies — can reference the same ID, sharing the same counters. In Redis mode this sharing extends across eRPC instances. **`waitTime` deprecation.** The `rules[].waitTime` field is explicitly ignored: validation emits a warning log and discards the value. There is no queue or hold logic in the rate limiter. Remove `waitTime` from any existing config to suppress the warning. ### Config schema #### `rateLimiters` (top-level) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `rateLimiters.store.driver` | string | `"memory"` | Backend store. Valid: `"memory"` or `"redis"`. Set by `RateLimitStoreConfig.SetDefaults`. **Footgun:** if `rateLimiters:` is present in YAML without an explicit `store.driver: redis`, the memory driver is silently used even if `store.redis.*` fields are configured. Source: [`common/defaults.go:L2782`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2782) | | `rateLimiters.store.redis.uri` | string | `""` | Redis URI; takes precedence over `addr`. Source: [`common/config.go:L390`](https://github.com/erpc/erpc/blob/main/common/config.go#L390) | | `rateLimiters.store.redis.addr` | string | `""` | `host:port`; used when `uri` is empty. Source: [`common/config.go:L384`](https://github.com/erpc/erpc/blob/main/common/config.go#L384) | | `rateLimiters.store.redis.username` | string | `""` | Redis ACL username. Source: [`common/config.go:L385`](https://github.com/erpc/erpc/blob/main/common/config.go#L385) | | `rateLimiters.store.redis.password` | string | `""` | Redis password; redacted in marshalled output. Source: [`common/config.go:L386`](https://github.com/erpc/erpc/blob/main/common/config.go#L386) | | `rateLimiters.store.redis.db` | int | `0` | Redis DB index. Source: [`common/config.go:L387`](https://github.com/erpc/erpc/blob/main/common/config.go#L387) | | `rateLimiters.store.redis.tls.enabled` | bool | `false` | Enable TLS. Source: [`common/config.go:L376`](https://github.com/erpc/erpc/blob/main/common/config.go#L376) | | `rateLimiters.store.redis.tls.certFile` | string | `""` | Client cert PEM for mTLS. Required with `keyFile` when server demands client auth. Source: [`common/config.go:L377`](https://github.com/erpc/erpc/blob/main/common/config.go#L377) | | `rateLimiters.store.redis.tls.keyFile` | string | `""` | Client key PEM for mTLS. Must match `certFile`. Source: [`common/config.go:L378`](https://github.com/erpc/erpc/blob/main/common/config.go#L378) | | `rateLimiters.store.redis.tls.caFile` | string | `""` | Custom CA bundle; system roots used when empty. Source: [`common/config.go:L379`](https://github.com/erpc/erpc/blob/main/common/config.go#L379) | | `rateLimiters.store.redis.tls.insecureSkipVerify` | bool | `false` | Skip server cert verification. Never use in production. Source: [`common/config.go:L380`](https://github.com/erpc/erpc/blob/main/common/config.go#L380) | | `rateLimiters.store.redis.connPoolSize` | int | `8` | Radix connection pool size. Derives admission cap: `max(256, connPoolSize × 32)`. Source: [`common/defaults.go:L955`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L955) | | `rateLimiters.store.redis.initTimeout` | Duration | `5s` | Connection establishment timeout. Source: [`common/defaults.go:L958`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L958) | | `rateLimiters.store.redis.getTimeout` | Duration | `1s` | Per-call DoLimit timeout. When exceeded, `store.onFailure` decides the request (`reason="limit_timeout"`). Source: [`common/defaults.go:L961`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L961) | | `rateLimiters.store.redis.setTimeout` | Duration | `3s` | **Unused by the rate limiter** — present for struct sharing with the data-connector Redis config. Source: [`common/defaults.go:L964`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L964) | | `rateLimiters.store.redis.lockRetryInterval` | Duration | `500ms` | **Unused by the rate limiter** — present for struct sharing with the data-connector Redis config. Source: [`common/defaults.go:L967`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L967) | | `rateLimiters.store.redis.iamAuth.enabled` | bool | `false` | Enables AWS ElastiCache IAM auth for the rate-limiter store. When true, `SetDefaults` auto-enables TLS (`rediss://`) and eRPC builds a `radix/v3` pool whose dial function mints a fresh SigV4 token per new connection. Mutually exclusive with a static password. Source: [`data/redis_ratelimiter_iam.go:L1-30`](https://github.com/erpc/erpc/blob/main/data/redis_ratelimiter_iam.go#L1-L30) | | `rateLimiters.store.redis.iamAuth.cacheName` | string | — | ElastiCache replication-group ID. Required when enabled. Lowercased automatically (AWS lowercases cache names at creation). Source: [`common/config.go:L533-545`](https://github.com/erpc/erpc/blob/main/common/config.go#L533-L545) | | `rateLimiters.store.redis.iamAuth.userID` | string | — | ElastiCache user. Required when enabled. The user **name and user ID must be identical** — supply that single value. Source: [`common/config.go:L533-545`](https://github.com/erpc/erpc/blob/main/common/config.go#L533-L545) | | `rateLimiters.store.redis.iamAuth.region` | string | derived | AWS region; derived from `AWS_REGION` / instance metadata when omitted. Source: [`common/config.go:L533-545`](https://github.com/erpc/erpc/blob/main/common/config.go#L533-L545) | | `rateLimiters.store.redis.iamAuth.auth.*` | `*AwsAuthConfig` | nil (default chain) | Optional AWS credential source (same fields as `dynamodb.auth`). Omit to use the instance-role / IRSA default chain (recommended on EKS/EC2). Source: [`common/config.go:L518-529`](https://github.com/erpc/erpc/blob/main/common/config.go#L518-L529) | | `rateLimiters.store.nearLimitRatio` | float32 | `0.8` | Envoy near-limit threshold fraction (`nearLimitThreshold = floor(maxCount × nearLimitRatio)`). **Has no effect on eRPC blocking decisions** — eRPC only checks `OVER_LIMIT`; `NEAR_LIMIT` is never returned to callers. Only alters internal Envoy stats counters, which are not exported to Prometheus. Source: [`upstream/ratelimiter_registry.go:L74`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L74) | | `rateLimiters.store.cacheKeyPrefix` | string | `"erpc_rl_"` | Prefix for all Redis/memory cache keys. **Footgun:** two eRPC deployments sharing the same Redis with the same prefix will merge their counters. Use distinct prefixes per deployment (`"erpc_prod_"`, `"erpc_staging_"`). Source: [`upstream/ratelimiter_registry.go:L76`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L76) | | `rateLimiters.store.onFailure` | string | `"allow"` | Redis only. `allow` \| `deny` \| `local`: what a request gets when Redis cannot decide it (not connected, error, `admission_full`, `limit_timeout`). See *Redis store failures* above. Source: [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go) | | `rateLimiters.store.localLimitFactor` | float | — | Required with `onFailure: local`, `(0, 1]`. The in-process limit is `min(maxCount, max(ceil(maxCount × localLimitFactor), hits))`, so a credit rule always fits one call (600 × 0.1 with a 200-credit call → 200). Set near `1/replicas`. Source: [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go) | #### `rateLimiters.budgets[]` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `budgets[].id` | string | required | Unique identifier referenced by `rateLimitBudget` fields. Source: [`common/config.go:L1806`](https://github.com/erpc/erpc/blob/main/common/config.go#L1806) | | `budgets[].rules[]` | list | required (min 1) | At least one rule required; empty list fails validation. Source: [`common/validation.go:L199`](https://github.com/erpc/erpc/blob/main/common/validation.go#L199) | | `budgets[].creditUnits` | `map[string]int64` | `nil` | Per-method cost table for this budget's `countMode: credit` rules. `"*"` is the fallback for unlisted methods; an entirely unpriced method costs `1`. A method priced `0` is **exempt**: credit rules skip it. Ignored by request-counting rules. **Footgun:** a `0`-priced method is served even after the pool is empty, so pair it with a flat `countMode: request` rule if it also needs a ceiling. Rejected on an upstream using `rateLimitCountMode: credit`, which prices from its vendor's table instead. Source: [`common/config.go:L1992-2000`](https://github.com/erpc/erpc/blob/main/common/config.go#L1992-L2000) | | `budgets[].rules[].method` | string | `"*"` | JSON-RPC method name or glob (`eth_*`, `*`). Default set by `SetDefaults`. Source: [`common/defaults.go:L2818`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2818) | | `budgets[].rules[].maxCount` | uint32 | required | Max requests per `period`. Mutable at runtime by auto-tuner. **Footgun: `maxCount: 0` means always-blocked**, not unlimited — the Envoy library sets `overLimitThreshold=0` so every request is immediately `OVER_LIMIT`. Omit `rateLimitBudget` entirely for unrestricted access. **uint32 overflow guard:** `AdjustBudgetByFactor` computes the new value as float64 and clamps to `math.MaxUint32` (4,294,967,295) before narrowing to uint32, preventing wrap-around from a large `increaseFactor`. Source: [`upstream/ratelimiter_budget.go:L109-119`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L109-L119) | | `budgets[].rules[].period` | RateLimitPeriod | `second` | Window granularity. Accepted string aliases (case-insensitive): `second`/`1s`, `minute`/`1m`/`60s`, `hour`/`1h`/`3600s`, `day`/`1d`/`24h`/`86400s`, `week`/`7d`/`168h`/`604800s`, `month`/`30d`/`720h`/`2592000s`, `year`/`365d`/`8760h`/`31536000s`. Integer enum values `0`–`6` also accepted. **Footgun:** `"2h"` is rejected even though it parses — only values exactly equal to a canonical duration are accepted. Similarly, `"90s"` (= 1.5 minutes) is rejected. Source: [`common/config.go:L1882-1950`](https://github.com/erpc/erpc/blob/main/common/config.go#L1882-L1950) | | `budgets[].rules[].perIP` | bool | `false` | Partition counters by client IP. **Footgun:** when `clientIP` is empty or `"n/a"` (e.g. non-HTTP transport), the `ip` descriptor is silently omitted and the rule uses a shared global counter for all IP-less callers. Source: [`upstream/ratelimiter_budget.go:L256-264`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L256-L264) | | `budgets[].rules[].perUser` | bool | `false` | Partition counters by authenticated user ID. Falls back to global counter when user label is empty or `"n/a"`. Source: [`common/config.go:L1816`](https://github.com/erpc/erpc/blob/main/common/config.go#L1816) | | `budgets[].rules[].perNetwork` | bool | `false` | Partition counters by network ID. Source: [`common/config.go:L1818`](https://github.com/erpc/erpc/blob/main/common/config.go#L1818) | | `budgets[].rules[].countMode` | `"request"` \| `"credit"` | inherits caller (`"request"` outside upstream scope) | What the rule counts. `"request"` charges a flat 1 per call and keeps a **counter per method**. `"credit"` charges the method's cost from `budgets[].creditUnits` and pools **every method into one counter**, so `maxCount` is a wallet rather than a per-method ceiling. Left unset, the rule inherits the caller's mode, which is `credit` only for an upstream on `rateLimitCountMode: credit`. Requires `maxCount > 0`. Source: [`upstream/ratelimiter_budget.go:L306-332`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L306-L332) | | `budgets[].rules[].waitTime` | Duration | `0` | **Deprecated — ignored with warning log.** Remove from config. Source: [`common/validation.go:L214-216`](https://github.com/erpc/erpc/blob/main/common/validation.go#L214-L216) | #### Attachment points | Config path | Scope | Evaluation order | Source | |---|---|---|---| | `projects[].auth.strategies[].rateLimitBudget` | Per auth strategy | 1st | [`auth/authorizer.go:L119`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L119) | | `projects[].auth.strategies[].secret.*.rateLimitBudget` | Per secret (overrides strategy) | 1st | [`auth/strategy_secret.go:L29`](https://github.com/erpc/erpc/blob/main/auth/strategy_secret.go#L29) | | `projects[].auth.strategies[].jwt.rateLimitBudgetClaimName` | JWT claim (default `"rlm"`) | 1st | [`auth/strategy_jwt.go:L87`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go#L87) | | `projects[].rateLimitBudget` | Project-level | 2nd | [`erpc/projects.go:L113`](https://github.com/erpc/erpc/blob/main/erpc/projects.go#L113) | | `projects[].networkDefaults.rateLimitBudget` | Default for all networks | 3rd | [`common/defaults.go:L1783`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1783) | | `projects[].networks[].rateLimitBudget` | Network-level | 3rd | [`erpc/networks.go:L1112`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1112) | | `projects[].upstreamDefaults.rateLimitBudget` | Default for all upstreams | 4th | [`common/defaults.go:L1514`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1514) | | `projects[].upstreams[].rateLimitBudget` | Upstream-level | 4th | [`upstream/upstream.go:L460`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L460) | | `projects[].auth.strategies[].siwe.rateLimitBudget` | SIWE per-session | 1st | [`auth/strategy_siwe.go:L53`](https://github.com/erpc/erpc/blob/main/auth/strategy_siwe.go#L53) | | `projects[].auth.strategies[].network.rateLimitBudget` | IP-network strategy | 1st | [`auth/strategy_network.go:L65`](https://github.com/erpc/erpc/blob/main/auth/strategy_network.go#L65) | | `projects[].auth.strategies[].database.failOpen.rateLimitBudget` | DB fail-open | 1st | [`auth/strategy_database.go:L526`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L526) | User-level budget (set by auth strategy on the user object) overrides strategy-level `rateLimitBudget`. Source: [`auth/authorizer.go:L119-122`](https://github.com/erpc/erpc/blob/main/auth/authorizer.go#L119-L122) #### `upstreams[].rateLimitAutoTune` Available only on `UpstreamConfig`. **Implicitly created with `enabled: true` when `rateLimitBudget != ""` and `rateLimitAutoTune` is absent.** Explicitly set `rateLimitAutoTune.enabled: false` to opt out. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `rateLimitAutoTune.enabled` | \*bool | `true` | Enable/disable. Source: [`common/defaults.go:L2491`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2491) | | `rateLimitAutoTune.adjustmentPeriod` | Duration | `1m` | Minimum elapsed time between adjustments per method. Clock resets even when no adjustment occurs (insufficient samples). Source: [`common/defaults.go:L2494`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2494) | | `rateLimitAutoTune.errorRateThreshold` | float64 | `0.1` | Decrease triggered when `errorRate > threshold`. Source: [`common/defaults.go:L2497`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2497) | | `rateLimitAutoTune.increaseFactor` | float64 | `1.05` | Multiplier when `errorRate == 0` exactly. **No increase when errorRate is in `(0, threshold]`.** Source: [`common/defaults.go:L2499`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2499) | | `rateLimitAutoTune.decreaseFactor` | float64 | `0.95` | Multiplier when `errorRate > threshold`. Source: [`common/defaults.go:L2503`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2503) | | `rateLimitAutoTune.minBudget` | int | `0` | Floor for `maxCount` after adjustment. **Footgun: `0` means no floor** — auto-tuner can drive `maxCount` to 0 (always-blocked). Set to at least 1. Source: [`common/config.go:L1057`](https://github.com/erpc/erpc/blob/main/common/config.go#L1057) | | `rateLimitAutoTune.maxBudget` | int | `100000` | Ceiling for `maxCount` after adjustment. Source: [`common/defaults.go:L2506`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2506) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Redis store with tuned pool for a multi-replica fleet.** In production, each eRPC machine handles 50k+ rate-limit checks per minute; the default `connPoolSize: 8` queues requests and accumulates goroutines under load. A larger pool with a generous-but-bounded `getTimeout` keeps the 99th-percentile check under 1ms without leaking goroutines during Redis slowdowns: **Config path:** `rateLimiters` **YAML — `erpc.yaml`:** ```yaml rateLimiters: store: driver: redis redis: uri: "\${REDIS_URL}" # 200ms covers RTT with headroom while still fast-failing during # real outages. Each check is one round trip; implicit pipelining # is off, so no batching window adds to it. getTimeout: 200ms # Default is 8 — not enough for 12+ machine fleets. Each in-flight # check holds one connection; past the pool, checks wait for one. connPoolSize: 64 # Use distinct prefixes per environment — two deployments sharing the # same Redis and same prefix will silently merge their counters. cacheKeyPrefix: "erpc_prod_" budgets: - id: per-client rules: - method: "*" maxCount: 200 period: second perIP: true ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { store: { driver: "redis", redis: { uri: "\${REDIS_URL}", // 200ms: generous enough for pipeline RTT, tight enough to fail fast getTimeout: "200ms", // 64 × 32 = ~2k concurrent checks/machine without queueing connPoolSize: 64, }, // Distinct prefix per environment prevents counter merging cacheKeyPrefix: "erpc_prod_", }, budgets: [{ id: "per-client", rules: [{ method: "*", maxCount: 200, period: "second", perIP: true }], }], } ``` **2. Tiered per-user budgets via JWT claim.** Production edge deployments serve customers across multiple subscription tiers. The JWT claim `"rlm"` names the budget to use per token; the auth strategy resolves it per request without any project/network attachment. Both `perUser: true` and `perIP: true` can be combined for combinatorial (user, IP) keys: **Config path:** `projects[].auth` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: # Free tier: 6 000 req/min total per user - id: edge-tier-6krpm-total-unlimited-per-ip rules: - method: "*" maxCount: 6000 period: minute perUser: true # Paid tier: 60 000 req/min total + 500 req/min per IP ceiling - id: edge-tier-60krpm-total-500rpm-per-ip rules: - method: "*" maxCount: 60000 period: minute perUser: true - method: "*" maxCount: 500 period: minute perUser: true perIP: true projects: - id: main auth: strategies: - type: jwt jwt: # Token payload contains "rlm": "edge-tier-60krpm-total-500rpm-per-ip" rateLimitBudgetClaimName: rlm ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [ { id: "edge-tier-6krpm-total-unlimited-per-ip", rules: [{ method: "*", maxCount: 6000, period: "minute", perUser: true }], }, { id: "edge-tier-60krpm-total-500rpm-per-ip", rules: [ { method: "*", maxCount: 60000, period: "minute", perUser: true }, // Per-IP ceiling prevents one IP from consuming the entire budget { method: "*", maxCount: 500, period: "minute", perUser: true, perIP: true }, ], }, ], }, projects: [{ id: "main", auth: { strategies: [{ type: "jwt", jwt: { rateLimitBudgetClaimName: "rlm" } }] }, }] ``` **3. Upstream outbound budget with aggressive auto-tuner.** Production uses fast `adjustmentPeriod: 30s` (not the 1-minute default) and an asymmetric `decreaseFactor: 0.7` so the tuner cuts hard during 429 storms but restores slowly with `increaseFactor: 1.1`. Always set `minBudget: 1` — the default is `0` which lets the auto-tuner drive `maxCount` to zero (always-blocked): **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: - id: alchemy-global rules: - method: "*" maxCount: 300 period: second projects: - upstreams: - endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}" rateLimitBudget: alchemy-global rateLimitAutoTune: enabled: true # Faster reaction than the 1-minute default — providers can # 429-storm and recover inside a single minute adjustmentPeriod: 30s errorRateThreshold: 0.1 # Restore gently: 1.1× per period rather than default 1.05× increaseFactor: 1.1 # Cut aggressively: 0.7× per period (not the conservative 0.95×) # to shed load fast during a 429 storm decreaseFactor: 0.7 # CRITICAL: 0 means no floor — auto-tuner can drive to always-blocked minBudget: 1 maxBudget: 100000 ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [{ id: "alchemy-global", rules: [{ method: "*", maxCount: 300, period: "second" }] }], }, projects: [{ upstreams: [{ endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", rateLimitBudget: "alchemy-global", rateLimitAutoTune: { enabled: true, // 30s: faster reaction than the 1-minute default adjustmentPeriod: "30s", errorRateThreshold: 0.1, // Restore gently, cut hard increaseFactor: 1.1, decreaseFactor: 0.7, // Never let auto-tuner drive to 0 (= always-blocked) minBudget: 1, maxBudget: 100000, }, }], }] ``` **4. Network-level admission cap on heavy methods to protect proxy capacity.** After an incident where a single user's burst of `eth_getBlockReceipts` calls filled all Fly proxy connections for minutes, production now hard-caps just the methods empirically observed stacking up connections. Light methods like `eth_blockNumber` are intentionally not restricted — the cap is surgical, not global: **Config path:** `rateLimiters + projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: - id: cronos-mainnet rules: # Healthy peak for receipt methods is ~5 RPS fleet-wide; # 100 RPS gives 20× headroom while still protecting proxy capacity. - method: "eth_getBlockReceipts|eth_getTransactionReceipt" maxCount: 100 period: second # Trace/debug requests are large and slow — 30 RPS matches # their typical low volume and prevents runaway archive crawls. - method: "debug_*|trace_*|arbtrace_*" maxCount: 30 period: second projects: - id: main networks: - evm: chainId: 25 alias: cronos-mainnet # Network-level: the (N+1)th excess request gets 429-ed in <1ms # instead of holding a proxy slot for up to 16s on a slow upstream. rateLimitBudget: cronos-mainnet ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [{ id: "cronos-mainnet", rules: [ // 100 RPS = 20× headroom over observed healthy peak { method: "eth_getBlockReceipts|eth_getTransactionReceipt", maxCount: 100, period: "second" }, // Trace/debug: low expected volume, high slot cost if stuck { method: "debug_*|trace_*|arbtrace_*", maxCount: 30, period: "second" }, ], }], }, projects: [{ id: "main", networks: [{ evm: { chainId: 25 }, alias: "cronos-mainnet", rateLimitBudget: "cronos-mainnet", }], }] ``` **5. Isolated budget per vendor to prevent cross-chain auto-tune interference.** When multiple chains share a single vendor budget (e.g. `alchemy-global`) and the auto-tuner reacts to errors on one chain, it adjusts the budget for all chains. Isolating a high-traffic chain onto its own budget prevents a polygon 429 storm from cutting Ethereum's limit: **Config path:** `rateLimiters.budgets[] + upstreams[].rateLimitBudget` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: # Shared default for most chains - id: alchemy-global rules: - method: "*" maxCount: 300 period: second # Isolated: polygon errors won't affect ethereum's tuned limit - id: alchemy-polygon rules: - method: "*" maxCount: 300 period: second projects: - upstreams: - id: eth-mainnet-alchemy endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}" rateLimitBudget: alchemy-global - id: polygon-alchemy endpoint: "https://polygon-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}" # Isolated budget: auto-tuner reacting to polygon errors # will not lower the limit for eth-mainnet-alchemy rateLimitBudget: alchemy-polygon ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [ { id: "alchemy-global", rules: [{ method: "*", maxCount: 300, period: "second" }] }, // Isolated so polygon auto-tuner adjustments don't affect other chains { id: "alchemy-polygon", rules: [{ method: "*", maxCount: 300, period: "second" }] }, ], }, projects: [{ upstreams: [ { id: "eth-mainnet-alchemy", endpoint: "https://eth-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", rateLimitBudget: "alchemy-global" }, { id: "polygon-alchemy", endpoint: "https://polygon-mainnet.g.alchemy.com/v2/\${ALCHEMY_KEY}", rateLimitBudget: "alchemy-polygon" }, ], }] ``` **6. Per-IP compute wallet with an exempt hot method.** Counting requests treats a range scan and a chain-ID lookup as equal, so a per-IP cap has to be tuned for the worst case and ends up throttling cheap traffic. A credit rule prices each method instead and spends from one shared pool, so a client can make many cheap calls or a few expensive ones. `eth_chainId` is priced `0` to keep polling out of the wallet entirely, and because a `0`-priced method is served even once the pool is empty, a second flat rule keeps it bounded: **Config path:** `rateLimiters` **YAML — `erpc.yaml`:** ```yaml rateLimiters: budgets: - id: frontend # Roughly proportional to node work. Only relative values matter. creditUnits: "*": 20 # unlisted methods eth_chainId: 0 # exempt: never touches the wallet net_version: 0 eth_blockNumber: 10 eth_call: 26 eth_getLogs: 60 # range scans are the expensive case debug_traceTransaction: 300 rules: # The wallet. All methods share this pool, so maxCount is a # compute allowance per IP per minute, not a request count. - method: "*" countMode: credit maxCount: 20000 period: minute perIP: true # Exempt methods still need a ceiling, or a 0-priced method is # unlimited. countMode is explicit so this stays a flat per-method # count even if the caller is counting credits. - method: eth_chainId countMode: request maxCount: 100 period: second perIP: true ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { budgets: [{ id: "frontend", // Roughly proportional to node work. Only relative values matter. creditUnits: { "*": 20, // unlisted methods eth_chainId: 0, // exempt: never touches the wallet net_version: 0, eth_blockNumber: 10, eth_call: 26, eth_getLogs: 60, // range scans are the expensive case debug_traceTransaction: 300, }, rules: [ // The wallet. All methods share this pool, so maxCount is a // compute allowance per IP per minute, not a request count. { method: "*", countMode: "credit", maxCount: 20000, period: "minute", perIP: true, }, // Exempt methods still need a ceiling, or a 0-priced method is // unlimited. countMode is explicit so this stays a flat per-method // count even if the caller is counting credits. { method: "eth_chainId", countMode: "request", maxCount: 100, period: "second", perIP: true, }, ], }], } ``` ### Request/response behavior Full error code reference: | Error | HTTP status on wire | When produced | |---|---|---| | `ErrAuthRateLimitRuleExceeded` | 429 | Auth-level budget rule fires. Source: [`common/errors.go:L545`](https://github.com/erpc/erpc/blob/main/common/errors.go#L545) | | `ErrProjectRateLimitRuleExceeded` | 429 | Project-level budget rule fires. Source: [`common/errors.go:L1738`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1738) | | `ErrNetworkRateLimitRuleExceeded` | 429 | Network-level budget rule fires. | | `ErrUpstreamRateLimitRuleExceeded` | **200** (despite `ErrorStatusCode()=429`) | Upstream-level budget rule fires; wrapped into `ErrNoUpstreamsAvailable`. The `ErrorStatusCode()=429` only affects the gRPC adapter path. Source: [`common/errors.go:L1801-1821`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1801-L1821) | | `ErrRateLimitBudgetNotFound` | 200 (wrapped) | Budget ID typo — runtime error, not caught at startup. Source: [`upstream/ratelimiter_registry.go:L224`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L224) | | `ErrRateLimitRuleNotFound` | 200 (wrapped) | **No production call sites** — reserved for future use. Source: [`common/errors.go:L1723`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1723) | - **`rateLimiters` absent from config = full passthrough.** When `rateLimiters` is omitted entirely, `bootstrap()` logs `"no rate limiters defined which means all capacity of both local cpu/memory and remote upstreams will be used"` at debug level and returns immediately — no budgets are registered and every request is allowed. Source: [`upstream/ratelimiter_registry.go:L48-51`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L48-L51) - No response carries a `Retry-After` header from eRPC. ### Best practices - **Set `minBudget` on auto-tuner to at least `1`.** Default `minBudget: 0` lets the auto-tuner drive `maxCount` to zero (always-blocked). A floor of 10–20 preserves minimal throughput during sustained provider pressure. - **Use `driver: redis` with distinct `cacheKeyPrefix` per environment.** Memory mode makes each replica's limit independent (`effectiveLimit = maxCount × replicaCount`). Two Redis deployments sharing a prefix merge counters across environments. - **Don't attach the same budget at both project and network scope.** Each layer increments the counter independently — one request consumes two quota units. - **Prefer `method: "eth_getLogs"` rules over wildcard for expensive methods.** Wildcard rules matched by the auto-tuner affect every method's `maxCount`, not just the one that triggered the 429. - **Opt out of implicit auto-tune when you manage limits manually.** Adding `rateLimitBudget` to an upstream silently enables the auto-tuner. Add `rateLimitAutoTune.enabled: false` to any upstream where you want stable, manually-tuned limits. - **Never use `period: "2h"` or other compound durations.** Only the seven canonical period names are accepted; `"2h"` parses successfully but is rejected at unmarshal time. - **Watch `erpc_rate_limiter_store_failure_total`.** Sustained `reason="limit_timeout"` or `admission_full` means Redis is too slow for `getTimeout`. Pick `onFailure` for what a Redis incident should do: `local` keeps a per-replica limit, `deny` blocks. ### Edge cases & gotchas 1. **`waitTime` is silently ignored with a warning.** The field exists for backward compatibility. Validation logs `"rateLimiter.*.budget.rules.*.waitTime is deprecated and will be ignored"` and discards the value. No queue or hold behaviour exists. Source: [`common/validation.go:L214-216`](https://github.com/erpc/erpc/blob/main/common/validation.go#L214-L216) 2. **Auto-tuner is implicitly enabled when `rateLimitBudget` is set.** `SetDefaults` creates `RateLimitAutoTuneConfig{enabled: true}` when `rateLimitBudget != ""` and `rateLimitAutoTune == nil`. Explicitly set `rateLimitAutoTune.enabled: false` to prevent auto-adjustment. Source: [`common/defaults.go:L1674`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1674) 3. **Shared budget + two auto-tuners = last-writer wins.** If two upstreams share the same budget id, each has its own auto-tuner. Both independently call `AdjustBudgetByFactor` on the same rule objects; no locking between tuners. Source: [`upstream/upstream.go:L1321-L1339`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1321-L1339) 4. **Same budget at project + network layers double-counts.** Each check increments the counter independently. One request consumes two quota units when the same budget id is attached at both layers. Source: [`erpc/projects.go:L270`](https://github.com/erpc/erpc/blob/main/erpc/projects.go#L270), [`erpc/networks.go:L1112`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1112) 5. **`ErrUpstreamRateLimitRuleExceeded` does NOT return HTTP 429 on the wire.** The HTTP status switch at `erpc/http_server.go:1484-1490` lists auth/project/network errors but omits the upstream error code. An upstream-level block wraps into `ErrNoUpstreamsAvailable` and returns HTTP 200 with a JSON-RPC error body. Source: [`erpc/http_server.go:L1484-L1490`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1484-L1490) 6. **`ErrRateLimitBudgetNotFound` is a runtime error, not a startup error.** A typo in `rateLimitBudget` is not caught at config validation; the error fires on the first request to hit that code path. Source: [`upstream/ratelimiter_registry.go:L224`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L224) 7. **`maxCount: 0` blocks everything.** Envoy sets `overLimitThreshold=0`; any increment produces `OVER_LIMIT` immediately. To disable a budget, remove the `rateLimitBudget` reference rather than setting `maxCount: 0`. Source: [`upstream/ratelimiter_budget.go:L109-L119`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L109-L119) 8. **`perIP` / `perUser` / `perNetwork` fall back to a global counter when the value is empty or `"n/a"`.** IP-less callers (e.g. non-HTTP transports) all share one counter, potentially allowing far more traffic than intended for that scope. Source: [`upstream/ratelimiter_budget.go:L256-L264`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L256-L264) 9. **Memory store is per-process.** In a multi-replica deployment, each instance has independent counters; effective cluster limit = `maxCount × instanceCount`. Use `driver: redis` for shared counting. Source: [`upstream/ratelimiter_mem_cache.go:L1-L30`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_mem_cache.go#L1-L30) 10. **Redis `cacheKeyPrefix` collision.** Two eRPC deployments sharing a Redis instance with the same prefix will merge counters across deployments. Use distinct prefixes per environment. Source: [`upstream/ratelimiter_registry.go:L75-L76`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L75-L76) 11. **`store` block is auto-created with `driver="memory"` when absent.** Declaring `rateLimiters:` without `store.driver: redis` silently uses memory even if Redis fields are present. No warning is emitted. Source: [`common/defaults.go:L2763-2769`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2763-L2769) 12. **Wildcard rules affect auto-tuner scope broadly.** A rule `method: "eth_*"` matched by `eth_call` will have its `maxCount` adjusted whenever any `eth_*` method hits the error threshold — not only the method that triggered the change. Source: [`upstream/ratelimiter_autotuner.go:L113`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_autotuner.go#L113) 13. **Period `"2h"` is rejected.** `time.ParseDuration("2h")` succeeds but `2*time.Hour` does not equal any canonical period. Only exact matches to `second`, `minute`, `hour`, `day`, `week`, `month`, `year` (and their aliases) are accepted. Source: [`common/config.go:L1924-1944`](https://github.com/erpc/erpc/blob/main/common/config.go#L1924-L1944) 14. **Redis DoLimit goroutines outlive their callers.** After `getTimeout` fires, the goroutine continues running and completes the Redis write. The counter is updated even though `onFailure` already decided the caller. This prevents counter drift but means Redis receives more writes than the caller observes. Source: [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go) 15. **Auto-tuner `adjustmentPeriod` clock resets on insufficient samples.** `lastAdjustments[method]` is updated at the start of `maybeAdjust` regardless of whether an actual adjustment occurs. A sustained pattern of exactly 9 requests per period (below the 10-sample floor) will perpetually reset the clock and prevent any evaluation. Source: [`upstream/ratelimiter_autotuner.go:L94`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_autotuner.go#L94) 16. **Auto-tuner only increases when `errorRate == 0.0` exactly.** Partial improvement in `(0, threshold]` produces no adjustment — budget will not grow back until error rate reaches exactly zero. Source: [`upstream/ratelimiter_autotuner.go:L107-L112`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_autotuner.go#L107-L112) 17. **`minBudget: 0` is no floor.** Default `minBudget=0` means no clamping floor — the auto-tuner can drive `maxCount` to 0, making the budget always-blocked. Set to at least 1. Source: [`common/config.go:L1057`](https://github.com/erpc/erpc/blob/main/common/config.go#L1057) 18. **`nearLimitRatio` has no effect on blocking decisions.** eRPC only inspects `OVER_LIMIT`; `NEAR_LIMIT` is never surfaced. The field only affects internal Envoy stats counters, which are not exported to Prometheus. Source: [`upstream/ratelimiter_budget.go:L306`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L306) 19. **No enforcement on nil request when all rules are non-scoped.** If `req == nil` is passed and all matching rules have `perIP=false`, `perUser=false`, `perNetwork=false`, validation does not reject the nil request — it proceeds with the method-only descriptor. Source: [`upstream/ratelimiter_budget.go:L188-191`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L188-L191) 20. **`ErrRateLimitRuleNotFound` has no production call sites.** The error type is defined in `common/errors.go` but no production code calls `NewErrRateLimitRuleNotFound` — it appears reserved for future use. Source: [`common/errors.go:L1723`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1723) 21. **Admission cap floor of 256 applies regardless of pool size.** Even with `connPoolSize: 1`, the admission cap is 256. Small pools on low-traffic instances still allow 256 concurrent Redis calls per budget before shedding. Source: [`upstream/ratelimiter_registry.go:L281-291`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L281-L291) 22. **A `0`-priced method is unlimited on that rule, not merely free.** Credit rules skip a `0`-cost method rather than sending a `0` addend, because the request-level `HitsAddend` coerces `0` to `1` (`GetHitsAddends` in envoyproxy/ratelimit), which would charge a full hit. Skipping means the method keeps being served after the pool is exhausted. Pair any `0`-priced method with a flat `countMode: request` rule if it also needs a ceiling. Source: [`upstream/ratelimiter_budget.go:L314-320`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L314-L320) 23. **Credit units are not comparable across vendors.** One budget shared by upstreams of different vendors accumulates each vendor's own units into a single pool: Alchemy CU and dRPC units summed as if they were the same currency. Give each vendor its own budget. Source: [`common/vendors.go:L18-41`](https://github.com/erpc/erpc/blob/main/common/vendors.go#L18-L41) 24. **A credit pool reports blocks against the concrete method that tripped it.** `erpc_rate_limits_total` and the internal stats key label by method independently of the descriptor, so a block on a cross-method wallet shows up as (say) `eth_call` being limited when the truth is that the pool is empty. Read it as "the wallet ran out while serving `eth_call`". Source: [`upstream/ratelimiter_budget.go:L336`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L336) 25. **A budget shared by credit-mode and request-mode upstreams keeps two counters per rule.** Credit counting omits the `method` descriptor entry and request counting includes it, so the two modes generate different cache keys for the same rule and each accumulates independently. Point a credit budget at credit-mode upstreams only. Source: [`upstream/ratelimiter_budget.go:L298-305`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L298-L305) 26. **IAM connections for the rate-limiter store recycle at a flat 11h.** Unlike the main Redis connector (which adds ±30m jitter), the rate-limiter IAM pool uses a flat `PoolMaxLifetime(11h)` — radix lacks a jitter knob. All connections created at startup will expire in the same ~11h window. For a small pool this is acceptable; connections dialed under load spread naturally. Source: [`data/redis_ratelimiter_iam.go:L70-76`](https://github.com/erpc/erpc/blob/main/data/redis_ratelimiter_iam.go#L70-L76) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_rate_limits_total` | counter | `project, network, vendor, upstream, category, finality, user, agent_name, budget, scope, auth, origin` | A budget rule denies a request. `origin` ∈ `{auth, project, network, upstream}` | | `erpc_rate_limiter_budget_max_count` | gauge | `budget, method, scope` | Set at budget initialization and on every auto-tuner adjustment | | `erpc_rate_limiter_failopen_total` | counter | `project, network, user, agent_name, budget, category, reason` | `onFailure: allow` admitted a request Redis could not decide; `reason` ∈ `{store_unavailable, store_error, admission_full, limit_timeout}` | | `erpc_rate_limiter_store_failure_total` | counter | `budget, reason, decision` | Every request Redis could not decide; `decision` ∈ `{allow, deny, local_allow, local_deny}` | | `erpc_rate_limiter_remote_inflight` | gauge | `budget` | Incremented when a Redis DoLimit goroutine starts; decremented on completion or panic | | `erpc_rate_limiter_remote_admission_shedded_total` | counter | `budget` | Admission semaphore was full; no Redis call was started | | `erpc_rate_limiter_remote_duration_seconds` | histogram | `budget, result` | Duration of each Redis DoLimit call; `result` ∈ `{ok, over_limit, fail_open}` (`fail_open`: error or timeout) | | `erpc_rate_limiter_budget_decision_total` | counter | `project, network, category, finality, user, agent_name, budget, method, scope, decision` | **DEPRECATED** — replaced by `erpc_rate_limits_total`. Zero call sites in production code. Source: [`telemetry/metrics.go:L515`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L515) | | `erpc_unexpected_panic_total` | counter | `origin, store, fingerprint` | Redis DoLimit goroutine panicked and was recovered; `origin="ratelimiter-redis-dolimit"` | Trace spans: `RateLimiter.TryAcquirePermit` (attrs: `budget`, `method`) and `RateLimiter.DoLimit` (attrs: `budget`, `method`, `scope`, `result`, one per rule evaluated). Source: [`upstream/ratelimiter_budget.go:L161`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L161), [`upstream/ratelimiter_budget.go:L279`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L279) **Log messages.** | Level | Message | When | |---|---|---| | `Debug` | `"no rate limiters defined which means all capacity of both local cpu/memory and remote upstreams will be used"` | `cfg == nil` at bootstrap. | | `Debug` | `"initializing rate limiter budget"` | Each budget initialized. | | `Debug` | `"preparing rate limiter rule: ..."` | Each rule added to budget. | | `Warn` | `"failed to initialize Redis rate limiter on first attempt (rate limiting will fail-open until connected, retrying in background)"` | Redis first-connect fails. | | `Info` | `"successfully connected to Redis for rate limiting"` | Redis connected. | | `Debug` | `"rate limiter timeout exceeded, failing open"` | `doLimitWithTimeout` timer fires. Logged at debug level only to avoid spam under sustained Redis pressure. | | `Warn` | `"adjusting rate limiter budget from: X to: Y"` | Auto-tuner changes `maxCount`. | | `Info` | `"auto-tuner: adjusting rate limit budget"` | Auto-tuner fires (method, prev, next, errorRate, samples, direction). | | `Warn` | `"rateLimiter.*.budget.rules.*.waitTime is deprecated and will be ignored"` | `waitTime != 0` at validation. | ### Source code entry points - [`upstream/ratelimiter_registry.go:L1-L300`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L1-L300) — Registry creation, Redis connect (background retry), budget initialization, `GetBudget`, admission cap: `remoteAdmissionCap` - [`upstream/ratelimiter_budget.go:L1-L460`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L1-L460) — `RateLimiterBudget`: `TryAcquirePermit`, parallel rule evaluation, `evaluateRule`, `doLimitWithTimeout`, `AdjustBudgetByFactor` - [`upstream/ratelimiter_autotuner.go:L1-L145`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_autotuner.go#L1-L145) — `RateLimitAutoTuner`: `RecordSuccess`, `RecordError`, `maybeAdjust` with error-rate logic - [`upstream/ratelimiter_mem_cache.go:L1-L130`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_mem_cache.go#L1-L130) — In-process sharded bucketed counter cache; 64 FNV-1a shards, lazy O(#buckets) cleanup - [`common/config.go:L1806-L1950`](https://github.com/erpc/erpc/blob/main/common/config.go#L1806-L1950) — `RateLimiterConfig`, `RateLimitBudgetConfig`, `RateLimitRuleConfig`, `RateLimitPeriod` enum + marshal/unmarshal - [`common/defaults.go:L2763-L2820`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2763-L2820) — `SetDefaults` for all rate limit types; auto-tune defaults; implicit auto-tune population - [`common/validation.go:L199-L216`](https://github.com/erpc/erpc/blob/main/common/validation.go#L199-L216) — Budget/rule validation; `waitTime` deprecation warning - [`upstream/ratelimiter_leak_test.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_leak_test.go) — Goroutine leak tests reproducing the 2026-05-07 Redis contention incident and admission panic safety ### Related pages - [Auth](/config/auth.llms.txt) — authentication strategies that set per-user `rateLimitBudget` via JWT claims or per-secret overrides. - [Projects](/config/projects.llms.txt) — project-level `rateLimitBudget` attachment. - [Hedge](/config/failsafe/hedge.llms.txt) — hedge bursts add request volume; combine with upstream rate limiters to cap the cost on expensive vendors. - [Retry](/config/failsafe/retry.llms.txt) — retries also add upstream request volume; upstream budgets apply per-attempt. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — how rate limiting and failsafe cooperate under provider pressure. --- --- # Server > Source: https://docs.erpc.cloud/config/server > eRPC's front door — dual-stack listeners, TLS/mTLS, a hard global timeout, gzip, drain-aware shutdown, and domain aliasing so any Host header routes to the right chain without touching a URL path. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Server eRPC's `server:` block is your front door to every chain. One setting gives every deploy a clean drain window so zero requests drop during rollouts. Another collapses a sprawling URL scheme into bare hostnames like `eth.example.com`. Configure it once and stop worrying about dropped connections, spoofed IPs, or timeout mismatches between your LB and eRPC's own retry loop. **What you get** - Dual IPv4/IPv6 HTTP listeners with optional gRPC sharing on the same port - TLS and mutual TLS with a single extra field - Graceful two-phase drain so load balancers deplete before the process exits - Domain-based aliasing: map any `Host` header directly to a project and chain ## Quick taste Illustrative, not a tuned production config — minimal HTTP server with a 30-second ceiling: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: listenV4: true httpHostV4: "0.0.0.0" httpPortV4: 4000 # hard ceiling for the full request lifecycle — must be > sum of retry delays + hedge delay maxTimeout: 30s ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { listenV4: true, httpHostV4: "0.0.0.0", httpPortV4: 4000, // hard ceiling for the full request lifecycle — must be > sum of retry delays + hedge delay maxTimeout: "30s", }, }); ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure server for production behind a load balancer** ```text Set up the eRPC server block in my eRPC config for production: behind an AWS ALB or Cloudflare, I need real client IPs extracted for per-IP rate limiting, a graceful drain window long enough for my LB health checks, and a maxTimeout that sits above my longest retry+hedge chain. Read the full reference first: https://docs.erpc.cloud/config/server.llms.txt ``` **Prompt Example #2: enable gRPC on a dedicated port without disrupting HTTP** ```text I want to enable the gRPC endpoint on eRPC but keep it on a separate port so HTTP traffic doesn't share the gRPC mux (and lose TimeoutHandler coverage). Update my eRPC config accordingly. Reference: https://docs.erpc.cloud/config/server.llms.txt ``` **Prompt Example #3: add mTLS so only my internal services can reach eRPC** ```text Lock down my eRPC instance so only services that present a certificate signed by my internal CA can connect. I only want to add the minimum fields needed — no unnecessary TLS knobs. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/config/server.llms.txt ``` **Prompt Example #4: debug clients seeing wrong IPs or rate limits misfiring** ```text My per-IP rate limits are all firing against the load balancer address instead of the real client IP. Help me fix trustedIPForwarders and trustedIPHeaders in my eRPC config, and explain which headers are safe to trust given my proxy topology. Reference: https://docs.erpc.cloud/config/server.llms.txt ``` **Prompt Example #5: map subdomains to chains without changing URL paths** ```text I want eth.example.com and arb.example.com to route to Ethereum mainnet and Arbitrum without clients needing a /project/evm/1 path. Set up domain-based aliasing rules in my eRPC config. Reference: https://docs.erpc.cloud/config/server.llms.txt ``` --- ### Server — full agent reference ### How it works **Handler chain.** `NewHttpServer` composes the stack innermost to outermost: `createRequestHandler` → optional `gzipHandler` (response compression) → custom `TimeoutHandler` (global deadline = `maxTimeout`) → optionally a gRPC content-type mux on IPv4 when gRPC shares the HTTP port. Two independent `http.Server` instances handle IPv4 and IPv6; only those whose `listenV4`/`listenV6` flag is true are created, and `Start()` fails if neither is set. gRPC sharing only ever applies to the IPv4 server. Source: [`erpc/http_server.go:L152-216`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L152-L216) **Cleartext HTTP/2 (h2c).** Without TLS, both servers set `http.Server.Protocols` to HTTP/1.1 + unencrypted HTTP/2, so net/http itself serves HTTP/2 prior-knowledge connections next to HTTP/1.1 on the same port. Because net/http owns these connections, they drain like every other connection on shutdown (see Graceful shutdown). Only prior knowledge is supported: an HTTP/1.1 request carrying `Upgrade: h2c` is answered over HTTP/1.1 and the upgrade is ignored. With TLS, `Protocols` stays unset and HTTP/2 is negotiated via ALPN. Source: [`erpc/http_server.go:L179-192`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L179-L192) **Timeout machinery.** eRPC does NOT use `net/http`'s built-in `TimeoutHandler`. Its own implementation buffers the entire response body in a pooled `bytes.Buffer` and stages headers privately; only when the inner handler finishes within the deadline does it flush to the real connection. On timeout: JSON-RPC `-32603` body at HTTP 200 (POST) or 504 (other). On client cancel: "request cancelled by client" at HTTP 200 (POST) or 503 with empty body (other). Source: [`erpc/http_timeout.go:L20-143`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L20-L143) **Request and response gzip.** `enableGzip: true` wraps the handler in a `conditionalGzipWriter`. Body writes (and any explicit status code) are held back until the cumulative body size reaches 1024 bytes; at that point `Content-Length` is deleted, `Content-Encoding: gzip` is set, and all bytes (buffered and subsequent) flow through a pooled `gzip.Writer`. If the handler finishes or flushes below 1024 bytes, the buffered bytes are sent uncompressed. The decision is cumulative rather than first-write-only because `JsonRpcResponse.WriteTo` streams the ~22-byte envelope prefix before the result. `Vary: Accept-Encoding` is set on every response through the handler, compressed or not. Inbound gzip bodies (`Content-Encoding: gzip`) are always accepted and decompressed using a pooled reader, regardless of `enableGzip`. Source: [`erpc/http_server.go:L2252-2412`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L2252-L2412) **gRPC port sharing.** When `grpcEnabled: true` and the gRPC v4 host:port equal the HTTP v4 host:port (the default derivation), the IPv4 HTTP handler multiplexes: HTTP/2 + `Content-Type: application/grpc` → in-process gRPC server (`grpc.Server.ServeHTTP`), bypassing `TimeoutHandler` and `gzipHandler` entirely. Without TLS, gRPC clients reach it over the native cleartext HTTP/2 above. Sharing never applies to IPv6. Because shared-port gRPC rides the HTTP server's connections, it drains with them on shutdown (GOAWAY, in-flight RPCs finish); `GracefulStop` only runs for a standalone gRPC server. To run a standalone gRPC server on a different port, set `grpcPortV4` to a different value. Source: [`erpc/http_server.go:L164-177`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L164-L177) **TLS and mTLS.** When `tls.enabled` is true, both listeners use `ListenAndServeTLS` with TLS 1.2 as the minimum version, and gRPC uses TLS credentials. Setting `caFile` is the only knob needed to enable mTLS: it populates `ClientCAs` and sets `ClientAuth = RequireAndVerifyClientCert`, forcing every client to present a valid certificate. Source: [`erpc/http_server.go:L1537-1637`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1537-L1637) **Trusted-proxy IP extraction.** `resolveRealClientIP` trusts forwarding headers only when the direct peer is inside `trustedIPForwarders` (default: loopback only). It walks `trustedIPHeaders` in order, parses each value XFF-style, strips trailing trusted-proxy entries right-to-left, and returns the nearest untrusted hop. If every hop is trusted, it falls back to the direct peer IP. RFC 7239 `Forwarded` is not supported. Source: [`erpc/http_server.go:L1782-1905`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1782-L1905) **Domain-based aliasing.** `server.aliasing.rules[]` maps a request `Host` header to a pre-selected `(project, architecture, chain)` so callers can use a bare URL like `https://eth.example.com`. Rules are evaluated in order; first wildcard match wins. Not every combination of `serveProject`/`serveArchitecture`/`serveChain` is valid — see Edge cases. Source: [`erpc/http_server.go:L232-257`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L232-L257) **Graceful shutdown.** On SIGTERM the app context is cancelled and shutdown runs in this order (Source: [`erpc/http_server.go:L226-256`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L226-L256), [`erpc/init.go:L221-236`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L221-L236)): 1. A `draining` flag flips immediately, so `GET /healthcheck` returns 503 "shutting down" and the LB stops sending new connections. 2. Keep-alives are disabled on both servers: idle HTTP/1.1 connections are closed, every HTTP/1.1 response carries `Connection: close`, and every HTTP/2 connection (h2 over TLS and h2c) gets GOAWAY the next time its last open stream completes (one that stays idle gets it in step 4). Pooled clients move to other instances during the grace window. 3. eRPC sleeps `waitBeforeShutdown` (default `10s`) while still serving. 4. `http.Server.Shutdown` runs with a hard-coded 30s budget. It closes the listeners and idle HTTP/1.1 connections, sends GOAWAY on every HTTP/2 connection, and waits for in-flight requests and streams to finish. When the budget runs out it gives up waiting and logs "http server forced to shutdown". 5. Only after step 4 returns does `Init` flush the integrity exporters, sleep `waitAfterShutdown` (default `10s`) and return, at which point the process exits. Worst-case lifetime after SIGTERM is therefore `waitBeforeShutdown + drain (≤ 30s) + waitAfterShutdown`: 50s with defaults. The drain ends as soon as the last connection closes, so it is usually far shorter than 30s. ### Config schema All fields live under `server.` unless noted. `Duration` accepts Go duration strings (`"30s"`) or bare integers interpreted as **milliseconds** (`"150"` = 150 ms, not 150 s). Struct at [`common/config.go:L130-200`](https://github.com/erpc/erpc/blob/main/common/config.go#L130-L200). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `server.listenV4` | `*bool` | `true` (except under `go test`) | Enables the IPv4 `http.Server`. Validation requires `httpHostV4` + `httpPortV4` when true. [`common/defaults.go:L640-644`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L640-L644) | | `server.httpHostV4` | `*string` | `"0.0.0.0"` | IPv4 bind host. [`common/defaults.go:L645-647`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L645-L647) | | `server.httpPortV4` | `*int` | `4000` | IPv4 HTTP port. Startup fails with "server.httpPortV4 is not configured" if nil while `listenV4` is true. [`common/defaults.go:L655-657`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L655-L657) | | `server.listenV6` | `*bool` | unset (OFF) | IPv6 must be opted in; `SetDefaults` never sets it. [`erpc/http_server.go:L191`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L191) | | `server.httpHostV6` | `*string` | `"[::]"` | IPv6 bind host. [`common/defaults.go:L648-650`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L648-L650) | | `server.httpPortV6` | `*int` | `httpPortV4 + 1000` (default `5000`) | Derived to avoid collision with the default metrics port 4001. [`common/defaults.go:L658-668`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L658-L668) | | `server.httpPort` | `*int` | deprecated alias of `httpPortV4` | If set and `httpPortV4` is unset, `httpPortV4` is assigned its value. After `SetDefaults` both always agree. No warning is emitted. New configs must use `httpPortV4`. [`common/defaults.go:L652-661`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L652-L661) | | `server.grpcEnabled` | `*bool` | `false` | Enables gRPC. With default port derivation, gRPC shares the HTTP v4 port (in-handler mux + h2c). [`common/defaults.go:L669-671`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L669-L671) | | `server.grpcHostV4` | `*string` | copy of `httpHostV4` | [`common/defaults.go:L672-675`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L672-L675) | | `server.grpcPortV4` | `*int` | copy of `httpPortV4` | Equal to HTTP by default — triggers port sharing. Set a different value for a standalone gRPC server. [`common/defaults.go:L676-679`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L676-L679) | | `server.grpcHostV6` | `*string` | copy of `httpHostV6` | No IPv6 port-sharing logic exists. [`common/defaults.go:L680-683`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L680-L683) | | `server.grpcPortV6` | `*int` | copy of `httpPortV6` | [`common/defaults.go:L684-687`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L684-L687) | | `server.grpcMaxRecvMsgSize` | `*int` | `104857600` (100 MiB) | gRPC max receive message size. [`common/defaults.go:L688-690`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L688-L690) | | `server.grpcMaxSendMsgSize` | `*int` | `104857600` (100 MiB) | gRPC max send message size. [`common/defaults.go:L691-693`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L691-L693) | | `server.maxTimeout` | `*Duration` | `150s` | Global per-HTTP-request deadline. **Required non-zero** — validation fails with "server.maxTimeout is required" if absent or zero. Bare integer YAML values are milliseconds: `maxTimeout: 150` = 150 ms. [`common/defaults.go:L694-697`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L694-L697) | | `server.readTimeout` | `*Duration` | `30s` | `http.Server.ReadTimeout` — covers reading headers and body. [`common/defaults.go:L698-701`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L698-L701) | | `server.writeTimeout` | `*Duration` | `120s` | `http.Server.WriteTimeout` — covers writing the response. The entire response is buffered by `TimeoutHandler` before reaching the socket, so this only matters at final flush. [`common/defaults.go:L702-705`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L702-L705) | | `server.enableGzip` | `*bool` | `true` | Wraps handler in `gzipHandler` for response compression. Inbound gzip is always accepted regardless of this flag. [`common/defaults.go:L706-708`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L706-L708) | | `server.tls.enabled` | `bool` | `false` | When true, both listeners use `ListenAndServeTLS` with TLS 1.2 minimum; gRPC also uses TLS. Disables cleartext HTTP/2 (h2c) on both listeners; HTTP/2 is then negotiated via ALPN. [`erpc/http_server.go:L179-192`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L179-L192) | | `server.tls.certFile` | `string` | `""` | PEM cert path. Load failure → "failed to load TLS certificate and key". | | `server.tls.keyFile` | `string` | `""` | PEM key path. | | `server.tls.caFile` | `string` | `""` | When set, enables **mandatory mTLS**: `ClientAuth = RequireAndVerifyClientCert`. All clients must present a valid cert. Setting this field alone is sufficient — no other change needed. [`erpc/http_server.go:L1621-1633`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1621-L1633) | | `server.tls.insecureSkipVerify` | `bool` | `false` | **No effect on inbound TLS.** Go's TLS stack ignores this in server mode. Inbound cert verification is controlled only by `caFile`. This field only matters when the same struct is reused for outbound connections (Redis, tracing exporters). [`erpc/http_server.go:L1635`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1635) | | `server.aliasing.rules` | `[]*AliasingRuleConfig` | `nil` (auto-injected when zero projects) | Evaluated per request against `Host` (port stripped) in order; first wildcard match wins. [`erpc/http_server.go:L232-257`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L232-L257) | | `server.aliasing.rules[].matchDomain` | `string` | — | Wildcard/boolean pattern (`*`, `\|`, `&`, `!`, parens) matched against the request host. [`common/matcher.go:L34-47`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L34-L47) | | `server.aliasing.rules[].serveProject` | `string` | `""` | Pre-selected project ID. | | `server.aliasing.rules[].serveArchitecture` | `string` | `""` | Pre-selected architecture. Without `serveProject`, requires project in the URL path. Combining with `serveChain` but without `serveProject` is always `ErrInvalidUrlPath`. | | `server.aliasing.rules[].serveChain` | `string` | `""` | Pre-selected chainId. Combining `serveProject` + `serveChain` without `serveArchitecture` is rejected at request time. | | `server.waitBeforeShutdown` | `*Duration` | `10s` | Sleep after app-ctx cancel before calling `http.Server.Shutdown`. Lets readiness probes fail so the LB drains traffic first. Keep-alives are already off during this window, so pooled clients migrate. [`common/defaults.go:L865-868`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L865-L868) | | `server.waitAfterShutdown` | `*Duration` | `10s` | Sleep in `Init` AFTER the HTTP drain (`Shutdown`, up to 30s) has finished, before process exit. Lets telemetry exporters flush. It is not a cap on total shutdown time. [`common/defaults.go:L869-872`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L869-L872) | | `server.includeErrorDetails` | `*bool` | `true` | When true, error responses include `error.data` = full original error object, except for `eth_call` (clients expect string revert data). Many early/client-side error paths force `true` regardless of this flag. [`common/defaults.go:L717-719`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L717-L719) | | `server.trustedIPForwarders` | `[]string` | `["127.0.0.1/8", "::1/128"]` | IPs/CIDRs of proxies whose forwarding headers are trusted. Invalid entries are warned and ignored at runtime. [`common/defaults.go:L725-729`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L725-L729) | | `server.trustedIPHeaders` | `[]string` | `[]` (none trusted by default) | Header names parsed XFF-style for real client IP, only when the direct peer is a trusted forwarder. RFC 7239 `Forwarded` is not supported. [`common/defaults.go:L730-733`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L730-L733) | | `server.responseHeaders` | `map[string]string` | `nil` | Static headers added to every response. Values are env-expanded once at startup (`${VAR}` and `$VAR`). **Footgun:** headers whose value expands to empty string are silently dropped with only a Debug log — no warning, no error. [`erpc/http_server.go:L135-148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148) | | `server.maxRequestBodySize` | `*int64` | unset (`0` and unset both mean no limit) | Maximum HTTP request body in bytes, counted **after** gzip decompression, so a small compressed body that inflates past the limit is refused too. eRPC stops reading one byte past the limit and answers HTTP 413 with `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"request body exceeds the limit of bytes (maxRequestBodySize)"}}`; no request in the body runs and no upstream is called. Applies to every architecture (Solana included: unlike a malformed body, which Solana gets at 200, this is a transport limit). Negative is a config error. WebSocket frames are not covered. Not to be confused with `networks[].maxClientBatchSize`, which counts batch elements. [`erpc/http_server.go:L509-532`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L509-L532) [`common/validation.go:L97-99`](https://github.com/erpc/erpc/blob/main/common/validation.go#L97-L99) | | `server.executionHeaders` | `*ExecutionHeadersMode` | `"all"` | `"all"` = counters + metadata + per-attempt `X-ERPC-Upstreams` log; `"summary"` = counters + metadata; `"off"` = no `X-ERPC-*` diagnostic headers. Batch responses get one aggregated set under the same mode. [`common/defaults.go:L720-723`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L720-L723) | | `server.costHeaders` | `*bool` | `false` ([`common/defaults.go:L727-729`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L727-L729)) | Opt-in cost/billing headers on single and batch responses: `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`. Pricing itself is **vendor-owned** (`CreditUnitsProvider.CreditUnits(req, upstreamCfg)` — nothing hard-coded in the eRPC layer): vendors ship their public tables, overridable per method via `providers[].settings.creditUnits` (or `upstreams[*].creditUnits`); vendors without pricing cost a flat 1 credit per request. WebSocket connections whose upgrade request sends `X-ERPC-Cost-Frames: 1` get the same headers as a block prefixed to every message ([cost frames](/operation/websocket.llms.txt#cost-frames)). [`erpc/http_server.go:L1434-1552`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1434-L1552) | | `healthCheck.mode` | `HealthCheckMode` | `"networks"` | `"simple"` = plain `OK` text; `"networks"` = per-network JSON; `"verbose"` = full JSON. [`erpc/healthcheck.go:L337-396`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L337-L396) | | `healthCheck.auth` | `*AuthConfig` | `nil` | When set, a dedicated auth registry guards healthcheck endpoints. [`erpc/http_server.go:L201-207`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L201-L207) | | `healthCheck.defaultEval` | `string` | `"any:initializedUpstreams"` | Default eval strategy when `?eval=` query param is absent. [`erpc/healthcheck.go:L106-112`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L106-L112) | | `projects[].cors.allowedOrigins` | `[]string` | `["*"]` | Wildcard-matched against `Origin` header. Configured per-project (and on admin) but enforced by the HTTP server. [`erpc/http_server.go:L1022-1033`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1022-L1033) | | `cors.allowedMethods` | `[]string` | `["GET","POST","OPTIONS"]` | Joined into `Access-Control-Allow-Methods`. [`erpc/http_server.go:L1055`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1055) | | `cors.allowedHeaders` | `[]string` | `["content-type","authorization","x-erpc-secret-token"]` | Joined into `Access-Control-Allow-Headers`. [`erpc/http_server.go:L1056`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1056) | | `cors.exposedHeaders` | `[]string` | `nil` | Joined into `Access-Control-Expose-Headers`. [`erpc/http_server.go:L1057`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1057) | | `cors.allowCredentials` | `*bool` | `false` | Emits `Access-Control-Allow-Credentials: true` only when true. [`erpc/http_server.go:L1059-1061`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1059-L1061) | | `cors.maxAge` | `int` | `3600` | Emits `Access-Control-Max-Age` when > 0. [`erpc/http_server.go:L1063-1065`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1063-L1065) | **Hardcoded constants (non-configurable):** - `IdleTimeout` = 300s on both servers - `MaxHeaderBytes` = 1 MiB — the only hard inbound size limit unless `server.maxRequestBodySize` is set - No request-body size limit by default — `util.ReadAll` copies until EOF; set `server.maxRequestBodySize` to bound it (counted after gzip decompression, HTTP 413 past it). Unset, the effective limits are `readTimeout` and process memory - Graceful shutdown budget = 30s - Response compression threshold = 1024 bytes of cumulative body - TLS `MinVersion` = TLS 1.2 ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Public edge gateway behind an Anycast load balancer.** Many PaaS proxies inject the real client IP into a platform header (e.g. `Fly-Client-IP`, `CF-Connecting-IP`); the RFC-1918 trusted-forwarder CIDRs cover the platform mesh. `includeErrorDetails: false` strips internal stack traces from public responses. `waitBeforeShutdown: 30s` covers a couple of LB health-check intervals so rolling deploys drain fully before shutdown: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: # platform machines typically sit in RFC-1918 space; trust private CIDRs trustedIPForwarders: - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 # your platform injects the real client IP here — prefer it over spoofable X-Forwarded-For trustedIPHeaders: - CF-Connecting-IP # strip internal error details from public 5xx responses includeErrorDetails: false # 30s covers a couple of LB health-check intervals before Shutdown is called waitBeforeShutdown: 30s # keep the process alive long enough for telemetry exporters to flush waitAfterShutdown: 30s responseHeaders: # expose which region handled this request — useful for latency debugging X-ERPC-Region: \${REGION} X-ERPC-Machine: \${MACHINE_ID} ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { // platform machines typically sit in RFC-1918 space; trust private CIDRs trustedIPForwarders: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], // your platform injects the real client IP here — prefer it over spoofable X-Forwarded-For trustedIPHeaders: ["CF-Connecting-IP"], // strip internal error details from public 5xx responses includeErrorDetails: false, // 30s covers a couple of LB health-check intervals before Shutdown is called waitBeforeShutdown: "30s", // keep the process alive long enough for telemetry exporters to flush waitAfterShutdown: "30s", responseHeaders: { // expose which region handled this request — useful for latency debugging "X-ERPC-Region": "\${REGION}", "X-ERPC-Machine": "\${MACHINE_ID}", }, }, }); ``` **2. Internal Kubernetes deployment with gRPC shared on the HTTP port.** Internal indexing fleets enable gRPC so indexer workers can use the gRPC connector without a separate endpoint. The default port derivation (`grpcPortV4` = `httpPortV4`) activates the in-process h2c mux — no separate `grpcPortV4` needed. Note that gRPC traffic on the shared port bypasses `TimeoutHandler` and gzip: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: # gRPC shares port 4000 via the h2c in-process mux # (grpcPortV4 defaults to httpPortV4 — no explicit value needed) grpcEnabled: true # 30s matches two readiness-probe intervals in most K8s LB configs waitBeforeShutdown: 30s waitAfterShutdown: 30s ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { // gRPC shares port 4000 via the h2c in-process mux // (grpcPortV4 defaults to httpPortV4 — no explicit value needed) grpcEnabled: true, // 30s matches two readiness-probe intervals in most K8s LB configs waitBeforeShutdown: "30s", waitAfterShutdown: "30s", }, }); ``` **3. Standalone gRPC on a dedicated port (when TimeoutHandler must cover all traffic).** When `grpcPortV4` differs from `httpPortV4`, eRPC starts a fully independent gRPC server instead of muxing. HTTP requests flow through `TimeoutHandler` and gzip as normal; gRPC has its own listener. Use this when you need `maxTimeout` enforcement on HTTP while still serving gRPC: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: httpPortV4: 4000 grpcEnabled: true # different port → standalone gRPC server, HTTP keeps its TimeoutHandler grpcPortV4: 4010 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { httpPortV4: 4000, grpcEnabled: true, // different port → standalone gRPC server, HTTP keeps its TimeoutHandler grpcPortV4: 4010, }, }); ``` **4. Mutual TLS for a private RPC gateway.** Adding `caFile` is the only field needed to flip mTLS on — it sets `ClientAuth = RequireAndVerifyClientCert` automatically. All clients must present a valid certificate signed by that CA. `waitBeforeShutdown: 20s` is two readiness-probe intervals for an NLB (10s probe interval × 2): **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: httpPortV4: 4443 tls: enabled: true certFile: /etc/erpc/tls.crt keyFile: /etc/erpc/tls.key # setting caFile alone enables mTLS — no other field required caFile: /etc/erpc/ca.crt # NLB probe interval is typically 10s; 2× = full drain window waitBeforeShutdown: 20s waitAfterShutdown: 5s ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { httpPortV4: 4443, tls: { enabled: true, certFile: "/etc/erpc/tls.crt", keyFile: "/etc/erpc/tls.key", // setting caFile alone enables mTLS — no other field required caFile: "/etc/erpc/ca.crt", }, // NLB probe interval is typically 10s; 2× = full drain window waitBeforeShutdown: "20s", waitAfterShutdown: "5s", }, }); ``` **5. Domain-based aliasing for a multi-chain gateway.** Operators serving Ethereum mainnet and Arbitrum on separate subdomains can pre-route requests by `Host` header so callers use bare URLs like `https://eth.example.com`. Specific rules are placed before the wildcard catch-all — first match wins. Combining `serveProject` + `serveChain` without `serveArchitecture` is an error; all three must be present for fully resolved routing: **Config path:** `server.aliasing` **YAML — `erpc.yaml`:** ```yaml server: aliasing: rules: # specific rules must come before the wildcard — first match wins - matchDomain: "eth.example.com" serveProject: main serveArchitecture: evm serveChain: "1" - matchDomain: "arb.example.com" serveProject: main serveArchitecture: evm serveChain: "42161" # wildcard catch-all: project pre-selected, chain still from URL path - matchDomain: "*.example.com" serveProject: main ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ server: { aliasing: { rules: [ // specific rules must come before the wildcard — first match wins { matchDomain: "eth.example.com", serveProject: "main", serveArchitecture: "evm", serveChain: "1" }, { matchDomain: "arb.example.com", serveProject: "main", serveArchitecture: "evm", serveChain: "42161" }, // wildcard catch-all: project pre-selected, chain still from URL path { matchDomain: "*.example.com", serveProject: "main" }, ], }, }, }); ``` ### Request/response behavior **HTTP status mapping** (`determineResponseStatusCode` and `handleErrorResponse`, both switch on the same error code set): | Status | Conditions | |--------|------------| | 400 | `ErrInvalidUrlPath`, `ErrJsonRpcRequestUnmarshal`, `ErrInvalidRequest` | | 401 | `ErrAuthUnauthorized`, `ErrEndpointUnauthorized` | | 404 | `ErrProjectNotFound`, `ErrNetworkNotFound`, `ErrNetworkNotSupported` | | 429 | `ErrAuthRateLimitRuleExceeded`, `ErrProjectRateLimitRuleExceeded`, `ErrNetworkRateLimitRuleExceeded`, `ErrEndpointCapacityExceeded` | | 200 | everything else; JSON-RPC application errors always stay 200 | Note: `writeFatalError` (panics, write failures) and the timeout/cancel paths force HTTP 200 for POST regardless of error type. Source: [`erpc/http_server.go:L1280-1317`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1280-L1317) **Error response shapes:** - Standard JSON-RPC single error: `{"jsonrpc":"","id":,"error":{"code":,"message":""[,"data":]}}` — `includeErrorDetails` adds `error.data` except on `eth_call` - Timeout body: `{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"http request handling timeout"}}` at HTTP 200 (POST) / 504 (other) [[`erpc/http_timeout.go:L107-122`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L107-L122)] - Client-cancel body: `{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"request cancelled by client"}}` at HTTP 200 (POST) / 503 (other) - Body over `server.maxRequestBodySize`: `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"request body exceeds the limit of bytes (maxRequestBodySize)"}}` at HTTP 413, every architecture [[`erpc/http_server.go:L1793-1796`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1793-L1796)] - Fatal-path body (panic/write failure): `{"jsonrpc":"2.0","error":{"code":-32603,"message":...}}` — **no `id` field** - Batch responses are always HTTP 200; each element is written as a streaming JSON array. They carry ONE aggregated `X-ERPC-*` diagnostic header set (counters summed, `X-ERPC-Cache` gains `PARTIAL:`, slowest-sub-call duration, trace capped at 50 segments; no single-winner `X-ERPC-Upstream`) under the same `executionHeaders` mode — see [directives](/operation/directives.llms.txt). Source: [`erpc/http_server.go:L706-712`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L706-L712) **Diagnostic response headers** (per-response set on singles via `setResponseHeaders`; aggregated set on batches via `writeBatchExecHeaders`): - `X-ERPC-Version`, `X-ERPC-Commit` — build-identity headers (ldflags vars, defaults `"dev"` and `"none"`); emitted unless `executionHeaders: "off"`. [`erpc/http_server.go:L275-278`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L275-L278) - `X-ERPC-Attempts`, `X-ERPC-Upstream-Attempts/-Retries/-Hedges`, `X-ERPC-Network-Attempts/-Retries/-Hedges` — counters, **zero-filled on early errors** (not omitted; only `mode: off` removes them). [`erpc/http_server.go:L1149-1166`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1149-L1166) - `X-ERPC-Cache-Attempts/-Retries/-Hedges` — emitted only when the cache scope was exercised. [`erpc/http_server.go:L1170-1174`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1170-L1174) - `X-ERPC-Consensus-Slots`, `X-ERPC-Consensus-Disputes`, `X-ERPC-Consensus-Low-Participants` — emitted only when consensus was exercised and the count is > 0. [`erpc/http_server.go:L1175-1183`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1175-L1183) - `X-ERPC-Cache: HIT|MISS`, `X-ERPC-Upstream`, `X-ERPC-Duration` — response metadata - `X-ERPC-Upstreams` (mode `all` only): per-attempt participation log in the form `=::ms[:won]` - `traceparent` (+ `tracestate`) — injected when tracing is enabled. [`common/tracing_util.go:L58-65`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L58-L65) **Request headers with server-level effects:** - `Host` — aliasing match (port stripped) - `Content-Encoding: gzip` — inbound body decompression (always, regardless of `enableGzip`) - `Accept-Encoding: gzip` — response compression eligibility - `Content-Type: application/grpc` over HTTP/2 — gRPC mux on shared port (bypasses `TimeoutHandler` and gzip) - `Origin` — CORS evaluation; absent Origin bypasses CORS entirely - `X-ERPC-Force-Trace: true|1|yes` or `?force-trace=true|1|yes` — force-sample the OTel trace for this request. [`common/tracing_util.go:L106-119`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L106-L119) - `traceparent` / `tracestate` — W3C trace-context extraction on ingress. [`common/tracing_util.go:L67-73`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L67-L73) - `?eval=` — healthcheck strategy override (bypasses `healthCheck.defaultEval`). [`erpc/healthcheck.go:L106-112`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L106-L112) - Auth headers: `?token=` (deprecated), `X-ERPC-Secret-Token`, `Authorization: Basic|Bearer`, `?secret=`, `?jwt=`, `?signature=&message=`, `X-Siwe-Message`/`X-Siwe-Signature`. [`auth/http.go:L13`](https://github.com/erpc/erpc/blob/main/auth/http.go#L13) ### Best practices - Set `maxTimeout` as a Go duration string (`"30s"`), never a bare integer. `maxTimeout: 150` means 150 milliseconds, not 150 seconds — this is the most common misconfiguration footgun. - Size `maxTimeout` to be greater than your largest network-level `failsafe.timeout` plus total retry overhead, or retries will be cut short by the server ceiling before they complete. See [Timeout](/config/failsafe/timeout.llms.txt). - In production behind an LB, set `waitBeforeShutdown` to at least two readiness-probe intervals (often 20s). The default `10s` is too short for many Kubernetes setups. - **Never omit `trustedIPForwarders`** when running behind a proxy. Without it, every request appears to come from the LB IP, breaking per-IP rate limits, auth network strategies, and client identity logging. - Setting `tls.caFile` enables mTLS implicitly and immediately — all clients must then present a certificate. Verify this is intended before adding the field in production. - Keep `executionHeaders: "summary"` or `"off"` for production traffic if response size is sensitive — `"all"` mode emits a verbose `X-ERPC-Upstreams` header that grows linearly with the number of upstream attempts. - Use `responseHeaders` for static CORS or security headers, but pin the env vars at deploy time. Values that expand to empty are silently dropped with no error, so a missing env var makes the header vanish invisibly. ### Edge cases & gotchas 1. **`maxTimeout` bare integer is milliseconds.** `maxTimeout: 150` = 150 ms, not 150 s. Always use a duration string like `"150s"`. Source: [`common/duration.go:L20-31`](https://github.com/erpc/erpc/blob/main/common/duration.go#L20-L31) 2. **`grpcEnabled: true` with default ports silently shares the HTTP v4 port.** gRPC traffic bypasses `maxTimeout` and gzip. Source: [`erpc/http_server.go:L161-177`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L161-L177) 3. **mTLS is implicit.** Setting `tls.caFile` flips `ClientAuth = RequireAndVerifyClientCert` — all clients must present certs. No other field is needed. Source: [`erpc/http_server.go:L1621-1633`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1621-L1633) 4. **`tls.insecureSkipVerify` does nothing for inbound connections.** It is a client-dialing flag only; Go's TLS server ignores it. Inbound cert verification is controlled by `caFile` alone. Source: [`erpc/http_server.go:L1635`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1635) 5. **`responseHeaders` env vars that expand to empty are silently dropped.** No warning is emitted — only a Debug log. A missing env var in production silently removes the header from all responses. Source: [`erpc/http_server.go:L135-148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148) 6. **`listenV6` has no default.** IPv6 is OFF unless explicitly set to `true`; it is never auto-enabled. Source: [`common/defaults.go:L640-650`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L640-L650) 7. **`httpPort` (deprecated) is silently migrated.** No warning is emitted. After `SetDefaults`, `httpPort` always equals `httpPortV4`. New configs must use `httpPortV4`. Source: [`common/defaults.go:L652-661`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L652-L661) 8. **No request-body size limit unless `server.maxRequestBodySize` is set.** By default there is no bound; a multi-GB body (or a small gzip body that inflates to GBs) is fully read into memory, and only `readTimeout` and process memory provide back-pressure. Set `maxRequestBodySize` to cap the decompressed bytes (HTTP 413, zero upstream calls). Source: [`erpc/http_server.go:L509-532`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L509-L532) 9. **POST requests can still get non-200 status codes.** HTTP 400/401/404/413/429 mappings apply to POST; only the fatal-writer and timeout/cancel paths force 200-for-POST. Source: [`erpc/http_server.go:L1470-1491`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1470-L1491) 10. **Whole responses are buffered before hitting the socket.** Large responses consume RAM; pooled buffers above 256 KiB are discarded to GC. `writeTimeout` only matters at the final socket copy. Source: [`erpc/http_timeout.go:L43-48`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L43-L48) 11. **Disallowed CORS origins are not blocked for non-OPTIONS requests.** The request proceeds without `Access-Control-*` headers; the browser enforces the block. Source: [`erpc/http_server.go:L1036-1051`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1036-L1051) 12. **Zero-project configs self-alias.** A default `main` project and `matchDomain: "*"` rule are injected so `/evm/1` works without a project segment. Source: [`common/defaults.go:L100-111`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L100-L111) 13. **`serveProject` + `serveChain` without `serveArchitecture` is always an error.** Source: [`erpc/http_server.go:L985-990`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L985-L990) 14. **Full request bodies are logged at Info level by default.** Sensitive params (private keys, tokens in JSON-RPC args) appear in logs. Source: [`erpc/http_server.go:L398-402`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L398-L402) 15. **`X-ERPC-Attempts` excludes NetworkAttempts** to avoid double-counting rotations. Source: [`erpc/http_server.go:L1151-1157`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1151-L1157) 16. **Batch detection is byte-exact.** Leading whitespace before `[` makes the body parse as a single (invalid) request. Source: [`erpc/http_server.go:L405`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L405) 17. **Any non-POST/non-OPTIONS request becomes a healthcheck**, including `GET /myproject/evm/1`. Source: [`erpc/http_server.go:L1001-1003`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1001-L1003) 18. **RFC 7239 `Forwarded` is dead code** — only headers named in `trustedIPHeaders` are consulted, parsed XFF-style. Source: [`erpc/http_server.go:L1856-1881`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1856-L1881) 19. **CORS metric label mismatch.** The label named `project` is populated with the URL path, not the project ID. Source: [`erpc/http_server.go:L1020`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1020) 20. **`serveArchitecture`-only aliasing requires a project in the URL path.** Combining `serveArchitecture` + `serveChain` without `serveProject` is always `ErrInvalidUrlPath`. Source: [`erpc/http_server.go:L963-990`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L963-L990) 21. **OPTIONS to a project without CORS config falls through to normal request handling.** The OPTIONS early-return lives inside the `CORS != nil` branch; a project with no `cors:` block sends an empty body OPTIONS through the full JSON-RPC path, returning a JSON-RPC error (not a 204). Source: [`erpc/http_server.go:L343-347`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L343-L347) 22. **An explicit `Flush()` below 1024 bytes commits to uncompressed.** The gzip writer buffers sub-threshold body bytes; a handler that flushes before reaching 1024 cumulative bytes forces passthrough for the rest of the response, however large. The JSON-RPC path does not flush mid-body, so this only affects streaming handlers. Source: [`erpc/http_server.go:L2346-2360`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L2346-L2360) 23. **Done/canceled race silently drops the response.** If the inner handler finishes but the request context has already errored (e.g. a race between handler return and deadline), nothing is written to the socket. The timeout layer has already responded. Source: [`erpc/http_timeout.go:L72-80`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L72-L80) 24. **Counter headers are zero-filled on early errors, not omitted.** Even URL-parse or project-lookup failures emit `X-ERPC-Attempts: 0`, `X-ERPC-Upstream-Attempts: 0`, etc., because `writeCounterHeaders` runs against a nil-safe snapshot. Only `executionHeaders: "off"` suppresses them entirely. Source: [`erpc/http_server.go:L1149-1166`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1149-L1166) 25. **`ErrUnknown` fallback body is not JSON-RPC shaped.** When `processErrorBody` receives an error that survives all unwrapping as neither a `*common.BaseError` nor `common.StandardError`, it produces `{"code":"ErrUnknown","message":"unexpected server error","cause":{...}}` — a struct dump, not `{"jsonrpc":"2.0","error":{...}}`. Clients parsing `response.error.code` as an integer will fail; detection must branch on whether the outer object has a `code` string key vs an `error` object key. Source: [`erpc/http_server.go:L1450-1454`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1450-L1454) 26. **`ErrorStatusCode()` on error types is dead code.** Every error type in `common/errors.go` implements `ErrorStatusCode() int`, but there are no call sites. The wire HTTP status is determined exclusively by the two switch blocks in `determineResponseStatusCode` and `handleErrorResponse` using `common.HasErrorCode`. Reading an error type's `ErrorStatusCode()` to infer the wire status gives wrong answers for many types (e.g. `ErrNetworkInitializing` → 503, `ErrUpstreamRateLimitRuleExceeded` → 429 per the method, but neither appears in the switch). Source: [`erpc/http_server.go:L1280-1317`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1280-L1317) 27. **Sonic encoder writes a trailing newline and disables HTML escaping globally.** The early-error path uses `encoder.Encode` (trailing `\n`) and sonic's HTML escaping is off (`common/sonic.go`). JSON field values such as URLs are not HTML-escaped in error bodies. Source: [`erpc/http_server.go:L229-230`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L229-L230) 28. **`waitAfterShutdown` runs after the drain, not alongside it.** The process lives up to `waitBeforeShutdown + 30s + waitAfterShutdown` after SIGTERM (50s with defaults). Your orchestrator's kill deadline (e.g. Kubernetes `terminationGracePeriodSeconds`, ECS `stopTimeout`) must exceed it, or SIGKILL lands mid-drain and in-flight requests die. If you sized `waitAfterShutdown` to cover the drain itself, lower it: it now only needs to cover exporter flushes. Source: [`erpc/init.go:L221-236`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L221-L236) 29. **h2c is prior-knowledge only.** HTTP/1.1 `Upgrade: h2c` is not honored; such a request is served over HTTP/1.1. Clients must open cleartext HTTP/2 with the connection preface (e.g. `http2_prior_knowledge`). Source: [`erpc/http_server.go:L179-192`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L179-L192) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_unexpected_panic_total` | counter | `scope`, `extra`, `error` | Scopes: `request-handler`, `final-error-writer`, `top-level-handler`, `timeout-handler`, `validate-pattern` | | `erpc_cors_requests_total` | counter | `project` (= URL path), `origin` | Every request carrying an `Origin` header | | `erpc_cors_preflight_requests_total` | counter | `project`, `origin` | Allowed-origin OPTIONS preflight requests | | `erpc_cors_disallowed_origin_total` | counter | `project`, `origin` | Origin matched no allowlist entry | **Trace spans:** `Http.ReceivedRequest` (SpanKind=server; attrs `http.method`, `http.url`, `http.scheme`, `http.user_agent`); `Request.Handle` per sub-request; detail spans `Http.ReadBody`, `Http.ParseRequests`, `HttpServer.WriteResponse`; `w3c traceparent`/`tracestate` extraction on ingress, injection on egress. **Note:** there is no generic `http_requests_total`-style server metric; request accounting happens at the network/upstream layers. **Notable log lines:** - `"received http request"` at **Info** — includes the full raw JSON body; sensitive params appear at default log level - `"entering draining mode → healthcheck will fail"` on SIGTERM - `"starting IPv4/IPv6 HTTP server on "` at listen - `"TLS enabled for IPv4/IPv6 HTTP server"` when TLS is active - `"http server forced to shutdown"` / `"http server stopped"` on graceful drain completion - `"custom response header configured"` / `"custom response header skipped (empty value after env expansion)"` for `responseHeaders` - `"invalid CIDR/IP in trusted forwarders; ignoring"` for malformed forwarder entries - `"CORS request from disallowed origin..."` at Debug when an origin is rejected ### Source code entry points - [`erpc/http_server.go:L1-L230`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1-L230) — `NewHttpServer`: handler chain assembly, gzip/timeout wrapping, gRPC mux, IPv4/IPv6 server construction, `responseHeaders` env expansion, trusted forwarder parsing - [`common/defaults.go:L640-L733`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L640-L733) — `ServerConfig.SetDefaults`: all defaults including port derivation, deprecated `httpPort` migration, zero-project aliasing injection - [`erpc/http_timeout.go:L20-L143`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L20-L143) — custom `TimeoutHandler`: buffered response, timeout/cancel body shapes, panic propagation - [`erpc/http_server.go:L1537-L1637`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1537-L1637) — TLS config construction, `ListenAndServeTLS`, mTLS `ClientAuth` assignment - [`erpc/http_server.go:L1782-L1905`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1782-L1905) — `resolveRealClientIP`: trusted forwarder check, XFF right-trim, fallback to peer IP - [`erpc/http_server.go:L810-L1006`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L810-L1006) — `parseUrlPath`: full aliasing × path-segment case matrix - [`common/validation.go:L70-L109`](https://github.com/erpc/erpc/blob/main/common/validation.go#L70-L109) — `ServerConfig.Validate`: listen host/port pairing, `maxTimeout` required, forwarder IP/CIDR syntax - [`erpc/http_server_test.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server_test.go) — path parsing matrix, CORS, timeouts, aliasing fixtures ### Related pages - [Timeout](/config/failsafe/timeout.llms.txt) — per-network timeout that must stay below `server.maxTimeout` or the server ceiling fires first. - [Rate limiters](/config/rate-limiters.llms.txt) — per-IP rate limits depend on accurate client IP, which requires correct `trustedIPForwarders` + `trustedIPHeaders`. - [Auth](/config/auth.llms.txt) — authentication strategies consume the resolved client IP from this layer. - [URL structure & aliasing](/operation/url.llms.txt) — full path-parsing logic and all valid segment combinations for domain aliasing. - [Deployment overview](/deployment/self-hosted.llms.txt) — where `server:` fits in a production Kubernetes or Docker deployment. --- --- # Hosted cloud > Source: https://docs.erpc.cloud/deployment/cloud > Managed eRPC instances with regional cache storage — no infrastructure setup required. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Hosted cloud Skip the infrastructure work and get a fully managed eRPC instance with cache storage in your preferred region. Compute and storage are provisioned in minutes; you own the config and we handle the rest. Available regions include EU (close to AWS `eu-central-1` / Hetzner EU) and US (close to AWS `us-east-1` / Hetzner US). ## Pricing | Feature | Unit cost / month | |---|---| | Compute instance | $50 per 2 vCPU + 4 GB RAM | | Cache data storage | $0.30 per 1 GB | **Example:** a LiFi project on Arbitrum caching 10 M transactions and traces plus 200 M blocks uses ~400 GB of storage: - 1 instance: $50 / mo - 400 GB cache: $120 / mo - **Total: ~$170 / mo** [Contact us on Telegram](https://t.me/erpc_cloud) to bring up a cloud instance in minutes. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure eRPC on a hosted cloud instance** ```text I have a managed eRPC cloud instance (erpc.cloud) and want to configure it correctly. The config schema is the same as self-hosted — help me write or review my eRPC config for my use case. For deployment details follow the child-page references: https://docs.erpc.cloud/deployment/docker.llms.txt and https://docs.erpc.cloud/deployment/kubernetes.llms.txt. Cloud page: https://docs.erpc.cloud/deployment/cloud.llms.txt ``` **Prompt Example #2: estimate cloud cost for my caching workload** ```text Help me estimate the monthly cost of a hosted eRPC cloud instance for my workload: I need to cache RPC responses for a high-traffic dApp and want to understand the compute and storage pricing. Then help me write an eRPC config that minimises storage use for my specific chains. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/cloud.llms.txt ``` **Prompt Example #3: harden config before going to production on cloud** ```text I am about to point production traffic at my hosted eRPC cloud instance. Review my eRPC config and apply the production hardening checklist — auth, rate limits, CORS, GOMEMLIMIT guidance, and any footguns in my current config. Start from this page's reference at https://docs.erpc.cloud/deployment/cloud.llms.txt, then follow the production checklist at https://docs.erpc.cloud/operation/production.llms.txt. Work with my existing eRPC config. ``` --- ### Hosted cloud — agent notes This page describes the commercial managed offering, not the open-source software. For self-hosted deployment details see: - [Docker](/deployment/docker.llms.txt) — image, compose, flags. - [Kubernetes](/deployment/kubernetes.llms.txt) — manifests, probes, resources. - [Production checklist](/operation/production.llms.txt) — hardening grounded in code behavior. Configuration on hosted instances uses the same `erpc.yaml` / `erpc.ts` schema documented across this site; nothing in the config surface is cloud-specific. --- --- # Docker > Source: https://docs.erpc.cloud/deployment/docker > A 30 MB distroless image, one mount, two ports — eRPC runs anywhere Docker runs, with a pre-wired Grafana dashboard ready the moment you start. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Docker Pull, mount your config, and you're live. eRPC's official image is distroless and ~30 MB — nothing but the proxy binary and TypeScript config support. Expose two ports and traffic flows immediately; an optional compose stack brings up Prometheus and Grafana with 80+ pre-built panels in the same command. ```bash docker run -v $(pwd)/erpc.yaml:/erpc.yaml \ -p 4000:4000 -p 4001:4001 \ ghcr.io/erpc/erpc:latest ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: get eRPC running in Docker** ```text Deploy eRPC using Docker for the first time. Mount my config from my eRPC config, expose the RPC and metrics ports, set GOMEMLIMIT correctly for the container, and pin the image to a specific release tag rather than :latest. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/deployment/docker.llms.txt ``` **Prompt Example #2: spin up local dev stack with Grafana** ```text Set up a full local dev environment with eRPC, Redis, Prometheus, and Grafana using docker-compose so I can see the 80+ dashboard panels. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/docker.llms.txt ``` **Prompt Example #3: debug a crashing container** ```text My eRPC Docker container is restarting unexpectedly in production. Help me diagnose whether it is an OOM kill (missing GOMEMLIMIT), a bad config mount, or a graceful shutdown issue. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/docker.llms.txt ``` **Prompt Example #4: profile memory or CPU in staging** ```text Enable the pprof profiling build of eRPC in my staging Docker container so I can capture heap and CPU profiles to investigate high memory usage. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/docker.llms.txt ``` --- ### Docker — full agent reference ### How it works **Image structure.** The Dockerfile uses six named build stages: `go-builder` compiles both `erpc-server` (production) and `erpc-server-pprof` (pprof build tag); `ts-core` installs shared pnpm dependencies on Node 20 alpine; `ts-dev` and `ts-prod` extend `ts-core` for their respective build targets; `symlink` creates a `/root/erpc-server → /erpc-server` compatibility symlink; `final` copies only the two Go binaries, the symlink, and compiled TypeScript files into a `gcr.io/distroless/static-debian12:nonroot` base. CGO is disabled and `-ldflags="-w -s"` strips debug info. The default `CMD` is `/erpc-server`. **Ports.** The image exposes three ports: - `4000` — JSON-RPC HTTP ingress (default `server.httpPortV4`) - `4001` — Prometheus metrics (`/metrics`) - `6060` — pprof (only functional in the `erpc-server-pprof` binary) **Config discovery.** At startup eRPC searches for a config file in this order: `--config` flag → positional arg → `./erpc.yaml`, `./erpc.yml`, `./erpc.ts`, `./erpc.js`, then the same paths under `/` and `/root/`. The simplest production mount is `-v $(pwd)/erpc.yaml:/erpc.yaml`. **Compose stack.** The repo's `docker-compose.yml` defines a `monitoring` service (Grafana on `:3000`, Prometheus on `:9090`) and a `redis` service (`redis:latest`, port `6379:6379`, restart always, on the `erpc` bridge network). The eRPC container entry is commented out by default (references `ghcr.io/erpc/erpc:main`) — operators add it back with a volume-mounted config. Additional optional services (Jaeger with OTLP gRPC/HTTP and UI, PostgreSQL, ScyllaDB in Alternator mode) are also present as commented-out blocks. Point monitoring at a running eRPC instance: ```bash SERVICE_ENDPOINT=host.docker.internal SERVICE_PORT=4001 docker compose up monitoring ``` `make down` passes `--volumes`, which destroys `prometheus_data` and `grafana_data` named volumes; use `docker compose down` (no `--volumes`) to preserve monitoring history. **Distroless/nonroot implications.** The final image has no shell, no package manager, and no standard utilities. You cannot exec into it with a shell. Attaching debug tools or copying files at runtime requires a privileged ephemeral sidecar. All file paths must be absolute. If you mount a config that does not exist, the process exits cleanly (non-zero) — it does not hang. TypeScript configs (`erpc.ts`) are supported: the image includes compiled TypeScript SDK files and node_modules. Node itself is not present as a standalone binary, but the bundled runtime path invoked by eRPC for TS config evaluation does work. If you strip `node_modules` from the image, TypeScript configs fail silently and fall back to YAML. **Layer caching.** `go.mod` and `go.sum` are copied into the builder stage first and `go mod download` runs before the source copy, so dependency layers are cached across rebuilds ([`Dockerfile:L16-L21`](https://github.com/erpc/erpc/blob/main/Dockerfile#L16-L21)). The pnpm stages use `--mount=type=cache,id=pnpm,target=/pnpm/store` to avoid re-downloading npm packages across builds ([`Dockerfile:L51`](https://github.com/erpc/erpc/blob/main/Dockerfile#L51), [`L63`](https://github.com/erpc/erpc/blob/main/Dockerfile#L63)). **CLI subcommands.** The `erpc` binary supports three subcommands: - `erpc [config]` or `erpc start` — start the server - `erpc validate [--format json|md]` — parse config and run a validation report; exits non-zero on errors - `erpc dump [--format yaml|json]` — parse config, resolve effective selection policies, and dump to stdout **Monitoring container internals.** `monitoring/Dockerfile` pulls Prometheus `v3.9.1` and Grafana `12.3.3` (both pinned by digest) into an `ubuntu:22.10` base. The entrypoint substitutes `SERVICE_ENDPOINT` and `SERVICE_PORT` into `prometheus.yml` using `sed`, then starts both processes in the background and tails `/dev/null` to keep the container alive. If either process crashes, the container stays up but becomes non-functional. This design is intentional for local dev convenience; run separate Prometheus and Grafana containers in production. ### Config schema The deployment layer has no `erpc.yaml` fields. The following environment variables control the running process: | Variable | Effect | Source | |---|---|---| | `LOG_LEVEL` | Overrides `cfg.LogLevel`; parsed as zerolog level (`trace`/`debug`/`info`/`warn`/`error`) | [`cmd/erpc/main.go:L354-363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) | | `LOG_WRITER` | If `"console"` → human-readable zerolog output with `04:05.000ms` timestamps; default is JSON | [`cmd/erpc/main.go:L53-57`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L53-L57) | | `GOMEMLIMIT` | Go soft memory limit (e.g. `GOMEMLIMIT=2700MiB`). **Not set in any manifest** — operators must set manually. Rule of thumb: 90% of container memory limit. | n/a | | `GOGC` | Go GC target percentage. Lower values (25–50) keep heap smaller at slightly higher CPU cost. Default is Go runtime default (100). | n/a | | `SERVICE_ENDPOINT` | Monitoring container only — injected into Prometheus scrape target by `monitoring/scripts/entrypoint.sh`. Default target is `host.docker.internal:4001`. | [`monitoring/scripts/entrypoint.sh:L1`](https://github.com/erpc/erpc/blob/main/monitoring/scripts/entrypoint.sh#L1) | | `SERVICE_PORT` | Same as above. | [`monitoring/scripts/entrypoint.sh:L1`](https://github.com/erpc/erpc/blob/main/monitoring/scripts/entrypoint.sh#L1) | ### Worked examples **1. Minimal single-container run.** The simplest production-ready invocation: mount config, expose both ports, no compose required: ```bash docker run --restart=unless-stopped \ -v $(pwd)/erpc.yaml:/erpc.yaml \ -e GOMEMLIMIT=2700MiB \ -p 4000:4000 -p 4001:4001 \ ghcr.io/erpc/erpc:latest ``` Set `GOMEMLIMIT` to 90% of your container's memory allowance to prevent Go GC from allowing the heap to reach the hard OOM limit. **2. Full local dev stack with monitoring.** Spin up eRPC, Redis, Prometheus, and Grafana together. Add the eRPC service block back into `docker-compose.yml`, then: ```bash SERVICE_ENDPOINT=erpc SERVICE_PORT=4001 docker compose up ``` Open `http://localhost:3000` for Grafana (default credentials `admin`/`admin`). The dashboard auto-loads with 80+ panels. **3. Profiling build.** Override CMD to the pprof variant when debugging performance in a staging environment. The binary is always present in every image: ```bash docker run -v $(pwd)/erpc.yaml:/erpc.yaml \ -p 4000:4000 -p 4001:4001 -p 6060:6060 \ --entrypoint /erpc-server-pprof \ ghcr.io/erpc/erpc:latest ``` Access pprof endpoints at `http://localhost:6060/debug/pprof/`. **4. `make docker-run`.** The Makefile wraps the single-container run: it maps ports `4000:4000` and `4001:4001`, mounts `./erpc.yaml:/erpc.yaml`, and explicitly invokes `/erpc-server --config /erpc.yaml` rather than relying on the image's default CMD. Equivalent to: [`Makefile:L127-L129`](https://github.com/erpc/erpc/blob/main/Makefile#L127-L129) ```bash docker run -p 4000:4000 -p 4001:4001 \ -v ./erpc.yaml:/erpc.yaml \ ghcr.io/erpc/erpc:latest /erpc-server --config /erpc.yaml ``` **5. Pinned production image.** Never run `:latest` in production — pin a specific tag or SHA: ```bash docker run -v $(pwd)/erpc.yaml:/erpc.yaml \ -p 4000:4000 -p 4001:4001 \ ghcr.io/erpc/erpc:v0.0.x ``` ### Request/response behavior - Graceful shutdown: `SIGINT`/`SIGTERM` triggers `signal.NotifyContext`; the HTTP server drains in-flight requests, returns 503 on healthcheck, then calls `Shutdown`. [[`cmd/erpc/main.go:L72-74`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L72-L74)] - The `/healthcheck` endpoint returns 200 while healthy and 503 during drain — wire it to Docker's `HEALTHCHECK` instruction or a load-balancer probe. - `VERSION` and `COMMIT_SHA` build args are injected via `-X` ldflags into `common.ErpcVersion` and `common.ErpcCommitSha` at build time and surfaced in startup logs and the `/healthcheck` response body. [[`Dockerfile:L24-34`](https://github.com/erpc/erpc/blob/main/Dockerfile#L24-L34)] ### Best practices - **Always set `GOMEMLIMIT`** to 90% of the container's memory limit. Without it, Go's GC may allow the heap to reach the hard OOM limit, triggering a container restart rather than a managed GC cycle. - **Pin the image tag** to a specific release (e.g. `ghcr.io/erpc/erpc:v0.0.x`) rather than `:latest` for reproducible deploys. - **Expose port 4001** even if you're not using the monitoring stack yet — it's zero cost and unlocks observability later without a redeploy. - **Use `docker compose down` (without `--volumes`)** to stop the local stack; `make down` passes `--volumes` and destroys all Prometheus/Grafana state. - **Do not use the monitoring container in production.** Prometheus and Grafana share one process group — a crash in either is not independently restarted. Use separate containers for production monitoring. - **Mount a non-existent config → clean exit.** If the path you mount at `/erpc.yaml` doesn't exist, eRPC exits non-zero immediately — verify your bind-mount paths before starting. - **gRPC port needs explicit mapping.** The image exposes `4000`, `4001`, `6060`. If you configure a separate `server.grpcPortV4`, add `-p :` explicitly. ### Edge cases & gotchas 1. **No shell in distroless**: Cannot exec with a shell; debug tools require privileged sidecars. 2. **`make down` destroys volumes**: `Makefile:L114` passes `--volumes` — this drops `prometheus_data` and `grafana_data`. Use `docker compose down` (without `--volumes`) to preserve monitoring state. 3. **`GOMEMLIMIT` not set in any manifest**: With a 3 Gi container limit and no `GOMEMLIMIT`, Go's GC may allow the heap to approach 3 Gi before collecting, triggering container OOM. Set `GOMEMLIMIT=2700MiB` (90% of limit). 4. **pprof binary always present but never used by default**: `/erpc-server-pprof` exists in every image but the default `CMD` runs `/erpc-server`. To use profiling endpoints, override `CMD` to `/erpc-server-pprof` and expose port `6060`. 5. **`SERVICE_ENDPOINT` sed-based substitution**: If the value contains `/` or other sed-special characters, substitution breaks. Use a plain hostname or IP, not a URL with a path. 6. **Monitoring container is not HA**: Both Prometheus and Grafana run in one container via `tail -f /dev/null`; a crash in either is not detected and the container stays running. Not suitable for production. 7. **gRPC port not exposed by default**: The image exposes `4000`, `4001`, `6060`. If you configure a separate `server.grpcPortV4`, add `-p :` explicitly. 8. **`prometheus.yaml` at repo root is NOT the monitoring container's config**: It is the production Prometheus Operator config. The monitoring container uses `monitoring/prometheus/prometheus.yml`. They have different scrape configs and targets. ### Observability All eRPC metrics are emitted at port `4001` path `/metrics`. The monitoring container's Prometheus scrapes this endpoint at `scrape_interval: 10s` and `evaluation_interval: 10s`. The local Prometheus config (`monitoring/prometheus/prometheus.yml`) defines two scrape jobs: `prometheus` (self-scrape at `localhost:9090`) and `erpc` (dual targets: `host.docker.internal:4001` plus a placeholder replaced by `SERVICE_ENDPOINT`/`SERVICE_PORT` at container start). **Grafana configuration.** `monitoring/grafana/grafana.ini` sets `http_addr=0.0.0.0`, `http_port=3000`, disables anonymous access and user sign-up, enables the `publicDashboards` feature toggle, and sets `default_home_dashboard_path` to point at the pre-built eRPC dashboard JSON. The datasource provisioning file (`monitoring/grafana/datasources/prometheus.yml`) registers `http://localhost:9090` as the default Prometheus datasource. The dashboard provider (`monitoring/grafana/dashboards/default.yml`) scans `/etc/grafana/dashboards` every 10 seconds for JSON files and loads them with UI editing allowed. **Dashboard template variables.** The Grafana dashboard uses `$datasource` to select the Prometheus datasource and `$finality` to filter Vendor Share panels by finality type. Key alert expressions from `monitoring/prometheus/alert.rules`: | Alert | Expression basis | Severity | |---|---|---| | `HighErrorRate` | `erpc_upstream_request_errors_total` rate > 5% for 5m | warning | | `SlowRequests` | `erpc_upstream_request_duration_seconds_budget` p95 > 1s for 5m | warning | | `HighRateLimiting` | `erpc_upstream_request_self_rate_limited_total` rate > 10% for 5m | warning | | `NetworkRateLimiting` | `erpc_network_request_self_rate_limited_total` > 10 req/s for 5m | warning | | `HighRequestRate` | `erpc_upstream_request_total` rate > 1000 req/s for 5m | warning | | `LowRequestRate` | `erpc_upstream_request_total` rate < 1 req/s for 15m | warning | The Grafana dashboard (`monitoring/grafana/dashboards/erpc.json`, 80+ panels) covers: request rates and RPS, latency (P50/P90/P99), failover retries by reason, upstream errors by type, block-head lag, cache hit/miss, consensus operations, selection policy, and rate limiter budgets. ### Source code entry points - [`Dockerfile:L70-L88`](https://github.com/erpc/erpc/blob/main/Dockerfile#L70-L88) — final distroless stage: what files land in the image - [`Dockerfile:L24-L34`](https://github.com/erpc/erpc/blob/main/Dockerfile#L24-L34) — `VERSION`/`COMMIT_SHA` ldflags injection - [`cmd/erpc/main.go:L279-L294`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L294) — config file search order (12 paths) - [`cmd/erpc/main.go:L72-L74`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L72-L74) — SIGINT/SIGTERM graceful shutdown via `signal.NotifyContext` - [`monitoring/scripts/entrypoint.sh`](https://github.com/erpc/erpc/blob/main/monitoring/scripts/entrypoint.sh) — sed substitution + dual-process startup - [`docker-compose.yml:L84-L86`](https://github.com/erpc/erpc/blob/main/docker-compose.yml#L84-L86) — named volumes `prometheus_data` and `grafana_data` - [`Makefile:L114`](https://github.com/erpc/erpc/blob/main/Makefile#L114) — `make down` passes `--volumes`, destroying monitoring state - [`Makefile:L121-L123`](https://github.com/erpc/erpc/blob/main/Makefile#L121-L123) — `make docker-build` defaults to `linux/amd64` - [`Makefile:L127-L129`](https://github.com/erpc/erpc/blob/main/Makefile#L127-L129) — `make docker-run`: mounts config, maps ports, invokes `/erpc-server --config /erpc.yaml` - [`monitoring/grafana/grafana.ini`](https://github.com/erpc/erpc/blob/main/monitoring/grafana/grafana.ini) — Grafana server config (port 3000, provisioning, publicDashboards feature toggle) - [`monitoring/grafana/datasources/prometheus.yml`](https://github.com/erpc/erpc/blob/main/monitoring/grafana/datasources/prometheus.yml) — auto-provisions Prometheus datasource at `localhost:9090` - [`monitoring/grafana/dashboards/default.yml`](https://github.com/erpc/erpc/blob/main/monitoring/grafana/dashboards/default.yml) — dashboard file provider scanning `/etc/grafana/dashboards` every 10s - [`monitoring/prometheus/prometheus.yml`](https://github.com/erpc/erpc/blob/main/monitoring/prometheus/prometheus.yml) — local scrape config (self at `localhost:9090` + eRPC at `host.docker.internal:4001`) ### Related pages - [Kubernetes](/deployment/kubernetes.llms.txt) — Deployment, ConfigMap, Service, PodMonitor, and probe tuning. - [Railway](/deployment/railway.llms.txt) — one-click managed deploy with monitoring included. - [Monitoring & metrics](/operation/monitoring.llms.txt) — full metrics reference for dashboards and alerting. - [Healthcheck](/operation/healthcheck.llms.txt) — probe strategy and evaluation logic. - [Authentication](/config/auth.llms.txt) — lock down the exposed RPC port before going public. --- --- # Kubernetes > Source: https://docs.erpc.cloud/deployment/kubernetes > Stateless by design — scale eRPC to any replica count, roll restarts without dropping requests, and wire Prometheus scraping in one manifest apply. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Kubernetes eRPC is a stateless proxy — every replica is identical, rolling restarts are safe, and you can scale to any count without session affinity. The reference manifests in `kube/` give you a Namespace, Deployment, ConfigMap, ClusterIP Service, and PodMonitor in one apply. A companion manifest adds a PostgreSQL cache store. Zero in-flight requests are dropped when you tune the termination grace period to match your timeout settings. ```bash kubectl apply -f kube/erpc.yml kubectl apply -f kube/postgres.yml # optional cache store ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: deploy eRPC to Kubernetes from scratch** ```text Apply the eRPC Kubernetes manifests to my cluster: Namespace, Deployment, ConfigMap, ClusterIP Service, and PodMonitor. Set GOMEMLIMIT to 90% of the memory limit, wire the Downward API for POD_NAME, and pin the image to a specific release tag. My Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/deployment/kubernetes.llms.txt ``` **Prompt Example #2: tune graceful drain to avoid dropped requests** ```text My Kubernetes pods are dropping in-flight requests during rolling deploys. Tune terminationGracePeriodSeconds, server.waitBeforeShutdown, and server.waitAfterShutdown so all requests drain cleanly before SIGKILL. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/kubernetes.llms.txt ``` **Prompt Example #3: fix OOM kills and high tail latency on pods** ```text My eRPC pods are being OOM-killed under load and I also see high p99 latency spikes. Help me set GOMEMLIMIT, GOGC, and resource limits/requests correctly, and explain whether I should remove the CPU limit to avoid CFS throttling. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/kubernetes.llms.txt ``` **Prompt Example #4: wire Prometheus scraping via PodMonitor** ```text My Prometheus Operator is not scraping eRPC metrics. Verify the PodMonitor spec, labels, and port names match my cluster's podMonitorSelector, and explain what metrics to alert on for production. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/kubernetes.llms.txt ``` --- ### Kubernetes — full agent reference ### How it works `kube/erpc.yml` defines five Kubernetes resources: a `erpc` Namespace, a Deployment (single replica by default, safe to scale), a ConfigMap `erpc-config` with an embedded example `erpc.yaml`, a ClusterIP Service (port 80 → 4000), and a `PodMonitor` for Prometheus Operator. `kube/postgres.yml` adds a PersistentVolumeClaim (500 Gi), Deployment, Service, and Secret for a companion PostgreSQL cache store. **Config delivery.** The Deployment mounts the ConfigMap as a volume at `/erpc.yaml`. To change config, update the ConfigMap and run `kubectl rollout restart deployment/erpc` — ConfigMap updates alone do not trigger a rolling restart. **Graceful drain.** eRPC handles `SIGTERM` via `signal.NotifyContext`. After receiving SIGTERM: 1. Healthcheck starts returning 503 — readiness probe fails, pod is removed from Service endpoints. 2. `server.waitBeforeShutdown` elapses — in-flight requests drain. 3. HTTP server calls `Shutdown`. 4. `server.waitAfterShutdown` elapses — lets kube-proxy/Envoy close lingering TCP connections. 5. Process exits. Set `terminationGracePeriodSeconds >= waitBeforeShutdown + waitAfterShutdown + server.maxTimeout`. 180s is a safe default for most workloads. **Prometheus scraping.** The pod template carries annotations and a `PodMonitor` (`monitoring.coreos.com/v1`) is created in the `erpc` namespace: ```yaml # Pod annotations (kube/erpc.yml:L20-L23) prometheus.io/scrape: "true" prometheus.io/port: "4001" prometheus.io/path: "/metrics" ``` The `PodMonitor` is labeled `release: monitoring`, targets the port named `http`, scrapes every `10s` with a `5s` timeout, and matches pods labeled `app: erpc`. **Probes.** The `/healthcheck` HTTP endpoint drives all three probe types. See [Healthcheck](/operation/healthcheck.llms.txt) for the full evaluation strategy. ```yaml startupProbe: httpGet: path: /healthcheck port: 4000 initialDelaySeconds: 10 periodSeconds: 10 failureThreshold: 6 # 60s window to absorb slow upstream init readinessProbe: httpGet: path: /healthcheck port: 4000 periodSeconds: 5 failureThreshold: 2 # removed from endpoints after ~10s livenessProbe: tcpSocket: port: 4000 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 ``` After SIGTERM, the readiness probe fails immediately by design, signalling the orchestrator to drain traffic before the in-flight drain completes. ### Config schema No `erpc.yaml` fields are specific to the Kubernetes deployment layer. The following env vars are relevant in the pod spec: | Variable | Recommended value | Notes | |---|---|---| | `GOMEMLIMIT` | 90% of `resources.limits.memory` (e.g. `2700MiB` for `3Gi`) | Not set in reference manifest; absence risks OOM kill at container limit | | `GOGC` | `40` | Lower GC target reduces heap swings; pair with `GOMEMLIMIT` | | `POD_NAME` | Downward API `metadata.name` | Used for shared-state lock ownership; resolution order: `INSTANCE_ID` → `POD_NAME` → `HOSTNAME` → random UUID | | `LOG_LEVEL` | `info` or `warn` | `trace` is extremely verbose at high RPC traffic; can saturate log shippers | | `LOG_WRITER` | `console` | If set to `"console"`, switches to a zerolog console writer with `04:05.000ms` time format; default is JSON structured output | **CLI subcommands** available in the container binary ([`cmd/erpc/main.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go)): | Subcommand | Purpose | |---|---| | `erpc start` (or `erpc [config]`) | Start the server | | `erpc validate [--format json\|md]` | Parse config, run validation report, exit non-zero on errors — useful in CI pre-deploy checks | | `erpc dump [--format yaml\|json]` | Parse config and dump the resolved effective config (including selection policy expansion) to stdout | Reference resource specs from the kube manifest (the only code-grounded recommendations): | Resource | Requests | Limits | |---|---|---| | eRPC pod | `3Gi` memory, `2` CPU | `3Gi` memory, `2` CPU | | PostgreSQL pod | `8Gi` memory, `4` CPU | `8Gi` memory, `4` CPU | | PostgreSQL PVC | — | `500Gi` | ### Worked examples **1. Minimal production Deployment patch.** Add `GOMEMLIMIT`, remove the CPU limit to avoid CFS throttling, and wire the Downward API for `POD_NAME`: ```yaml env: - name: GOMEMLIMIT value: "2700MiB" - name: GOGC value: "40" - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name resources: requests: memory: "3Gi" cpu: "2" limits: memory: "3Gi" # no cpu limit — avoids CFS throttling on Go goroutines ``` **2. Graceful drain tuning for a 30s `maxTimeout`.** Set these in `erpc.yaml` and match `terminationGracePeriodSeconds` in the pod spec: ```yaml # erpc.yaml (inside ConfigMap) server: waitBeforeShutdown: 30s waitAfterShutdown: 30s ``` ```yaml # Deployment pod spec terminationGracePeriodSeconds: 180 ``` 30s drain + 30s TCP teardown + 30s max request timeout + buffer = 180s is safe for most workloads. **3. Triggering a config reload.** After updating the ConfigMap with a new `erpc.yaml`, restart the Deployment — ConfigMap edits alone are not detected at runtime: ```bash kubectl apply -f kube/erpc.yml kubectl rollout restart deployment/erpc -n erpc kubectl rollout status deployment/erpc -n erpc ``` **4. Horizontal scaling.** eRPC has no replica-count constraint. Scale freely — no sticky sessions, no leader election needed for the proxy path: ```bash kubectl scale deployment/erpc --replicas=5 -n erpc ``` ### Best practices - **Set `GOMEMLIMIT=2700MiB`** (or 90% of your memory limit) as a container env var. The reference manifest omits it — without it, Go's GC may allow the heap to reach the hard 3 Gi limit and trigger an OOM kill instead of a managed GC cycle. - **Remove `resources.limits.cpu`**. Go's work-stealing scheduler is sensitive to Linux CFS throttling; a hard CPU limit raises tail latency without reducing memory usage. Set `resources.requests.cpu` for scheduler placement but leave limits absent. - **Pin the image tag**. The reference manifest uses `ghcr.io/erpc/erpc:latest` — pin to a specific tag or SHA for reproducible production rollouts. - **Pin PostgreSQL too**. `kube/postgres.yml` uses `postgres:latest` — pin a specific PostgreSQL version and digest for production. - **Always `kubectl rollout restart` after ConfigMap changes**. A ConfigMap update in place does not trigger pod restarts; traffic keeps hitting the old config until you explicitly restart. - **Size `terminationGracePeriodSeconds` generously**. It must be ≥ `waitBeforeShutdown + waitAfterShutdown + server.maxTimeout`; otherwise Kubernetes sends SIGKILL before the drain completes, dropping active requests. - **Allow egress to upstream RPC endpoints**. eRPC makes outbound connections on 443/TCP and 80/TCP to upstream providers, plus 5432/TCP (PostgreSQL) and 6379/TCP (Redis) for cache backends. Include these in your NetworkPolicy. ### Edge cases & gotchas 1. **No `GOMEMLIMIT` in reference manifest**: With `3Gi` limit, Go GC may trigger OOM. Set `GOMEMLIMIT=2700MiB`. 2. **CPU limits cause throttling**: Hard CPU limits engage Linux CFS throttling on Go goroutines, raising tail latency. Omit `resources.limits.cpu`. 3. **`terminationGracePeriodSeconds` too small**: If shorter than `waitBeforeShutdown + waitAfterShutdown + maxTimeout`, Kubernetes sends SIGKILL before drain completes, dropping active requests. 4. **Startup probe `initialDelaySeconds` too low**: If upstreams are slow to respond at startup, the probe fails and Kubernetes restarts the pod in a loop. Use a `startupProbe` with generous `failureThreshold` (6 × 10s = 60s window). 5. **ConfigMap update alone does not restart pods**: Run `kubectl rollout restart deployment/erpc` or checksum the ConfigMap in pod template annotations to force a rolling update. 6. **Image tag `:latest` is not reproducible**: Reference manifest pins `:latest` — operators should pin a specific tag or SHA. 7. **`kube/postgres.yml` PVC is `ReadWriteOnce`**: Multi-zone clusters may fail to reschedule the pod to a different availability zone. Ensure your StorageClass supports cross-zone access or use a managed database instead. 8. **No official Helm chart**: The repository provides raw manifests under `kube/`. Community-maintained charts may exist on Artifact Hub. 9. **Network policy egress**: eRPC makes outbound connections to upstream RPC endpoints (443/TCP, 80/TCP) and optional cache backends (5432/TCP PostgreSQL, 6379/TCP Redis). Allow ingress on 4000/TCP from app pods and 4001/TCP from the Prometheus scraper. 10. **`kube/postgres.yml` uses `postgres:latest`**: Pin a specific PostgreSQL version and digest for production. 11. **gRPC and HTTP share port 4000 by default**: `server.grpcPortV4` and `server.httpPortV4` both default to `4000`. If you override the gRPC port to a different value, a second listener is bound and you must add a corresponding `containerPort` and Service port entry. The manifest only exposes 4000 and 4001. 12. **pprof binary present but never invoked by default**: The image ships `/erpc-server-pprof` (built with `-tags pprof`) alongside the default `/erpc-server`. To enable profiling on port 6060, override the container `command` to `/erpc-server-pprof`; the default `CMD` runs the non-pprof binary. ### Observability Scraped by Prometheus via PodMonitor at `4001/metrics` every 10s. Key metrics for Kubernetes-level alerting: | Metric | Type | When it fires | |---|---|---| | `erpc_upstream_request_errors_total` | counter | Every upstream request error (used in `HighErrorRate` alert) | | `erpc_upstream_request_duration_seconds_budget` | histogram | Per-upstream request duration (used in `SlowRequests` p95 alert) | | `erpc_upstream_request_total` | counter | Every upstream request; drives `HighRequestRate` alert (> 1000 req/s for 5 min) and `LowRequestRate` alert (< 1 req/s for 15 min, warning) | | `erpc_upstream_request_self_rate_limited_total` | counter | Upstream self-rate-limiting events | | `erpc_network_request_self_rate_limited_total` | counter | Network-level self-rate-limiting events | The `PodMonitor` is labeled `release: monitoring` and must match your Prometheus Operator's `serviceMonitorSelector` / `podMonitorSelector`. [[`kube/erpc.yml:L145-160`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L145-L160)] ### Source code entry points - [`kube/erpc.yml`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml) — Namespace, Deployment, ConfigMap, Service, PodMonitor - [`kube/postgres.yml`](https://github.com/erpc/erpc/blob/main/kube/postgres.yml) — PVC (500Gi), Deployment, Service, Secret for PostgreSQL - [`kube/erpc.yml:L33-L36`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L33-L36) — reference resource sizing: `3Gi` memory, `2` CPU - [`kube/erpc.yml:L145-L160`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L145-L160) — PodMonitor spec (10s scrape interval, 5s timeout) - [`kube/erpc.yml:L54-L130`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L54-L130) — embedded ConfigMap with Arbitrum example config - [`cmd/erpc/main.go:L72-L74`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L72-L74) — SIGTERM graceful shutdown via `signal.NotifyContext` - [`cmd/erpc/main.go:L279-L294`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L294) — config file search order (12 paths) ### Related pages - [Docker](/deployment/docker.llms.txt) — single-container run and local compose stack with monitoring. - [Railway](/deployment/railway.llms.txt) — one-click managed deploy. - [Healthcheck](/operation/healthcheck.llms.txt) — probe strategy and evaluation logic. - [Monitoring & metrics](/operation/monitoring.llms.txt) — full metrics reference for dashboards and alerting. - [Authentication](/config/auth.llms.txt) — secure the ingress before exposing the Service externally. --- --- # Railway > Source: https://docs.erpc.cloud/deployment/railway > From zero to a running eRPC proxy with Grafana monitoring in one click — no infra to manage, public endpoints ready immediately. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Railway The fastest way to get eRPC running. Click the button, Railway deploys both the proxy and a full Prometheus + Grafana monitoring stack in seconds. The default config already covers every supported chain using public free endpoints — no API keys required to start sending requests. [![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/template/10iW1q) ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: deploy eRPC on Railway with monitoring** ```text Deploy eRPC on Railway using the one-click template, then connect my own fork so I can customize eRPC config with premium upstream API keys stored as Railway environment variables. Include Grafana monitoring. My config will go in my eRPC config. Read the full reference first: https://docs.erpc.cloud/deployment/railway.llms.txt ``` **Prompt Example #2: secure the public endpoint before production** ```text My Railway-deployed eRPC instance is publicly accessible without any auth. Add authentication and rate limiting to my eRPC config so the public URL is safe for production traffic, and show me how to inject the secret via Railway environment variables without committing it to the repo. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/railway.llms.txt ``` **Prompt Example #3: call eRPC from another service in the same project** ```text I have a Railway service that needs to call my eRPC instance without going over the public internet. Configure the internal .railway.internal hostname and show me the correct fetch call. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/deployment/railway.llms.txt ``` --- ### Railway — full agent reference ### How it works The template deploys from the [`erpc/railway-deployment`](https://github.com/erpc/railway-deployment) repository and creates two Railway services: - **erpc** — the proxy, listening on port 4000. Railway assigns a public URL automatically. - **monitoring** — the same combined Prometheus v3.9.1 + Grafana 12.3.3 container as the repo's `monitoring/Dockerfile`. Grafana is accessible on port 3000. The default `erpc.yaml` in the template uses public free RPC endpoints across all supported chains, so traffic flows immediately without any credentials. **Private networking.** Services within the same Railway project communicate via `.railway.internal` hostnames without leaving Railway's network and without incurring egress costs. Services outside the project (or local clients) use the public URL. **Config customization.** Railway deploys from a connected Git repository. To change `erpc.yaml`, fork [`erpc/railway-deployment`](https://github.com/erpc/railway-deployment), edit the config in your fork, and connect Railway to your fork under **Settings → Source**. Pushing to the connected branch triggers an automatic redeploy. **Monitoring.** After deploying, open the `monitoring` service in Railway, find the Grafana URL under **Settings → Networking → Public Networking**, and log in with `admin`/`admin`. The Grafana dashboard loads automatically with 80+ panels covering request rates, latency, failover events, and cache metrics. ```js // Calling eRPC from another Railway service (private network) const result = await fetch("https://my-erpc.railway.internal/main/evm/1", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ method: "eth_getBlockByNumber", params: ["0x1203319", false], id: 1, jsonrpc: "2.0", }), }); ``` Use the public URL (found under **Settings → Networking → Public Networking** in the eRPC service) for clients outside the same Railway project. ### Config schema Railway deployment has no eRPC-specific config fields. Configuration is entirely through `erpc.yaml` in the connected repository. Railway injects standard env vars (`PORT`, `RAILWAY_ENVIRONMENT`, etc.) which eRPC does not use directly. The relevant eRPC env vars that operators may set via Railway's environment variable UI: | Variable | Effect | |---|---| | `LOG_LEVEL` | `trace`/`debug`/`info`/`warn`/`error` — overrides `cfg.LogLevel` | | `LOG_WRITER` | Set to `console` for human-readable log output | | `GOMEMLIMIT` | Go soft memory limit; set to ~90% of the service's memory allocation | ### Worked examples **1. One-click deploy from the template.** Click the Railway button above, sign in or create a Railway account, click **Deploy**. Done — both services start in under a minute. **2. Adding premium upstreams.** Fork [`erpc/railway-deployment`](https://github.com/erpc/railway-deployment) and edit `erpc.yaml` to add your Alchemy or QuickNode keys. In Railway, go to your eRPC service → **Settings → Source** and connect your fork. Subsequent pushes to main auto-deploy: ```yaml # erpc.yaml in your fork projects: - id: main networks: - architecture: evm evm: chainId: 1 upstreams: - id: alchemy-mainnet endpoint: https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_KEY} ``` Set `ALCHEMY_KEY` as a Railway environment variable so it's not committed to the repo. **3. Enabling CORS for browser usage.** If you call eRPC directly from a frontend, add a CORS block to `erpc.yaml`. See [CORS](/config/projects/cors.llms.txt) for full options: ```yaml projects: - id: main cors: allowedOrigins: - "https://your-app.com" ``` **4. Securing the public endpoint.** The default config proxies all chains to anyone with the public URL. Add authentication before going to production: ```yaml projects: - id: main auth: strategies: - type: secret secret: value: ${AUTH_SECRET} ``` Set `AUTH_SECRET` in Railway's environment variable UI. ### Best practices - **Change the Grafana password immediately.** The monitoring service ships with `admin`/`admin`. Set a strong password via Railway environment variables before sharing the public Grafana URL. - **Set `GOMEMLIMIT`** to ~90% of your Railway service's memory allocation. Without it, Go's GC may allow the heap to reach the hard memory limit and trigger a service restart. - **Use CORS before exposing to browsers.** eRPC's default config has no CORS headers. Add a `cors` block under your project in `erpc.yaml` before consuming from a frontend. See [CORS](/config/projects/cors.llms.txt). - **Use authentication before going public.** The default config proxies all supported chains without access control. Add [authentication](/config/auth.llms.txt) or [rate limiters](/config/rate-limiters.llms.txt) before exposing the public URL to untrusted clients. - **Keep secrets out of `erpc.yaml`.** Use Railway environment variables for API keys and reference them as `${VAR_NAME}` in your config file. - **Do not rely on the monitoring service for production observability.** Prometheus and Grafana share one container — a crash in either is not independently restarted. For production monitoring, use separate Railway services or an external observability stack. ### Edge cases & gotchas 1. **Default credentials**: Grafana ships with `admin`/`admin`. Set a strong password via Railway env vars before exposing the public URL. 2. **CORS for browser usage**: eRPC's default config has no CORS headers. Add a `cors` block under your project in `erpc.yaml` before consuming from a frontend. See [CORS](/config/projects/cors.llms.txt). 3. **Config changes require a connected repo**: Editing `erpc.yaml` triggers an automatic redeploy only if you connected your fork to Railway. Manual deploys are needed otherwise. 4. **Monitoring container is single-process**: Prometheus and Grafana share one container. A crash in either is not independently restarted. Not suitable for production monitoring. 5. **Public URL exposes all chains**: The default config proxies public endpoints for all supported chains. Add [authentication](/config/auth.llms.txt) or [rate limiters](/config/rate-limiters.llms.txt) before exposing the public URL to untrusted clients. 6. **Private networking is project-scoped**: The `.railway.internal` hostname is only reachable from services within the same Railway project. External clients must use the public URL. ### Source code entry points - [`railway-deployment` repository](https://github.com/erpc/railway-deployment) — template source with default `erpc.yaml` - [`monitoring/Dockerfile`](https://github.com/erpc/erpc/blob/main/monitoring/Dockerfile) — combined Prometheus v3.9.1 + Grafana 12.3.3 image - [`monitoring/scripts/entrypoint.sh`](https://github.com/erpc/erpc/blob/main/monitoring/scripts/entrypoint.sh) — dual-process startup and `SERVICE_ENDPOINT` substitution - [`cmd/erpc/main.go:L354-L363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) — `LOG_LEVEL` env var handling - [`cmd/erpc/main.go:L72-L74`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L72-L74) — SIGTERM graceful shutdown via `signal.NotifyContext` ### Related pages - [Docker](/deployment/docker.llms.txt) — self-hosted container deploy with local compose stack. - [Kubernetes](/deployment/kubernetes.llms.txt) — production-grade orchestration with resource sizing and drain tuning. - [Monitoring & metrics](/operation/monitoring.llms.txt) — full metrics reference for dashboards and alerting. - [Authentication](/config/auth.llms.txt) — lock down the public endpoint before production traffic. - [Rate limiters](/config/rate-limiters.llms.txt) — cap per-client or per-upstream traffic. - [CORS](/config/projects/cors.llms.txt) — required for browser-side usage. --- --- # FAQ > Source: https://docs.erpc.cloud/faq > Quick answers to the most common eRPC questions — config files, caching gotchas, auth setup, rate limits, and error codes decoded. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # FAQ Get unstuck fast. These are the questions that come up most often when setting up, configuring, and operating eRPC. ### How do I use environment variables in my config file? YAML: every `$VAR` or `${VAR}` is substituted before the file is parsed — no extra syntax. TypeScript: use `process.env.MY_KEY` like any Node program. ### Which config file does eRPC load automatically? eRPC checks for `erpc.yaml`, `.yml`, `.ts`, and `.js` — first in `./`, then `/`, then `/root/`. First file found wins. No config file found and `--require-config` not set? eRPC starts with a built-in default project. ### What happens if I leave out a config section — do I get defaults? Yes. `SetDefaults` fills every missing field. Run `erpc dump ./erpc.yaml` to see the exact config the engine would use, with all defaults resolved. ### How do I validate my config without starting eRPC? ```bash erpc validate ./erpc.yaml ``` Exit 0 means no errors. Pipe stdout through `jq .errors` to see only errors. ### Can I use `--set` to override a single config value? No. The `--set` / `-s` flag was planned but is not implemented. Use environment variables or edit the config file. --- ### Why does eRPC still hit upstreams even though I added a cache? The most common cause: no `finality: realtime` policy. Methods like `eth_blockNumber` and `eth_gasPrice` resolve to `realtime` finality and only match policies that explicitly declare `finality: realtime`. A policy without `finality` silently covers only finalized data. Add a second policy for realtime: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: my-redis driver: redis redis: addr: "localhost:6379" policies: - connector: my-redis network: "*" method: "*" finality: finalized - connector: my-redis network: "*" method: "*" # realtime methods (eth_blockNumber, eth_gasPrice) only match this policy finality: realtime ttl: 2s ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "my-redis", driver: "redis", redis: { addr: "localhost:6379" } }], policies: [ { connector: "my-redis", network: "*", method: "*", finality: "finalized" }, { connector: "my-redis", network: "*", method: "*", // realtime methods (eth_blockNumber, eth_gasPrice) only match this policy finality: "realtime", ttl: "2s", }, ], }, } ``` ### Why do empty `eth_getLogs` results trigger a retry instead of being cached? The default `empty: ignore` skips caching empty results. This is intentional — an empty log set for a block that hasn't been produced yet would be wrong to cache. Set `empty: allow` if you genuinely want to cache empty responses for confirmed blocks. ### How does the realtime TTL guard work? It checks the **block's age**, not how long ago the response was cached. A response cached five minutes ago is still served if its block is fresh; a response cached ten seconds ago is rejected if its block is older than the TTL. ### Is zstd compression on by default? Yes — even if you omit the `compression:` block entirely. To disable it you must explicitly set `compression.enabled: false`. ### How do I disable caching entirely? Omit the `database.evmJsonRpcCache` key (and `database.svmJsonRpcCache` if you run SVM networks). When the pointer is nil, that cache subsystem is never created. ### Does eRPC support Solana? Yes. Declare `architecture: svm` with an `svm.cluster`, give each upstream `type: svm` (it is never inferred), and eRPC applies the same failsafe, routing, and caching machinery it uses for EVM. Network ids are `svm:` — or `svm::` for forks like Fogo and Eclipse. See [Networks](/config/projects/networks.llms.txt) and the [SVM reference](/reference/svm/commitment.llms.txt). ### Why isn't my Solana `getBalance` cached even at `commitment: finalized`? Because Solana's `finalized` is the state at the latest **rooted** slot, and that slot advances roughly every 400 ms — it is a moving head, not an immutability guarantee. Only reads pinned to a specific slot or signature (`getBlock`, `getTransaction`) at `finalized` commitment are cached as immutable; every other read is `realtime` and needs a `finality: realtime` policy with a TTL. Full explanation: [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt). --- ### What auth strategies does eRPC support? Five: `secret` (static token), `jwt` (signed bearer), `siwe` (EIP-4361 Ethereum sign-in), `network` (IP/CIDR allowlist), and `database` (dynamic lookup against PostgreSQL, DynamoDB, Redis, or memory). If `projects[*].auth` is nil, all requests are allowed. ### How does the database strategy handle a DB outage? Default is fail-closed (`failOpen.enabled: false`), so any DB error rejects the request. Set `failOpen.enabled: true` to treat DB failures as successful authentication using a synthetic `failOpen.userId`. A circuit-breaker limits live DB probes to one per second during an outage. ### Why is my JWT auth rejecting all tokens? Most likely: empty `verificationKeys` map. With no keys configured no signature can be verified and every JWT is rejected. Add at least one `kid → keyData` entry. ### How do rate-limit budgets interact with auth? After successful authentication the rate-limit check fires at auth scope before the request reaches project or network scope. A per-user budget on the auth record overrides the strategy-level budget. --- ### What is the default rate-limiting behavior? When `rateLimiters` is omitted, no budgets are registered and every request passes through. Adding `rateLimiters:` without any `budgets:` entries also passes all traffic. ### Does eRPC rate-limit inbound or outbound traffic? Both. Check order: auth → project → network → upstream. Inbound rejections return HTTP 429. Upstream-level rejections return HTTP 200 with JSON-RPC error code `-32005`. ### Why does my upstream budget rate limit return HTTP 200, not 429? `ErrUpstreamRateLimitRuleExceeded` is not in the wire 429 list. It returns HTTP 200 with JSON-RPC error code `-32005`. ### Can multiple eRPC instances share a rate-limit budget? Yes, but only with `store.driver: redis`. The default `memory` driver is per-process — each instance counts independently. With Redis, set distinct `cacheKeyPrefix` values per deployment to prevent quota collision. ### Does the auto-tuner affect shared budgets? Yes, and it can conflict. Each upstream has its own auto-tuner that independently adjusts `MaxCount` on the shared budget's rules. Whichever tuner fires last wins. --- ### Why do I see `-32603` for errors that should have a specific code? `-32603` is the fallback for any internal error that doesn't map to a specific JSON-RPC code. Check the error `message` field and look for an `ErrCode` in the body. If the error is wrapped in `ErrUpstreamsExhausted`, the dominant child error determines the final code. ### What does `-32005` mean? `-32005` is `JsonRpcErrorCapacityExceeded` — eRPC's normalized code for rate limits, upstream 429s, billing issues, and endpoint capacity errors. ### What does `-32014` mean? `-32014` is `JsonRpcErrorMissingData` — the requested block, transaction, or state is not available on this node (archive vs. full node mismatch, or data not yet indexed). ### Why does `eth_sendRawTransaction` sometimes get retried to a different upstream? `eth_sendRawTransaction` is intentionally excluded from the non-retryable write-method guard. Reverts and out-of-gas errors are safe to retry because the transaction was never mined. However, `"already known"` or `"nonce too low"` responses are classified as `ErrEndpointNonceException` and are NOT retried to another upstream. ### How do I suppress verbose error labels in Prometheus? Set `metrics.errorLabelMode: compact` (the default). Compact mode emits only the error code chain; verbose mode includes the full message string, which can create high-cardinality series. --- --- ### FAQ — agent details ### How it works The FAQ answers above are each grounded in one or more KB source files. This section provides the full mechanics, config schema, worked examples, best practices, edge cases, and source entry points for each topic area. ### Config schema Key fields referenced across FAQ answers: | YAML path | Type | Default | Notes | |---|---|---|---| | `logLevel` | string | `"INFO"` | Zerolog global level; also overridable via `LOG_LEVEL` env var (applied twice: at init and after config load). [`common/defaults.go:L50-52`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L50-L52) | | `clusterKey` | string | `"erpc-default"` | Logical replica group for shared-state scoping. [`common/defaults.go:L53-55`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L53-L55) | | `metrics.errorLabelMode` | string | `"compact"` | `"compact"` = code-only labels; `"verbose"` = code + message. High-cardinality risk with verbose. [`common/defaults.go:L762-764`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L762-L764) | | `database.evmJsonRpcCache.policies[*].finality` | string | `"finalized"` (zero value) | Must be explicitly `"realtime"` to cache realtime methods. Omitting is identical to `finality: finalized`. [`common/data.go:L10`](https://github.com/erpc/erpc/blob/main/common/data.go#L10) | | `database.evmJsonRpcCache.policies[*].empty` | string | `"ignore"` | `"ignore"` = skip empty on write, treat as miss on read. `"allow"` = cache empty results. `"only"` = cache only empty results. | | `database.evmJsonRpcCache.compression.enabled` | bool | `true` | Auto-enabled even when `compression:` block is omitted. Must explicitly be set to `false` to opt out. [`common/defaults.go:L580-582`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L580-L582) | | `rateLimiters.store.driver` | string | `"memory"` | `"redis"` required for cross-instance shared budgets. [`common/defaults.go:L2782`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2782) | | `rateLimiters.store.cacheKeyPrefix` | string | `"erpc_rl_"` | Must differ between eRPC deployments sharing the same Redis to prevent quota collision. [`upstream/ratelimiter_registry.go:L76`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L76) | | `rateLimiters.budgets[*].rules[*].maxCount` | uint32 | required | `0` means always-blocked (not unlimited). Omit `rateLimitBudget` entirely for unrestricted access. | | `projects[*].auth` | `*AuthConfig` | nil (allow-all) | When nil, all requests are authenticated as anonymous with no check. | | `projects[*].auth.strategies[*].database.failOpen.enabled` | bool | `false` | Set `true` to allow traffic through on DB outage, using the synthetic `failOpen.userId`. [`common/defaults.go:L2735-2742`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2735-L2742) | ### Worked examples **1. Full cache setup with finality buckets.** Cover both finalized and realtime data; without the second policy, `eth_blockNumber` and `eth_gasPrice` will always miss cache and hit upstreams: **Config path:** `database.evmJsonRpcCache` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: connectors: - id: my-redis driver: redis redis: addr: "localhost:6379" policies: - connector: my-redis network: "*" method: "*" finality: finalized - connector: my-redis network: "*" method: "*" finality: realtime ttl: 2s ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { connectors: [{ id: "my-redis", driver: "redis", redis: { addr: "localhost:6379" } }], policies: [ { connector: "my-redis", network: "*", method: "*", finality: "finalized" }, { connector: "my-redis", network: "*", method: "*", finality: "realtime", ttl: "2s" }, ], }, } ``` **2. JWT auth with per-user rate-limit budgets.** The JWT claim named by `rateLimitBudgetClaimName` (default `"rlm"`) sets the per-user budget; tokens without that claim fall through to the strategy-level budget or no budget: **Config path:** `projects[].auth` **YAML — `erpc.yaml`:** ```yaml auth: strategies: - type: jwt jwt: verificationKeys: my-key-id: "file:///run/secrets/jwt-pub.pem" allowedAlgorithms: ["RS256"] rateLimitBudget: default-budget ``` **TypeScript — `erpc.ts`:** ```typescript auth: { strategies: [{ type: "jwt", jwt: { verificationKeys: { "my-key-id": "file:///run/secrets/jwt-pub.pem" }, allowedAlgorithms: ["RS256"], }, rateLimitBudget: "default-budget", }], } ``` **3. Redis shared rate limiter with separate prefixes per environment.** Prevents staging and production counters from colliding when both deployments share one Redis instance: **Config path:** `rateLimiters` **YAML — `erpc.yaml`:** ```yaml rateLimiters: store: driver: redis redis: addr: "shared-redis:6379" cacheKeyPrefix: "erpc_prod_" budgets: - id: provider-budget rules: - method: "*" maxCount: 500 period: second ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { store: { driver: "redis", redis: { addr: "shared-redis:6379" }, cacheKeyPrefix: "erpc_prod_", }, budgets: [{ id: "provider-budget", rules: [{ method: "*", maxCount: 500, period: "second" }] }], } ``` **4. Database auth with fail-open.** Lets traffic through during a DB outage, capping emergency users with a dedicated budget: **Config path:** `projects[].auth.strategies[]` **YAML — `erpc.yaml`:** ```yaml strategies: - type: database database: connector: driver: postgresql postgresql: connectionUri: "\${AUTH_DB_URI}" failOpen: enabled: true userId: emergency-failopen rateLimitBudget: failopen-budget ``` **TypeScript — `erpc.ts`:** ```typescript strategies: [{ type: "database", database: { connector: { driver: "postgresql", postgresql: { connectionUri: process.env.AUTH_DB_URI } }, failOpen: { enabled: true, userId: "emergency-failopen", rateLimitBudget: "failopen-budget" }, }, }] ``` ### Request/response behavior **Config loading flow.** `os.ExpandEnv` runs on raw YAML bytes before the YAML parser sees the file. If `$VAR` expands to a value containing `:` or `{`, the value must be quoted: `endpoint: "${MY_URL}"`. TypeScript configs receive the full OS environment as `process.env` in the sobek runtime — substitution is JS-native, not a pre-parse pass. [`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) **Cache finality matching.** On reads, a `finalized` request also matches `unfinalized` policies (a block finalized after write may have been stored unfinalized). A `realtime` request matches only `realtime` policies — no cross-finality fallthrough. On writes, finality must match exactly. [`architecture/evm/json_rpc_cache.go:L951-978`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L951-L978) **Realtime TTL guard.** Compares the **block's unix timestamp** (from the response body) against `time.Now()`. It does NOT check how long ago the response was written to cache. For methods with no block timestamp in the response (`eth_blockNumber`, `eth_gasPrice`, `eth_getLogs`), the guard falls back to the gRPC connector's latest-block timestamp, which is polled every 60 seconds. If no timestamp is available the guard fails open and serves the cached result. [`architecture/evm/json_rpc_cache.go:L841-920`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L841-L920) **Rate-limit check order.** auth → project → network → upstream. Each layer uses the same `TryAcquirePermit` path. Auth, project, and network rejections return HTTP 429. Upstream rejections return HTTP 200 with JSON-RPC code `-32005` because `ErrUpstreamRateLimitRuleExceeded` is absent from the wire 429 switch. [`erpc/http_server.go:L1484`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1484) **Error code derivation.** When `ErrUpstreamsExhausted` wraps multiple per-upstream errors, the final JSON-RPC code is the dominant child: highest occurrence count, skipping `ErrCodeUpstreamRequestSkipped` and `ErrCodeEndpointUnsupported`; earliest error per code wins ties. The fallback for any unmapped internal error is `-32603`. [`common/json_rpc.go:L1501`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1501) ### Best practices - Always add a `finality: realtime` policy alongside your `finality: finalized` policy — omitting it silently bypasses the cache for all time-sensitive methods. The zero-value trap is the single most common cache misconfiguration. On SVM this is even more pronounced: `realtime` covers nearly all traffic, because only `getBlock`/`getTransaction` at `finalized` commitment (plus `getBlockTime` and `getInflationReward`) land in the `finalized` bucket. - Use `erpc dump ./erpc.yaml` before deploying to verify that all defaults have been filled in as expected, especially compression and auto-tuner settings. - Use `erpc validate ./erpc.yaml` in CI; exit code 0 means no errors. Pipe through `jq .errors` for clean output. - For fleet deployments using Redis rate limiting, set a distinct `cacheKeyPrefix` per environment (`erpc_prod_`, `erpc_staging_`) to prevent quota collision between deployments sharing one Redis. - Set `metrics.errorLabelMode: compact` (the default) in production. Verbose mode can create unbounded label cardinality when provider error messages contain addresses, hashes, or block numbers. - For `database` auth strategy, set `failOpen.enabled: true` with a dedicated `failOpen.rateLimitBudget` so traffic during DB outages is capped and observable — the circuit-breaker limits live DB probes to one per second automatically. - Do not set `rateLimitBudget` to a budget that doesn't exist in `rateLimiters.budgets` — the error is a runtime error, not a startup error, and will surface only on the first request that reaches that code path. ### Edge cases & gotchas 1. **`finality` zero-value trap.** Omitting `finality` in a cache policy is identical to `finality: finalized`. Realtime methods never match and always hit upstreams silently. [`common/data.go:L10`](https://github.com/erpc/erpc/blob/main/common/data.go#L10) 2. **Compression is always on.** The `compression` sub-block is auto-created with `enabled: true` even when omitted. You must explicitly write `compression.enabled: false` to disable it. [`common/defaults.go:L482-488`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L482-L488) 3. **Empty `eth_getLogs` with `empty: ignore` triggers retries.** The default behavior skips caching empty results. The upstream is hit every time until a non-empty response is produced or the block is confirmed past the network head. [`architecture/evm/json_rpc_cache.go:L1079`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L1079) 4. **Realtime TTL guard checks block age, not cache-entry age.** A cached response from 10 minutes ago is served if its block is still fresh; a cached response from 5 seconds ago is rejected if its block is stale. 5. **Memory rate limiter is per-process.** In a multi-instance deployment, each instance has independent counters. The effective limit scales linearly with instance count. Use the Redis driver for shared limits. [`upstream/ratelimiter_registry.go:L48-51`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_registry.go#L48-L51) 6. **Upstream rate-limit rejections return HTTP 200.** `ErrUpstreamRateLimitRuleExceeded` is not in the 429 wire list. Client SDKs that interpret HTTP 200 as success will not retry — check the JSON-RPC error code `-32005`. [`erpc/http_server.go:L1484`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1484) 7. **`maxCount: 0` in a rate-limit rule means always-blocked**, not unlimited. Omit `rateLimitBudget` entirely to allow unrestricted traffic. [`upstream/ratelimiter_budget.go:L109-119`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L109-L119) 8. **`--set` / `-s` is not implemented.** Passing `-s` or `--set` produces `"flag provided but not defined: -s"` from the CLI framework — no eRPC code runs. [`cmd/erpc/main.go:L86-90`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L86-L90) 9. **`--config` sets `requireConfig: true` implicitly.** If the specified file does not exist, eRPC exits 1001. There is no fallback to auto-discovery when an explicit path is given. [`cmd/erpc/main.go:L300-302`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L300-L302) 10. **YAML strict mode rejects unknown keys.** A typo in any YAML key is a fatal error at startup. TypeScript configs go through the same strict YAML decoder via JSON round-trip. [`common/config.go:L103`](https://github.com/erpc/erpc/blob/main/common/config.go#L103) 11. **Auto-tuner is implicitly enabled when `rateLimitBudget` is set.** `SetDefaults` auto-creates `RateLimitAutoTuneConfig` when `rateLimitBudget != ""` and `rateLimitAutoTune` is nil. Opt out with `rateLimitAutoTune.enabled: false`. [`common/defaults.go:L1674`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1674) 12. **Database auth circuit-breaker limits probes to 1 per second during outage.** Only one goroutine per second is elected to probe the real DB path; all others get fail-open (if enabled) immediately. [`auth/strategy_database.go:L25-54`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L25-L54) 13. **Empty `verificationKeys` rejects all JWTs.** With no keys, `findVerificationKey` always fails → every JWT token is rejected regardless of content. Add at least one `kid → keyData` entry. [`auth/strategy_jwt.go:L25-42`](https://github.com/erpc/erpc/blob/main/auth/strategy_jwt.go#L25-L42) 14. **`os.ExpandEnv` in YAML runs on raw bytes before parse.** A YAML value like `password: ${REDIS_PASSWORD}` is substituted before decode. If the value contains YAML special characters (`:`, `{`), the resulting YAML will be malformed — use quoted values: `password: "${REDIS_PASSWORD}"`. [`common/config.go:L102`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) 15. **SVM cache keys are case-sensitive; EVM's are not.** The EVM hasher lowercases string params, which is correct for hex. The SVM key preserves case exactly, because base58 pubkeys and signatures are case-significant and folding them would serve one account another's data. [`architecture/svm/json_rpc_cache.go:L412-433`](https://github.com/erpc/erpc/blob/main/architecture/svm/json_rpc_cache.go#L412-L433) 16. **SVM has no realtime block-age guard.** The TTL on a `finality: realtime` SVM policy is the *only* staleness bound — there is no block-timestamp cross-check to catch an over-long TTL, and `erpc_cache_get_age_guard_reject_total` never fires on SVM networks. [`architecture/svm/json_rpc_cache.go:L30-33`](https://github.com/erpc/erpc/blob/main/architecture/svm/json_rpc_cache.go#L30-L33) 17. **`type: svm` is never inferred on an upstream.** An upstream omitting `type` defaults to `evm`, so a Solana endpoint without it fails bootstrap while trying `eth_chainId`. [`common/defaults.go:L1715-1718`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1715-L1718) ### Observability | Metric | Type | When it fires | |--------|------|---------------| | `erpc_cache_get_age_guard_reject_total` | counter | Realtime cached result rejected because block age exceeded policy TTL | | `erpc_cache_set_skipped_total` | counter | `shouldCacheResponse` returned false (empty result, size filter, future block) | | `erpc_rate_limits_total` | counter | Any budget rule denied a request; labeled by `origin` (auth/project/network/upstream) | | `erpc_rate_limiter_failopen_total` | counter | Rate limiter allowed request due to Redis timeout or admission semaphore full | | `erpc_auth_failed_total` | counter | Auth strategy rejected the request | | `erpc_upstream_request_errors_total` | counter | Upstream returned an error; `error` label uses `ErrorFingerprint` | ### Source code entry points - [`cmd/erpc/main.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279) — config search order, `--config` flag, `--set` (commented out), `getConfig`, `baseCliAction` - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49) — `SetDefaults`, default project synthesis, auto-tune injection, compression auto-creation - [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go#L102) — `LoadConfig`, `os.ExpandEnv` YAML substitution, TS loader, strict YAML decoder - [`common/data.go`](https://github.com/erpc/erpc/blob/main/common/data.go#L10) — `DataFinalityState` enum (finalized=0, realtime=2) - [`architecture/evm/json_rpc_cache.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go#L841) — `shouldAcceptCachedResult` (realtime age guard), `shouldCacheResponse`, finality policy matching - [`erpc/http_server.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1484) — wire HTTP status switch, 429 error list, upstream-level 200 return - [`upstream/ratelimiter_budget.go`](https://github.com/erpc/erpc/blob/main/upstream/ratelimiter_budget.go#L153) — `TryAcquirePermit`, fail-open, admission semaphore - [`auth/strategy_database.go`](https://github.com/erpc/erpc/blob/main/auth/strategy_database.go#L25) — circuit-breaker, `tryFastFailOpen`, singleflight dedup - [`common/errors.go`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1) — full error type hierarchy, retryability flags, `ErrUpstreamsExhausted` dominant-code selection - [`architecture/evm/error_normalizer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L20) — vendor error normalization rules, 22-rule cascade ### Related pages - [Cache database](/config/database.llms.txt) — connector setup, full policy reference, compression config. - [Auth](/config/auth.llms.txt) — all five strategies in depth, method filtering, per-user budgets. - [Rate limiters](/config/rate-limiters.llms.txt) — budget rules, auto-tuner, Redis vs. memory store. - [Config reference](/reference.llms.txt) — complete field listing with defaults. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — putting failsafe and routing together. --- --- # Free & Public RPCs > Source: https://docs.erpc.cloud/free > Zero config, zero API keys — eRPC auto-connects to thousands of free public EVM endpoints the moment you start it. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Free & Public RPCs No config file, no API keys, no provider signup. Start eRPC and it immediately routes every EVM chain through an auto-injected provider — a curated public endpoint catalog — backed by eRPC's full resilience stack. The fastest way to go from zero to any chain in development or prototyping. ## Quick taste Illustrative — this is the default behavior with no config: **npm:** ```bash npx start-erpc ``` **Docker:** ```bash docker run -p 4000:4000 ghcr.io/erpc/erpc ``` Or deploy instantly to Railway: [![Deploy on Railway](https://railway.app/button.svg)](https://railway.com/template/10iW1q?referralCode=PpPFJd) Then query any chain by its EVM chain ID: ```bash curl 'http://localhost:4000/main/evm/42161' \ --header 'Content-Type: application/json' \ --data '{"method":"eth_blockNumber","params":[],"id":1,"jsonrpc":"2.0"}' ``` --- ### Free & Public RPCs — full agent reference ### How it works When a project has zero `providers`, zero `upstreams`, and no CLI `--endpoint` flags, eRPC logs a warning and auto-injects one provider before any request is processed: - **`repository` (id `public`)** — fetches `https://evm-public-endpoints.erpc.cloud` on first request for a chain and re-checks every hour. The catalog is a JSON map of `{ "": { "endpoints": [...] } }`. Each `http`/`https` entry becomes a separate upstream with `autoIgnoreUnsupportedMethods: true`; `wss`/`ws` entries are silently skipped. Upstream ids embed a redacted endpoint (`https#redacted=ab12c`) so no raw URLs appear in logs or metrics. On the first request for a chain, eRPC schedules a bootstrap task for the provider and waits up to 30 seconds (capped by the request deadline) polling every 200 ms until at least one upstream is ready. Subsequent requests on the same chain reuse the prepared upstreams. Failed bootstrap tasks are auto-retried with exponential backoff (factor 1.5, 3 s → 130 s). The hot-path data path is lock-free: the provider caches catalog data in a `RemoteDataCache` backed by an `atomic.Pointer`, so reads on warm chains involve no I/O and no mutex. ### Config schema The auto-injected provider is not configurable through YAML. Its exact defaults: | Field | Type | Auto-injected value | Behavior / footguns | |---|---|---|---| | `providers[].id` | string | `"public"` | Appears in upstream task names and metric labels. Do not reuse `"public"` if you later add explicit providers — id collisions cause undefined upstream selection behavior. | | `providers[].vendor` | string | `"repository"` | Selects the vendor integration. | | `providers[].settings` | map | `{}` (all vendor defaults) | Cannot be customized without opting out of auto-injection by explicitly adding a provider or upstream. | | `repository` › `repositoryUrl` | string | `"https://evm-public-endpoints.erpc.cloud"` | Remote JSON catalog. Non-integer chain id keys are silently skipped. Only `http`/`https` entries produce upstreams. | | `repository` › `recheckInterval` | duration | `1h` | Catalog freshness window. **YAML footgun**: the value is read with a Go `.(time.Duration)` type assertion; YAML decodes scalars to `string`/`int64`, so the assertion always fails silently and the 1 h default is used regardless of what you write. Only Go programmatic config (`common.VendorSettings{"recheckInterval": 1*time.Hour}`) can override it. | | `repository` › `autoIgnoreUnsupportedMethods` | bool | `true` | Public RPCs vary wildly in method support; unsupported-method errors are treated as permanent and that method is skipped on that upstream. | ### Worked examples **1. Prototyping on Arbitrum with no setup.** No config needed — just start and query: ```bash npx start-erpc # then curl 'http://localhost:4000/main/evm/42161' \ -d '{"method":"eth_getLogs","params":[{"fromBlock":"latest"}],"id":1,"jsonrpc":"2.0"}' ``` When using a human-readable alias in a project config, the URL shortens: ```yaml projects: - id: main networks: - id: evm:42161 alias: arbitrum # then: curl http://localhost:4000/main/arbitrum ``` **2. Switching to explicit providers once you have an API key.** Auto-injection turns off the moment any provider or upstream is present. To graduate from zero-config: ```yaml projects: - id: main providers: - id: alchemy vendor: alchemy settings: apiKey: ${ALCHEMY_KEY} ``` This disables `repository` auto-injection entirely. **3. Pointing `repository` at a private mirror (Go programmatic config only).** Because `recheckInterval` and `repositoryUrl` cannot be overridden from YAML, the only path that works is Go config: ```go providers: []common.ProviderConfig{{ Id: "custom-repo", Vendor: "repository", Settings: common.VendorSettings{ "repositoryUrl": "https://my-internal-catalog.example.com", "recheckInterval": 30 * time.Minute, }, }} ``` **4. Read-only chain fan-out behind Envio.** Envio HyperRPC covers 14 read methods for 61 well-known chains and needs an API token from [app.envio.dev](https://app.envio.dev/api-tokens). A workload heavy on `eth_getLogs` or `eth_getBlockReceipts` can add it next to the public catalog: ```yaml providers: - id: public vendor: repository - id: envio vendor: envio settings: apiKey: ${ENVIO_API_TOKEN} ``` ### Request/response behavior - URL path format: `POST ///` — e.g. `/main/evm/42161`. A human-readable network alias (`alias: arbitrum` in `networks[]`) makes the path `/main/arbitrum`. See [URL structure](/reference/evm/url-structure.llms.txt) for all accepted shapes. - Only `POST` and `OPTIONS` reach the proxy; any other method (`GET`, etc.) is silently treated as a healthcheck and returns a JSON health envelope, not a JSON-RPC response. - Responses carry standard `X-ERPC-*` headers (attempts, upstream, etc.) even on zero-config setups. - Unknown chain IDs return HTTP 404 with a JSON-RPC error body (`ErrNetworkNotSupported`) after all provider tasks complete without producing any upstream for that chain. ### Best practices - **Use zero-config only for development and prototyping.** Public endpoints have no SLA, unpredictable rate limits, and no authentication — not suitable for production traffic. - **Graduate to explicit providers before going live.** Adding a single `providers[]` entry disables auto-injection and gives you full resilience control. See [Providers](/config/projects/providers.llms.txt). - **Add auth and rate limits when exposing eRPC externally.** Zero-config has no per-project auth, no rate limiter, and no circuit-breaker budget configured on auto-injected upstreams. See [Auth](/config/auth.llms.txt) and [Rate limiters](/config/rate-limiters.llms.txt). - **Expect cold-start latency on first request per chain.** `repository` has no static fallback — the first request for a new chain may wait for the HTTP catalog fetch (retried with 3 s → 130 s backoff). Warm the chain before serving user traffic. - **Do not reuse provider id `"public"` in explicit configs.** It is reserved by the auto-injected repository provider; a collision causes upstream-id overlap. - **`recheckInterval` only works from Go programmatic config.** YAML silently ignores the value; the 1 h default always applies in YAML/TS setups. - **Monitor `erpc_upstream_request_total{vendor="repository"}` to spot slow public endpoints.** The `upstream` label carries the redacted endpoint id for drill-down without leaking URLs. ### Edge cases & gotchas 1. **Explicit `providers: []` in YAML still triggers auto-injection** if `upstreams` is also empty and no CLI `--endpoint` flags were passed. There is no YAML opt-out flag; you must add at least one explicit provider or upstream to disable it. Source: [`common/defaults.go:L1113-1115`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1113-L1115) 2. **`recheckInterval` from YAML is always silently ignored** — `VendorSettings` is a `map[string]interface{}`; YAML decodes duration strings/integers to `string`/`int64`, not `time.Duration`, so the `.(time.Duration)` type assertion fails and the vendor default is used. Only Go programmatic config can override it. Source: [`thirdparty/repository.go:L56-59`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L56-L59) 3. **`repository` catalog cold start is not instant** — first request for any chain may wait for the HTTP fetch (no static fallback). Source: [`thirdparty/repository.go:L61-64`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L61-L64) 4. **`wss`/`ws` endpoints in the repository catalog are silently skipped** — only `http`/`https` entries produce upstreams. Source: [`thirdparty/repository.go:L121-166`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L121-L166) 5. **Rate limits on public endpoints are uncontrolled** — no rate-limit budget or per-upstream circuit-breaker is configured on auto-injected upstreams. A misbehaving upstream will only be flagged once the upstream's circuit-breaker window fills (if a project-wide policy is configured). 6. **Provider id `"public"` is reserved** by the auto-injected repository provider. Adding an explicit provider with the same id causes upstream-id collisions; the upstream registry will deduplicate by id, silently merging them. Source: [`common/defaults.go:L1126-1133`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1126-L1133) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_total` | counter | `project, vendor, network, upstream, ...` | Every request forwarded to a repository upstream. `vendor` label is `"repository"`. | | `erpc_upstream_request_duration_seconds` | histogram | `project, vendor, network, upstream` | Latency of each upstream call; useful for spotting slow public endpoints. | | `erpc_selection_score` | gauge | `project, network, method, upstream` | Per-upstream score produced by the selection policy (`sortByScore`). Lower = better. | Notable log messages: - `warn: no providers or upstreams found in project; will use default 'public' endpoints repository` — fires at project setup when auto-injection triggers. - `debug: provider does not support network; skipping upstream creation` — fires when a chain is not in the catalog. - `warn: vendor remote-data refresh failed; keeping previous snapshot` — catalog fetch failed; previous data used. ### Source code entry points - [`common/defaults.go:L1113-L1142`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1113-L1142) — auto-injection conditions and injected provider construction (`len(providers)==0 && len(upstreams)==0 && no CLI endpoints`) - [`thirdparty/repository.go:L41-L92`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L41-L92) — `SupportsNetwork`, `autoIgnoreUnsupportedMethods` default, cold-start guard (`ErrRemoteCacheCold`) - [`thirdparty/repository.go:L121-L166`](https://github.com/erpc/erpc/blob/main/thirdparty/repository.go#L121-L166) — `GenerateConfigs` fan-out: one upstream per `http`/`https` endpoint, redacted ids - [`thirdparty/remote_cache.go:L13-L78`](https://github.com/erpc/erpc/blob/main/thirdparty/remote_cache.go#L13-L78) — `RemoteDataCache` design rationale: lock-free hot path, single-flight async refresh, copy-on-write - [`upstream/registry.go:L155-L293`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L155-L293) — lazy provider bootstrap, 30 s readiness wait, `ErrNetworkInitializing` / `ErrNetworkNotSupported` - [`util/initializer.go:L179-L182`](https://github.com/erpc/erpc/blob/main/util/initializer.go#L179-L182) — exponential retry parameters for failed bootstrap tasks (factor 1.5, 3 s → 130 s) - [`util/redact.go:L10-L36`](https://github.com/erpc/erpc/blob/main/util/redact.go#L10-L36) — endpoint redaction for repository upstream ids (`https#redacted=ab12c`) ### Related pages - [Providers](/config/projects/providers.llms.txt) — add explicit providers with API keys to replace zero-config. - [Auth](/config/auth.llms.txt) — add project-level authentication before exposing eRPC externally. - [Rate limiters](/config/rate-limiters.llms.txt) — protect public endpoints from overuse. - [Failsafe policies](/config/failsafe.llms.txt) — hedge, retry, timeout applied on top of any provider. - [URL structure & routing](/reference/evm/url-structure.llms.txt) — how `///` paths are parsed. --- --- # Quick start > Source: https://docs.erpc.cloud/ > Stop babysitting RPC providers. eRPC handles failover, caching, and multi-chain routing so your stack stays fast even when providers don't. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Introducing eRPC Stop babysitting RPC providers. eRPC sits in front of every upstream you have — Alchemy, QuickNode, your own node, anything — and handles failover, retries, response caching, and multi-chain routing automatically. One URL pattern, every EVM chain, zero provider lock-in. ## Quick start ### Write a minimal config Create `erpc.yaml` in the current directory: ```yaml # erpc.yaml — minimal single-project config logLevel: info projects: - id: main upstreams: - id: my-alchemy endpoint: https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY ``` Prefer TypeScript for full type safety and closures in selection policies: ```ts // erpc.ts export default createConfig({ logLevel: "info", projects: [ { id: "main", upstreams: [ { id: "my-alchemy", endpoint: "https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY" }, ], }, ], }); ``` See the [example config](/config/example.llms.txt) for a production-ready starting point, including YAML vs. TypeScript tradeoffs. ### Run with Docker Mount the config file and expose the RPC and metrics ports: ```bash docker run \ -v $(pwd)/erpc.yaml:/erpc.yaml \ -p 4000:4000 \ -p 4001:4001 \ ghcr.io/erpc/erpc:latest ``` Or with `npx` (requires Node 18+): ```bash npx @erpc-cloud/cli start ./erpc.yaml ``` The server listens on `4000` for JSON-RPC traffic and `4001` for Prometheus metrics. ### Send a request ```bash curl -s http://localhost:4000/main/evm/1 \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` URL pattern: `///`. Use `/main/evm/42161` for Arbitrum, `/main/evm/137` for Polygon — no config change needed to add a chain if your upstream supports it. ### Validate your config (optional) ```bash docker run --rm -v $(pwd)/erpc.yaml:/erpc.yaml ghcr.io/erpc/erpc:latest validate ``` Exits 0 when config is valid; prints a structured JSON report with `errors`, `warnings`, and `notices` on any issue. ### Bring up monitoring (optional) The repo ships a combined Prometheus + Grafana container with an 80+ panel dashboard pre-loaded: ```bash git clone https://github.com/erpc/erpc.git && cd erpc docker-compose up -d ``` Grafana opens at [http://localhost:3000](http://localhost:3000) (admin / admin). Prometheus scrapes eRPC at `host.docker.internal:4001` every 10 seconds. ![eRPC Grafana Dashboard](/assets/monitoring-example-erpc.png.llms.txt) --- ### eRPC homepage — full agent reference ### How it works eRPC is a fault-tolerant EVM RPC proxy and permanent caching layer. The bootstrap sequence: config file (YAML, TypeScript, or JavaScript) is loaded and validated, then the engine initialises database connectors, rate limiters, the ERPC core, HTTP/gRPC transports, metrics, and tracing — all bound to a context that cancels on SIGINT/SIGTERM for graceful drain. **Config discovery order** (no `--config` flag needed): `./erpc.yaml`, `./erpc.yml`, `./erpc.ts`, `./erpc.js`, `/erpc.yaml`, `/erpc.yml`, `/erpc.ts`, `/erpc.js`, `/root/erpc.yaml`, `/root/erpc.yml`, `/root/erpc.ts`, `/root/erpc.js` — first match wins. **URL routing**: `///`. Domain aliasing and per-network aliases let you shorten this — e.g. `/main/arbitrum` instead of `/main/evm/42161`. Unknown projects return HTTP 404; invalid architecture returns HTTP 400, both as JSON-RPC envelopes. **TypeScript configs** are compiled in-process via esbuild (IIFE bundle) and evaluated with the sobek JS runtime, so closures and module-level helpers in selection-policy `evalFunc` functions are preserved natively — no function serialisation. **No-config mode**: when `projects` is empty, a synthetic `main` project with public repository provider is injected, and `/evm/` resolves without a project prefix. ### Config schema See individual feature pages for per-field tables. Top-level keys: `logLevel`, `clusterKey`, `server`, `healthCheck`, `admin`, `database`, `projects`, `rateLimiters`, `metrics`, `proxyPools`, `tracing`. Key environment variables: | Variable | Effect | |---|---| | `LOG_LEVEL` | Override `logLevel` at runtime without a config edit | | `LOG_WRITER=console` | Switch from JSON logs to human-readable output (dev only) | | `GOMEMLIMIT` | Not set by default — set to ~90% of container memory limit to avoid OOM kills | ### Best practices - Use TypeScript (`erpc.ts`) over YAML for any config that needs selection-policy closures or env-var helpers. - Always run `erpc validate` in CI before deploying — it exits non-zero on errors and prints a structured JSON report. - Set `GOMEMLIMIT` in your Kubernetes pod spec (e.g. `2700MiB` for a 3Gi limit). The kube manifest ships without it, which can cause OOM kills under load. - Pin a specific image tag (e.g. `ghcr.io/erpc/erpc:v0.x.y`) rather than `:latest` in production. - For the combined Prometheus+Grafana monitoring container: it is a single-process convenience for local dev. Run Prometheus and Grafana as separate services in production. - Quote YAML values that contain environment variable references: `password: "${REDIS_PASSWORD}"` — bare `${VAR}` with special characters can break YAML parsing before the variable is even read. ### Edge cases & gotchas - **`--set` / `-s` is not implemented.** Passing `-s logLevel=debug` produces a CLI framework error. Use `LOG_LEVEL=debug` instead. - **`erpc dump --format csv`** (or any unknown format) exits 1 with a clear error — only `yaml`, `yml`, and `json` are valid. - **`validate` and `dump` suppress all log output** via a global zerolog disable before config loading. If a failure is hard to diagnose, pipe stdout through `jq .errors` — warnings from `SetDefaults` are silenced and won't appear on stderr. - **`.env` is loaded before CLI parsing**: variables in a local `.env` file are available for `${VAR}` substitution in YAML configs. - **`GET //evm/`** is a healthcheck, not an error — any non-POST/non-OPTIONS method on a proxy path is silently treated as a network-scoped health probe. - **`docker-compose down --volumes`** (via `make down`) destroys `prometheus_data` and `grafana_data`. Use `docker compose down` without `--volumes` to preserve monitoring state. ### Observability Port `4001` exposes Prometheus metrics. The repo's monitoring container bundles a pre-built Grafana dashboard (`monitoring/grafana/dashboards/erpc.json`, 80+ panels) covering request rates, latency, failover events, consensus, cache, selection policy, and block-head lag. Five built-in alert rules: `HighErrorRate` (upstream error rate >5% for 5 min), `SlowRequests` (p95 >1s), `HighRateLimiting`, `NetworkRateLimiting`, `HighRequestRate` / `LowRequestRate`. ### Source code entry points - [`cmd/erpc/main.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go) — CLI entry point: config discovery, `start`/`validate`/`dump` subcommands, env-var overrides - [`erpc/init.go`](https://github.com/erpc/erpc/blob/main/erpc/init.go) — full startup orchestration: log level, database init, ERPC core, transports, graceful drain - [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go) — `Config` struct, `LoadConfig`, TypeScript compilation pipeline - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) — `SetDefaults`, synthetic project injection, vendor shorthand URL parsing - [`erpc/http_server.go:L810-L1006`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L810-L1006) — `parseUrlPath`: full routing state machine - [`kube/erpc.yml`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml) — Kubernetes Namespace + Deployment + ConfigMap + Service + PodMonitor - [`monitoring/grafana/dashboards/erpc.json`](https://github.com/erpc/erpc/blob/main/monitoring/grafana/dashboards/erpc.json) — pre-built Grafana dashboard ### Related pages - [How eRPC works](/use-cases/how-it-works.llms.txt) — request lifecycle, failsafe layers, and caching in one diagram - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — automatic failover in action - [Cut costs and latency](/use-cases/cut-costs-and-latency.llms.txt) — permanent EVM JSON-RPC cache - [Scale chains and providers](/use-cases/scale-chains-and-providers.llms.txt) — multi-upstream routing and scoring - [Resilience config](/config/failsafe.llms.txt) — retry, hedge, timeout, circuit breaker, consensus - [Full machine-readable reference](/llms.txt.llms.txt) — `/llms.txt` for LLM agents and tooling --- --- # Admin API > Source: https://docs.erpc.cloud/operation/admin > A built-in operator control plane — inspect topology, cordon sick upstreams without restarts, purge JSON-RPC cache entries, and manage API keys, all over a secure JSON-RPC 2.0 endpoint. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Admin API eRPC ships a live control plane at `POST /admin` — completely separate from your consumer endpoints. Without touching config files or restarting the server, you can inspect the running topology, instantly pull a misbehaving upstream out of rotation, and manage API keys stored in your database connector. **What you get:** - Runtime introspection of every project, network, and upstream - One-call cordon/uncordon to remove an upstream from traffic without a deploy - Admin cache purge (`erpc_purgeCache`) with dry-run match counts across connectors - API key provisioning backed by any database connector - `erpc validate` CLI to catch config errors before they reach production ## Quick taste Illustrative, not a tuned production config — secret-token auth on the admin endpoint: **Config path:** `admin` **YAML — `erpc.yaml`:** ```yaml admin: auth: strategies: # secret token — pass as x-erpc-secret-token header on every admin request - type: secret secret: value: "your-admin-secret" ``` **TypeScript — `erpc.ts`:** ```typescript admin: { auth: { strategies: [{ // secret token — pass as x-erpc-secret-token header on every admin request type: "secret", secret: { value: "your-admin-secret" }, }], }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: secure and enable the admin endpoint** ```text Enable the eRPC admin control plane in my eRPC config with secret-token auth and locked-down CORS so only my internal dashboard can reach it. Explain what happens if admin.auth is missing vs the entire admin block being absent. Read the full reference first: https://docs.erpc.cloud/operation/admin.llms.txt ``` **Prompt Example #2: cordon a degraded upstream without a redeploy** ```text One of my upstreams is returning elevated errors right now. Show me the exact admin API curl commands to cordon it immediately for all methods, verify the cordon took effect, and restore it when the vendor recovers. My eRPC admin endpoint is at https://erpc.example.com/admin. Reference: https://docs.erpc.cloud/operation/admin.llms.txt ``` **Prompt Example #3: add erpc validate to my CI pipeline** ```text I want to run erpc validate in CI to catch config errors before they reach production. Show me the correct command, how to parse the JSON output as a deployment blocker, and how to skip live endpoint checks in local dev. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/admin.llms.txt ``` **Prompt Example #4: provision and revoke consumer API keys at runtime** ```text My project uses database-backed auth and I need to add, list, and revoke consumer API keys via the admin API without touching config files. Show me the correct erpc_addApiKey / erpc_listApiKeys / erpc_deleteApiKey calls and explain the connectorId vs admin auth difference. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/admin.llms.txt ``` --- ### Admin API — full agent reference ### How it works Any `POST` or `OPTIONS` request whose path has exactly one segment equal to `"admin"` is routed to the admin endpoint by `parseUrlPath`. The handler first applies admin-specific CORS from `admin.cors` — OPTIONS preflights return 204 immediately, before any auth evaluation. For non-OPTIONS requests an `AuthPayload` is built from HTTP headers, then `AdminAuthenticate` is called against `adminAuthRegistry`. On success, `AdminHandleRequest` switch-dispatches on the JSON-RPC method name. Unrecognized methods produce `ErrEndpointUnsupported`. Two distinct failure modes exist for misconfigured admin. If the entire `admin:` block is absent, every request returns `"admin is not enabled for this project"` (HTTP 401) and OPTIONS also fails with 401 (the CORS block is skipped). If `admin:` is present but `admin.auth:` is omitted, requests return `"admin auth not configured"`. Both are HTTP 401 but require different fixes. `adminAuthRegistry` is built at startup inside `NewERPC` using `auth.NewAuthRegistry` — the same factory as project consumer auth. All strategy types are supported: `secret`, `jwt`, `siwe`, `network`, `database`. Most deployments use a single `type: secret` strategy. The API key management methods (`erpc_addApiKey` etc.) are authenticated by the admin auth registry but operate on connectors belonging to the project's consumer auth. The `connectorId` parameter must match a `database` strategy connector on the named project's consumer auth config, not on the admin config. CORS for the admin endpoint defaults to `allowedOrigins: ["*"]` with `allowCredentials: false` because the endpoint is gated by secret tokens. The full default set — `allowedMethods: ["GET","POST","OPTIONS"]`, `allowedHeaders: ["content-type","authorization","x-erpc-secret-token"]`, `maxAge: 3600` — is auto-synthesised at startup when no `admin.cors` block is present. ### Config schema All fields are under the top-level `admin:` key. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `admin` | `*AdminConfig` | `nil` (absent) | When nil, every `POST /admin` returns 401 "admin is not enabled for this project". OPTIONS preflight also returns 401 — the CORS block is skipped. Source: [`erpc/http_server.go:L586-L610`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L586-L610) | | `admin.auth` | `*AuthConfig` | `nil` | When nil, `adminAuthRegistry` is nil and every request returns "admin auth not configured". Source: [`erpc/admin.go:L26-L30`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L26-L30) | | `admin.auth.strategies` | `[]*AuthStrategyConfig` | `[]` | Supports `secret`, `jwt`, `siwe`, `network`, `database`. Most deployments use `type: secret`. | | `admin.cors` | `*CORSConfig` | auto-synthesised: `{allowedOrigins: ["*"], allowCredentials: false}` | Admin-specific CORS; project-level CORS is never consulted for `/admin`. Intentionally defaults to `*` because the endpoint is token-gated. Source: [`common/defaults.go:L775-L784`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L775-L784) | | `admin.cors.allowedOrigins` | `[]string` | `["*"]` | Override in production, e.g. `["https://dashboard.example.com"]`. | | `admin.cors.allowedMethods` | `[]string` | `["GET", "POST", "OPTIONS"]` | Set by `CORSConfig.SetDefaults`. Source: [`common/defaults.go:L2828-L2829`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2828-L2829) | | `admin.cors.allowedHeaders` | `[]string` | `["content-type", "authorization", "x-erpc-secret-token"]` | The third entry is the standard header for eRPC secret-token strategies. Source: [`common/defaults.go:L2831-L2836`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2831-L2836) | | `admin.cors.exposedHeaders` | `[]string` | `nil` | Never set by defaults. When nil, `Access-Control-Expose-Headers` is omitted. Set explicitly if browser clients need to read custom eRPC response headers. | | `admin.cors.allowCredentials` | `*bool` | `false` (pointer) | Must stay `false` when `allowedOrigins: ["*"]` per CORS spec. Source: [`common/defaults.go:L2838-L2840`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2838-L2840) | | `admin.cors.maxAge` | `int` | `3600` | Preflight cache duration in seconds. `Access-Control-Max-Age` is emitted when `> 0`. Source: [`common/defaults.go:L2841-L2843`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2841-L2843) | | `admin.denyMethods` | `[]string` (wildcard) | `nil` | Blocks matching admin JSON-RPC methods after auth, before the handler runs — an unauthenticated request fails auth first, so method availability is never leaked. Wildcards (`*`, `?`) and boolean operators (`\|`, `&`, `!`) are supported. A blocked method returns JSON-RPC error `-32601` ("method not supported"). Evaluated before `allowMethods`. | | `admin.allowMethods` | `[]string` (wildcard) | `nil` | When set, only matching methods are served; all others are blocked. Also re-admits a method blocked by `denyMethods`. Example: `allowMethods: ["erpc_list*"]` restricts the admin endpoint to read-only list methods. | ### Worked examples **1. Secret-token admin endpoint (minimal production setup).** Lock down the control plane with a static shared secret; override `allowedOrigins` to match your internal dashboard origin: **Config path:** `admin` **YAML — `erpc.yaml`:** ```yaml admin: auth: strategies: - type: secret secret: value: "changeme-use-env-var" cors: allowedOrigins: - "https://ops.example.com" ``` **TypeScript — `erpc.ts`:** ```typescript admin: { auth: { strategies: [{ type: "secret", secret: { value: "changeme-use-env-var" }, }], }, cors: { allowedOrigins: ["https://ops.example.com"] }, } ``` **2. Cordon a degraded upstream without a restart.** When a provider is returning elevated errors but hasn't fully failed, you can remove it from routing immediately: ```sh # Cordon for all methods curl -X POST https://erpc.example.com/admin \ -H "x-erpc-secret-token: changeme-use-env-var" \ -H "content-type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"erpc_cordonUpstream", "params":[{"projectId":"myProject","upstream":"alchemy-mainnet","reason":"elevated 5xx"}]}' # Verify curl ... -d '{"jsonrpc":"2.0","id":2,"method":"erpc_listCordoned", "params":[{"projectId":"myProject"}]}' # Restore when provider recovers curl ... -d '{"jsonrpc":"2.0","id":3,"method":"erpc_uncordonUpstream", "params":[{"projectId":"myProject","upstream":"alchemy-mainnet"}]}' ``` **3. Validate config in CI.** Run `erpc validate` before deploying to catch chain-ID mismatches, orphan rate-limit budgets, and missing failsafe policies: ```sh erpc validate --config ./erpc.yaml --format json # exits 0 = clean, 1 = errors # skip live checks for local dev nodes: ERPC_IGNORE_LOCAL_ENDPOINT_VALIDATION=true erpc validate --config ./erpc.yaml ``` **4. Provision an API key via admin (requires a database auth connector on the project).** Add, list, and revoke consumer API keys without any code deploys: ```sh # Add curl ... -d '{"jsonrpc":"2.0","id":1,"method":"erpc_addApiKey","params":[{ "projectId":"myProject","connectorId":"my-dynamodb","apiKey":"sk_abc123", "userId":"user-42","rateLimitBudget":"standard"}]}' # List (paginated, default limit 50) curl ... -d '{"jsonrpc":"2.0","id":2,"method":"erpc_listApiKeys","params":[{ "projectId":"myProject","connectorId":"my-dynamodb"}]}' # Delete curl ... -d '{"jsonrpc":"2.0","id":3,"method":"erpc_deleteApiKey","params":[{ "projectId":"myProject","connectorId":"my-dynamodb","apiKey":"sk_abc123"}]}' ``` ### Request/response behavior #### Transport - **URL**: `POST /admin` (single path segment; no project/network/chain segments). - **Envelope**: JSON-RPC 2.0 — `{"jsonrpc":"2.0","id":,"method":"","params":[...]}`. - **Auth**: evaluated per-request before dispatch. Failure → HTTP 401 JSON-RPC error. - **Batch**: a JSON array body fans out to per-method goroutines, each independently authenticated. - **OPTIONS preflight**: returns 204 before auth is evaluated; uses `admin.cors` exclusively. --- #### `erpc_taxonomy` **Params**: none. **Response**: ```json { "projects": [ { "id": "myProject", "networks": [ { "id": "evm:1", "alias": "ethereum", "upstreams": [{"id": "alchemy-mainnet", "vendor": "alchemy"}], "providers": [] } ] } ] } ``` Lists all loaded projects, their networks (with aliases if configured), and per-network upstreams with vendor name. `vendor` is empty string when no vendor is detected. The `providers` field is present in the response struct but is always an empty array in the current implementation — only `upstreams` is populated. Source: [`erpc/admin.go:L474-L541`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L474-L541) --- #### `erpc_config` **Params**: none. **Response**: full `*common.Config` struct as JSON. Sensitive `secret.value` fields are replaced with `"REDACTED"` by `SecretStrategyConfig.MarshalJSON`. Source: [`erpc/admin.go:L456-L471`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L456-L471) --- #### `erpc_project` **Params**: `[""]` **Response**: ```json { "config": {}, "health": { "upstreams": [], "initialization": {} } } ``` `config` is the current `*ProjectConfig` including lazy-loaded networks. `health.upstreams` is the live list from `UpstreamsRegistry.GetUpstreamsHealth()` with metrics and cordon state. `health.initialization` reflects the network initializer status. Returns `ErrInvalidRequest` if param is missing or not a string. Source: [`erpc/admin.go:L544-L588`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L544-L588) --- #### `erpc_addApiKey` **Params**: `[{"projectId": string, "connectorId": string, "apiKey": string, "userId": string, "rateLimitBudget"?: string, "enabled"?: bool}]` `enabled` defaults to `true` when omitted. `connectorId` must match a `database` strategy connector in the **project's consumer auth config** (not admin auth). Source: [`erpc/admin.go:L102-L192`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L102-L192) **Response**: ```json {"success": true, "apiKey": "", "userId": ""} ``` --- #### `erpc_listApiKeys` **Params**: `[{"projectId": string, "connectorId": string, "limit"?: number, "paginationToken"?: string}]` `limit` defaults to `50`. `paginationToken` is the opaque `nextToken` from a previous response. Source: [`erpc/admin.go:L195-L291`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L195-L291) **Response**: ```json { "apiKeys": [ { "key": "abc123", "userId": "user1", "rateLimitBudget": "standard", "enabled": true, "createdAt": "", "updatedAt": "" } ], "nextToken": "", "hasMore": true, "totalReturned": 50 } ``` **Footgun**: `createdAt`/`updatedAt` are always `time.Now()` — actual creation timestamps are not stored. --- #### `erpc_updateApiKey` **Params**: `[{"projectId": string, "connectorId": string, "apiKey": string, "updates": object}]` Applies patch semantics: `null` values in `updates` delete fields from the stored blob; non-null values overwrite. No schema enforcement — any JSON field can be added. Source: [`erpc/admin.go:L294-L381`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L294-L381) **Response**: ```json {"success": true, "apiKey": "", "updated": {/* mirror of the updates object passed in */}} ``` --- #### `erpc_deleteApiKey` **Params**: `[{"projectId": string, "connectorId": string, "apiKey": string}]` Fetches the current record to retrieve `userId` (range key for deletion), then calls `connector.Delete`. Source: [`erpc/admin.go:L384-L453`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L384-L453) **Response**: ```json {"success": true, "apiKey": "", "userId": ""} ``` --- #### `erpc_cordonUpstream` **Params**: `[{"projectId": string, "upstream": string, "method"?: string, "reason"?: string}]` `method` defaults to `"*"` (all methods). `reason` defaults to `"admin: manual cordon"`. The `"*"` scope is a shared counter in `database.sharedState`: with a remote connector every replica applies it (milliseconds on Redis) and it survives restarts; with the `memory` driver it is in-process only. A method scope stays on this replica. See [Cordoning](/operation/cordoning.llms.txt). Source: [`erpc/admin.go:L656-L694`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L656-L694) **Response**: ```json {"projectId": "...", "upstream": "...", "method": "*", "cordoned": true, "reason": "admin: manual cordon"} ``` --- #### `erpc_uncordonUpstream` **Params**: `[{"projectId": string, "upstream": string, "method"?: string, "reason"?: string}]` `method` defaults to `"*"`. `reason` defaults to `"admin: manual uncordon"` (different string from `erpc_cordonUpstream`); it is used only for the automatic cordon this call also lifts on this replica. Source: [`erpc/admin.go:L656-L694`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L656-L694) **Response**: ```json {"projectId": "...", "upstream": "...", "method": "*", "cordoned": false, "reason": "admin: manual uncordon"} ``` --- #### `erpc_listCordoned` **Params**: `[{"projectId": string}]` **Footgun**: only reports upstreams cordoned for `"*"` (whole-upstream, operator or automatic). Method-scoped cordons (e.g. cordon only for `eth_getLogs`) are invisible to this method. Use the `erpc_upstream_cordoned` metric with the `reason` label to track method-scoped cordons. On replicas other than the one that took the call the reason reads `"operator cordon (set on another replica)"`. Source: [`erpc/admin.go:L696-L736`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L696-L736) **Response**: ```json { "projectId": "myProject", "cordoned": [ {"upstream": "alchemy-mainnet", "reason": "admin: manual cordon"} ] } ``` --- #### `erpc_purgeCache` **Params**: `[{"projectId": string, "networkId": string, "method"?: string, "blockRef"?: string, "dryRun"?: bool, "confirm"?: string}]` Purges JSON-RPC cache entries for a network (or every network in the project when `networkId` is `"*"`). Prefer `dryRun: true` first — it returns match counts and deletes nothing. `networkId: "*"` requires `confirm: "WIPE"` and is rejected with 4xx before any store is touched. Optional `method` / `blockRef` narrow the partition/range key patterns. Patterns are built with `CachePartitionKey` using each network's configured `cacheKeySuffix` (never from API params). Gateable via `admin.denyMethods` / `admin.allowMethods`. Source: [`erpc/admin.go`](https://github.com/erpc/erpc/blob/main/erpc/admin.go) (`handlePurgeCache`) **Response**: ```json { "projectId": "main", "scope": {"networkId": "evm:1", "cacheKeySuffix": "systx", "method": "", "blockRef": ""}, "dryRun": false, "connectors": [ {"connectorId": "redis-cache", "driver": "redis", "matched": 128, "deleted": 128, "durationMs": 940} ], "totalDeleted": 128 } ``` Unsupported connectors are reported per-row (`unsupported` / `error` fields); other connectors still purge. Remote connectors (Redis, DynamoDB, PostgreSQL) are fleet-wide; the `memory` driver only affects the replica that handled the call. --- #### `erpc validate` CLI ```sh erpc validate --config [--format json|md] ``` Default format: `json`. Exit code 0 = clean; exit code 1 = errors present or config load failed. Logs are suppressed during validation. Set `ERPC_IGNORE_LOCAL_ENDPOINT_VALIDATION=true` to skip live checks for local/private endpoints. An endpoint is considered local when its hostname is `localhost`, `127.0.0.1`, `::1`, matches `*.cluster.local`, or resolves to a private-range IP address. Source: [`erpc/config_analyzer.go:L28-L59`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L28-L59) **Static checks** — orphan rate-limit budgets, budgets used without `rateLimitAutoTune`, networks missing failsafe policies, upstreams with empty endpoints, invalid `metrics.histogramBuckets`. **Live upstream checks** — up to 50 concurrent goroutines per project, each with a 5s timeout and 3 retries. For every upstream: fetches `eth_chainId` (mismatch vs config → error), genesis block hash (skipped for `evm.nodeType: full` or `maxAvailableRecentBlocks > 0`), and a stable historical block hash (`min(finalized) - 64`, falling back to `min(latest) - 1024`). Within each project/chain group, majority voting flags upstreams that disagree with ≥2-of-≥3 consensus as errors; smaller samples produce warnings. **`ValidationReport` JSON schema**: ```json { "errors": [], "warnings": [], "notices": [], "resources": { "totals": { "projectsTotal": 2, "networksTotal": 5, "upstreamsTotal": 12, "rateLimitBudgetsTotal": 3 }, "tree": { "projects": [ { "id": "myProject", "networks": [ { "id": "evm:1", "alias": "ethereum", "upstreams": [{"id": "alchemy-mainnet"}] } ] } ], "rateLimiters": { "budgets": [{"id": "standard", "rulesCount": 2}] } } } } ``` Source: [`cmd/erpc/main.go:L97-L142`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L97-L142), [`erpc/config_analyzer.go:L76-L123`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L76-L123) ### Best practices - Always set a real `admin.auth.strategies` entry — running without admin auth means the endpoint is unauthenticated. - Override `admin.cors.allowedOrigins` to a specific origin (e.g. your internal dashboard URL) when the admin endpoint is reachable from a browser; the default `"*"` is safe only when the endpoint is not browser-accessible. - Use method-scoped cordons (`"method": "eth_getLogs"`) to surgically remove an upstream from expensive calls while keeping it available for others — but remember they stay on one replica and `erpc_listCordoned` will not show them; monitor via `erpc_upstream_cordoned` metric. - Cordons reach every replica and survive restarts only with a remote `database.sharedState` connector. For permanent upstream removal, update config and redeploy. Cordons are a break-glass tool for transient degradations. - Run `erpc validate` in CI with `--format json` and parse the exit code. Treat any `errors` entry as a deployment blocker. Use `ERPC_IGNORE_LOCAL_ENDPOINT_VALIDATION=true` in local dev to skip live checks that will fail against localhost URLs. - Do not store the admin secret in the config file directly — inject it via an environment variable reference or a secrets manager so it stays out of version control. ### Edge cases & gotchas 1. **Two distinct "admin not available" errors.** `admin:` absent → `"admin is not enabled for this project"`. `admin:` present but `admin.auth:` absent → `"admin auth not configured"`. Both return HTTP 401 but require different fixes. Source: [`erpc/http_server.go:L586-L610`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L586-L610), [`erpc/admin.go:L26-L30`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L26-L30) 2. **`admin:` absent + OPTIONS = 401 not 204.** The CORS block requires `s.adminCfg != nil`. A browser-based admin dashboard won't work until an `admin:` block is present in config, even if only to enable preflight. 3. **Automatic and method-scoped cordons are per pod.** A consensus sit-out, chain-identity cordon or `method`-scoped cordon exists only on the replica that set it. Whole-upstream operator cordons are fleet-wide, and a whole-upstream `erpc_uncordonUpstream` lifts automatic wildcard cordons on every replica too. 4. **API key methods target the project's consumer auth connector, not admin auth.** The `connectorId` must exist in the project's consumer `auth.strategies[].database.connector` config. Source: [`erpc/admin.go:L82-L100`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L82-L100) 5. **`erpc_listApiKeys` timestamps are always `time.Now()`.** `createdAt`/`updatedAt` do not reflect actual creation or modification time — timestamps are not stored in the connector. Source: [`erpc/admin.go:L257-L259`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L257-L259) 6. **`erpc_updateApiKey` uses patch semantics.** `null` in `updates` deletes the field; non-null overwrites. No schema validation; any JSON field name is accepted. Source: [`erpc/admin.go:L351-L357`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L351-L357) 7. **Cordon persistence depends on `database.sharedState`.** Remote connector: one shared counter per upstream, propagated by the connector's pub/sub or reconcile loop and restored at bootstrap. Memory driver: in-process only, lost on restart. Source: [`upstream/upstream.go:L1503-L1567`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1503-L1567) 8. **Config validator genesis check is skipped for full nodes.** `evm.nodeType: full` or `evm.maxAvailableRecentBlocks > 0` suppresses genesis hash fetching since full nodes may not retain block 0. Source: [`erpc/config_analyzer.go:L400-L403`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L400-L403) 9. **Config validator groups by resolved chain ID.** If `eth_chainId` fails, the upstream is grouped under `"unknown"`. Two `"unknown"` upstreams skip cross-comparison to avoid false positives from different chains. The config-declared chain ID is used as a fallback grouping key when the live fetch fails. Source: [`erpc/config_analyzer.go:L449-L489`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L449-L489) 10. **Config validator uses `finalized - 64` for historical hash comparison.** Falls back to `latest - 1024` when finalized is unsupported. This avoids reorg false-positives. Source: [`erpc/config_analyzer.go:L589-L631`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L589-L631) 11. **Block heatmap `category` label uses the full JSON-RPC method name.** High-cardinality method sets significantly increase the number of time-series written to your metrics store. 12. **`eth_blockNumber` always emits bucket label `"TIP"` and `finality="Realtime"`.** No block number extraction occurs for this method; it is special-cased as a direct TIP/Realtime emit in `recordEvmBlockRangeHeatmap`. Source: [`erpc/block_heatmap.go:L37-L40`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L37-L40) 13. **CORS `exposedHeaders` is never set by defaults.** If browser clients need to read custom eRPC response headers, `admin.cors.exposedHeaders` must be set explicitly. 14. **Batched admin requests fan out to per-method goroutines.** Each goroutine independently authenticates. A failed auth on one method in a batch does not block the others. Source: [`erpc/http_server.go:L404-L427`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L404-L427) 15. **Block heatmap bucket start is always size-aligned.** `start = (blockNumber / size) * size` (integer floor-division). Two requests for blocks N and N+1 that straddle a size boundary land in different buckets. Source: [`erpc/block_heatmap.go:L91-L178`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L91-L178) 16. **Block heatmap tip-unknown fallback.** When `tip ≤ 0`, `ComputeBlockHeatmapBucket` returns `size = 0`; the caller falls back to `telemetry.EvmBlockRangeBucketSize` (default `100000`) and formats absolute bucket labels. Source: [`erpc/block_heatmap.go:L63-L72`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L63-L72) 17. **`erpc_purgeCache` memory driver is per-replica.** Remote connectors purge fleet-wide in one call; `memory` only clears the pod that received the admin request. Documented in the method response row via `driver: "memory"`. 18. **Unsuffixed purge must not delete `cacheKeySuffix` siblings.** `SCAN evm:1:*` also matches `evm:1:systx:…` on a shared Redis. When the network has no suffix, the connector post-filters to the unsuffixed partition shape (escaped `:` in block refs still count as unsuffixed). Suffixed networks use the tighter `{networkId}:{suffix}:*` pattern. 19. **Tip-tag `blockRef` values after chain-tracker tip resolution.** Prefer purging by `networkId` ± `method`, or a concrete decimal block number — not `blockRef: "latest"` / `"finalized"` once tip tags resolve to numbers in the partition key. Soft invalidation on reorg is not key deletion; ops purge remains required for intentional wipes. 20. **`networkId: "*"` without `confirm: "WIPE"` is rejected before any store touch.** Unsupported connectors surface per-row; other connectors still purge. 21. **`networkId: "*"` only covers networks already bootstrapped on this replica.** `GetNetworks()` returns in-memory prepared networks — keys written for networks only ever loaded on other pods (or before a restart) are not scanned. Prefer an exact `networkId` when possible. 22. **`blockRef`-scoped purge skips `rvi#` companions.** Reverse-index keys are network-wide wildcards; deleting them for one block would wipe companions for every block. Dangling companions resolve to a miss on Get. ### Block heatmap algorithm `ComputeBlockHeatmapBucket(blockNumber, tip, blockRef)` produces the `bucket` and `size` label values for `erpc_network_evm_block_range_requested_total`. Key details: **`selectDynamicBucketSize` — distance from tip → bucket size:** | Distance from tip | Bucket size | |---|---| | ≤ 1,000 | 100 | | ≤ 5,000 | 1,000 | | ≤ 20,000 | 5,000 | | ≤ 50,000 | 10,000 | | ≤ 100,000 | 30,000 | | ≤ 300,000 | 50,000 | | ≤ 1,000,000 | 100,000 | | ≤ 10,000,000 | 1,000,000 | | ≤ 30,000,000 | 10,000,000 | | ≤ 100,000,000 | 50,000,000 | | > 100,000,000 | 50,000,000 | Source: [`erpc/block_heatmap.go:L91-L178`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L91-L178) **Label selection (first match wins):** - `blockRef == "latest"` → `"LATEST"` - `blockRef == "finalized"` → `"FINALIZED"` - `blockRef == "safe"` → `"SAFE"` - `blockRef == "pending"` → `"PENDING"` - `|blockNumber - tip| ≤ 4` → `"TIP"` (±4 block tolerance) - `blockNumber > tip + 4` → `"FUTURE"` - Near-tip zone (`tip - start ≤ 5,000,000`): - If `end == tip`: `"L"` (e.g. `"L100k"`) - Otherwise: `"L-L"`; if `roundedEnd == 0` the `-L0` suffix is omitted - Beyond 5M blocks from tip: absolute `"-"` using k/m/b suffixes (size < 1M → thousands, < 1B → millions, else billions) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_evm_block_range_requested_total` | counter | `project`, `network`, `vendor`, `upstream`, `category`, `user`, `finality`, `bucket`, `size` | Every successfully-forwarded EVM request. `bucket` = label like `"TIP"`, `"L100k"`, `"119m-120m"`. `size` = numeric bucket size as string. Source: [`telemetry/metrics.go:L724-L728`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L724-L728) | | `erpc_upstream_cordoned` | gauge | `project`, `vendor`, `network`, `upstream`, `category`, `reason` | Set to 1 on cordon, 0 on uncordon. Source: [`telemetry/metrics.go:L164-L168`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L164-L168) | | `erpc_upstream_cordon_duration_seconds` | histogram | `project`, `network`, `upstream` | Recorded on uncordon: time spent in cordoned state. Buckets 1–86400 seconds. Source: [`telemetry/metrics.go:L299`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L299) | | `erpc_admin_cache_purge_total` | counter | `project`, `network`, `connector`, `result` | Per-connector outcome of `erpc_purgeCache`. `result` ∈ {`ok`, `dry_run`, `unsupported`, `error`}. Audit log lines use `component=admin` with projectId, networkId, method, blockRef, dryRun, connectorId, matched, deleted, durationMs, actor, suffix. | No dedicated trace spans for admin methods. The HTTP server's standard OTel server span covers the entire request. The `component=admin` logger is used for all admin requests. The config analyzer uses a silent `zerolog.New(io.Discard)` logger during live upstream checks so that ephemeral upstream probes do not pollute CLI output. Source: [`erpc/config_analyzer.go:L282`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L282) ### Source code entry points - [`erpc/admin.go:L38-L65`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L38-L65) — `AdminHandleRequest`: switch-dispatch on method name (includes `erpc_purgeCache`) - [`common/cache_dal.go`](https://github.com/erpc/erpc/blob/main/common/cache_dal.go) — optional `CachePurger` / `CachePurgeScope` (does not extend `CacheDAL`) - [`data/pattern_delete.go`](https://github.com/erpc/erpc/blob/main/data/pattern_delete.go) — purge pattern builders + connector walk - [`erpc/http_server.go:L835-L838`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L835-L838) — `parseUrlPath`: admin endpoint detection (single segment `"admin"`) - [`erpc/http_server.go:L295-L610`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L295-L610) — main handler: CORS, auth, dispatch, "admin not enabled" error path - [`erpc/erpc.go:L83-L88`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go#L83-L88) — `NewERPC`: `adminAuthRegistry` construction from `cfg.Admin.Auth` - [`erpc/config_analyzer.go:L76-L728`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L76-L728) — `GenerateValidationReport`, `ValidationReport`/`ValidationResources` types, static + live check phases - [`erpc/block_heatmap.go:L1-L200`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L1-L200) — `recordEvmBlockRangeHeatmap`, `ComputeBlockHeatmapBucket`, `selectDynamicBucketSize`, label formatting - [`common/defaults.go:L775-L784`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L775-L784) — `AdminConfig.SetDefaults`: auto-synthesised CORS with full default values - [`cmd/erpc/main.go:L97-L142`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L97-L142) — `validate` subcommand: config load, `GenerateValidationReport`, render, exit code - [`erpc/block_heatmap_test.go`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap_test.go) — bucket label tests with real Arbitrum block numbers, TIP tolerance, no-L0 guarantee - [`erpc/projects.go:L189-L190`](https://github.com/erpc/erpc/blob/main/erpc/projects.go#L189-L190) — `recordEvmBlockRangeHeatmap` call site in `project.Forward` (post-successful-forward) - [`data/connector.go`](https://github.com/erpc/erpc/blob/main/data/connector.go) — `ConnectorMainIndex = "idx_main"` constant used by API key management methods as the index key ### Related pages - [Auth strategies](/config/auth.llms.txt) — the same strategy types used for `admin.auth.strategies`. - [Rate limiters](/config/rate-limiters.llms.txt) — rate-limit budgets validated by `erpc validate`. - [Failsafe policies](/config/failsafe/retry.llms.txt) — networks without failsafe policies trigger a notice in `erpc validate`. - [Deployment](/deployment/docker.llms.txt) — where to wire the `ERPC_IGNORE_LOCAL_ENDPOINT_VALIDATION` env var. - [Observability](/operation/monitoring.llms.txt) — dashboards and alerting around `erpc_upstream_cordoned`. --- --- # Batching & multiplexing > Source: https://docs.erpc.cloud/operation/batch > Send one request, get back a merged response — eRPC parallelises inbound batch arrays, re-batches calls to supporting upstreams, and collapses identical in-flight requests so each unique call hits the network exactly once. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Batching & multiplexing Send a JSON array and eRPC fans it out in parallel — one failure never aborts the rest. Upstreams that support batching receive your calls as a single HTTP POST, slashing per-request overhead. And when multiple clients ask for the same data at the same time, eRPC collapses them into one upstream call and hands every caller its own copy. **What you get** - Inbound `[…]` arrays unpacked into parallel sub-requests, results merged in order - Outbound re-batching to compatible upstreams, timer- and size-gated - In-flight deduplication: N concurrent identical calls → 1 upstream round-trip ## Quick taste Illustrative, not a tuned production config — enable outbound batching on one upstream: **Config path:** `projects[].upstreams[].jsonRpc` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreams: - id: alchemy-mainnet endpoint: https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY jsonRpc: # enable outbound batching to this upstream supportsBatch: true # flush once 100 calls have accumulated batchMaxSize: 100 # safety valve: flush after 50ms even if batch isn't full batchMaxWait: 50ms ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreams: [{ id: "alchemy-mainnet", endpoint: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", jsonRpc: { // enable outbound batching to this upstream supportsBatch: true, // flush once 100 calls have accumulated batchMaxSize: 100, // safety valve: flush after 50ms even if batch isn't full batchMaxWait: "50ms", }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: enable outbound batching on an archive upstream** ```text I want to reduce HTTP overhead when my indexer fires hundreds of eth_getLogs calls per second. Enable outbound batching on my archive upstream in my eRPC config so eRPC accumulates calls into a single POST, with a safe size cap and a timer flush for low-traffic periods. Read the full reference first: https://docs.erpc.cloud/operation/batch.llms.txt ``` **Prompt Example #2: audit multiplexer setting across all networks** ```text Review my eRPC config and tell me which networks have the multiplexer enabled vs disabled. For each network explain whether the current setting is correct given the workload (dashboard/polling vs indexer), and how to use networkDefaults to apply a single toggle instead of repeating it per network. Reference: https://docs.erpc.cloud/operation/batch.llms.txt ``` **Prompt Example #3: debug duplicate upstream calls on a hot read** ```text My eRPC instance is firing multiple upstream calls for the same eth_blockNumber even when many clients poll simultaneously — I expected the multiplexer to collapse them. Check my eRPC config to see if multiplexing is accidentally disabled, explain the nil-vs-false semantics, and fix it. Reference: https://docs.erpc.cloud/operation/batch.llms.txt ``` **Prompt Example #4: integrate batching with rate limiter budget** ```text My upstream charges per HTTP request. I want outbound batching to accumulate as many calls as possible before flushing so I stay within my rate-limit budget. Configure the right batchMaxSize, batchMaxWait, and rate limiter in my eRPC config so batches are large but callers never time out waiting. Reference: https://docs.erpc.cloud/operation/batch.llms.txt ``` --- ### Batching & multiplexing — full agent reference ### How it works There are three independent subsystems that compose: **Inbound batch handling** is unconditional. Detection is a single-byte test: if `body[0] == '['` the HTTP handler treats the body as a JSON-RPC batch. The body is unmarshalled into `[]json.RawMessage`; failure returns HTTP 400 with `ErrJsonRpcRequestUnmarshal`. A `responses []interface{}` slice sized to the request count preserves positional ordering — each sub-request runs in its own goroutine with a deferred `recover()`, so a panic in one slot produces a `-32603` error at that index while all other goroutines continue unaffected. After `wg.Wait()`, if the HTTP context is already cancelled eRPC drops all responses and writes a fatal error; otherwise it writes HTTP 200 and streams the array through `BatchResponseWriter.WriteTo` — the full batch response is never buffered in memory. HTTP status is always 200 for a batch POST regardless of how many sub-requests failed; callers must inspect each array element for `"error"` fields. **Outbound upstream batching** activates when `upstream.jsonRpc.supportsBatch: true`. The upstream client switches from `sendSingleRequest` to a queue-and-flush loop. Each call creates a `batchRequest` struct with per-request response and error channels, takes `batchMu`, and calls `queueRequest`. A duplicate JSON-RPC `id` in the pending map triggers an immediate flush before re-queuing to prevent ID collision during response matching. The first request in an empty queue arms a `time.AfterFunc(batchMaxWait, processBatch)` timer; when the queue reaches `batchMaxSize` the timer is stopped and `processBatch` fires immediately. `processBatch` drops already-cancelled requests, builds a batch context from the earliest requester deadline, serialises the array, and fires one HTTP POST. Response matching uses `sonic/ast` zero-copy JSON traversal keyed by `id`. Three upstream response shapes are handled: a JSON array (normal), a single JSON object (broadcast error for all queued requests), and non-JSON (all queued requests receive `ErrUpstreamMalformedResponse`). **In-flight multiplexer** intercepts at `Network.Forward`, after static-response short-circuit but before cache lookup and upstream selection. It is enabled by default — `MultiplexingEnabled()` returns `true` when the `multiplexing` field is `nil` (omitted). The deduplication key is `":"` computed by `JsonRpcRequest.CacheHash()`; the JSON-RPC `id` is not part of the hash, so two requests with identical method and params but different IDs are treated as duplicates. Leader/follower election uses `sync.Map.LoadOrStore`: the first goroutine to insert a hash entry is the leader and proceeds to cache lookup and upstream dispatch. Every subsequent goroutine for the same hash becomes a follower: it registers via `copyWg.Add(1)`, increments `erpc_network_multiplexed_request_total`, and waits on the leader's `done` channel. When the leader closes, each follower calls `CopyResponseForRequest` which deep-clones the parsed `JsonRpcResponse` and rewrites its `id` to the follower's original request `id`. Cleanup ordering prevents use-after-free: `cleanupMultiplexer` marks `closed = true`, deletes the hash from `inFlightRequests`, then calls `copyWg.Wait()` so all active followers finish copying before `resp.Release()` is called. ### Config schema #### Inbound batch Inbound batch handling is automatic and unconditional. There are no config fields to enable, disable, or size-limit it. Any POST body whose first byte is `[` is treated as a batch. Source: [`erpc/http_server.go:L405`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L405). #### Outbound upstream batching (`upstream.jsonRpc.*`) Config struct: [`common/config.go:L1072-1094`](https://github.com/erpc/erpc/blob/main/common/config.go#L1072-L1094). `SetDefaults` for `JsonRpcUpstreamConfig` is a no-op — all three fields below have no system defaults and must be provided explicitly. Source: [`common/defaults.go:L1777-1779`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1777-L1779). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `upstream.jsonRpc.supportsBatch` | `*bool` | `nil` (batch **disabled**) | When `true`, all requests through this upstream are queued and dispatched as batches. When `nil` or `false`, every request uses `sendSingleRequest`. No other `jsonRpc` batch fields are read unless this is `true`. Source: [`clients/http_json_rpc_client.go:L132-137`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L132-L137) | | `upstream.jsonRpc.batchMaxSize` | `int` | `0` (no size cap) | Max requests before an immediate flush. **Footgun:** a value of `0` means the size condition is always met, flushing every queued request immediately and negating batching. Always set a non-zero value. Source: [`clients/http_json_rpc_client.go:L294-297`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L294-L297) | | `upstream.jsonRpc.batchMaxWait` | `Duration` | `0` (timer fires immediately) | Time from first queued request before flushing. Uses `time.AfterFunc`. A zero value fires on the next event loop tick. Always set a non-zero value such as `50ms` when using outbound batching. Source: [`clients/http_json_rpc_client.go:L289-292`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L289-L292) | #### Multiplexer (`network.multiplexing`) Config field: [`common/config.go:L1995-2039`](https://github.com/erpc/erpc/blob/main/common/config.go#L1995-L2039). Network defaults propagation: [`common/defaults.go:L1841-1843`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1841-L1843). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `network.multiplexing` | `*bool` | `nil` → **enabled** | **`nil` means ON.** `MultiplexingEnabled()` returns `true` when the field is `nil` or `true`; returns `false` only when explicitly set to `false`. Omitting the key activates the multiplexer. **Footgun:** there is no project-level or global toggle; the knob is strictly per-network (or via `networkDefaults.multiplexing`). Source: [`common/config.go:L2034-2039`](https://github.com/erpc/erpc/blob/main/common/config.go#L2034-L2039) | `networkDefaults.multiplexing` at [`common/config.go:L593-600`](https://github.com/erpc/erpc/blob/main/common/config.go#L593-L600) propagates to all per-network configs that do not set the field explicitly. ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. High-throughput indexer — outbound batching to saturate allowance.** An indexer firing hundreds of `eth_getLogs` calls per second benefits from accumulating calls into large batches, reducing HTTP overhead and round-trip count. Set `batchMaxSize` large enough to fill batches under load; `batchMaxWait` is a safety valve for low-traffic periods. Always set both — zero for either field is a footgun (immediate or unbounded flush): **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: node-archive endpoint: https://archive.example.com/v2/\${ARCHIVE_KEY} jsonRpc: supportsBatch: true # large cap: under full indexer load batches fill quickly — # this prevents the timer from being the bottleneck batchMaxSize: 200 # safety valve: flush after 100ms even when batch isn't full # (low-traffic gaps should not block individual callers for long) batchMaxWait: 100ms ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "node-archive", endpoint: \`https://archive.example.com/v2/\${process.env.ARCHIVE_KEY}\`, jsonRpc: { supportsBatch: true, // large cap: under full indexer load batches fill quickly batchMaxSize: 200, // safety valve for low-traffic gaps batchMaxWait: "100ms", }, }] ``` **2. Frontend dApp — inbound fan-out, no extra config.** A dApp wallet sends a single `[eth_getBalance, eth_getTransactionCount, eth_chainId]` batch in one fetch. eRPC detects the `[` body, dispatches all three in parallel sub-goroutines, and returns the merged array — inbound batch handling is always-on and requires no config: ```json // POST /main/evm/1 [ {"jsonrpc":"2.0","id":1,"method":"eth_getBalance","params":["0xabc…","latest"]}, {"jsonrpc":"2.0","id":2,"method":"eth_getTransactionCount","params":["0xabc…","latest"]}, {"jsonrpc":"2.0","id":3,"method":"eth_chainId","params":[]} ] ``` **3. Production fleet — explicitly disable multiplexer via networkDefaults.** In production, the multiplexer is disabled fleet-wide via `networkDefaults` because indexer workloads issue unique block-range requests that rarely collide; deduplication adds lock contention with no benefit. Individual networks that DO serve hot dashboard traffic (many identical `eth_blockNumber` polls) can re-enable it locally. Omitting `multiplexing:` from a network inherits the default — so the knob only needs to appear where it differs: **Config path:** `projects[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: # explicitly off fleet-wide: indexer traffic is unique-per-request, # so the sync.Map election overhead buys nothing; dashboards re-enable below multiplexing: false networks: - architecture: evm evm: { chainId: 1 } # inherits multiplexing: false from networkDefaults — no override needed - architecture: evm evm: { chainId: 137 } # dashboard / wallet traffic: many tabs poll eth_blockNumber simultaneously — # re-enable here so N identical polls collapse to 1 upstream round-trip multiplexing: true ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { // explicitly off fleet-wide: indexer traffic is unique-per-request multiplexing: false, }, networks: [ { architecture: "evm", evm: { chainId: 1 }, // inherits multiplexing: false — no override needed }, { architecture: "evm", evm: { chainId: 137 }, // dashboard traffic: re-enable for hot identical polls multiplexing: true, }, ], }] ``` **4. Cache upstream with tight hedging — keep batching disabled, tune failsafe per-upstream.** Production cache connectors (gRPC or HTTP) use a tight per-upstream failsafe rather than outbound batching: the cache must answer fast or not at all, so a tight timeout plus a low-delay hedge races a second cache node before falling through to live upstreams. Outbound batching is left disabled on cache upstreams — their latency is already sub-millisecond and batch accumulation would only add wait time: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: cache-sepolia endpoint: https://cache.example.com/sepolia # supportsBatch omitted → disabled (default); cache reads must be fast allowMethods: - eth_getLogs - eth_getBlockByNumber - eth_getTransactionByHash - eth_getTransactionReceipt failsafe: - matchMethod: "*" timeout: duration: 1s # adaptive: cut off slow cache reads more aggressively as p80 warms up quantile: 0.8 minDuration: 200ms maxDuration: 1s hedge: # race a second cache node quickly — cache latency is stable, static delay is fine quantile: 0.9 maxCount: 1 minDelay: 50ms maxDelay: 100ms ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "cache-sepolia", endpoint: "https://cache.example.com/sepolia", // supportsBatch omitted → disabled; cache reads must be fast allowMethods: [ "eth_getLogs", "eth_getBlockByNumber", "eth_getTransactionByHash", "eth_getTransactionReceipt", ], failsafe: [{ matchMethod: "*", timeout: { duration: "1s", // adaptive: cut off slow cache reads more aggressively as p80 warms quantile: 0.8, minDuration: "200ms", maxDuration: "1s", }, hedge: { // race a second cache node; cache latency is stable — static delay works quantile: 0.9, maxCount: 1, minDelay: "50ms", maxDelay: "100ms", }, }], }] ``` **5. Debugging — disable multiplexer to trace individual upstream calls.** When troubleshooting, force every request to hit the upstream individually so each request appears as its own upstream span without follower short-circuiting: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: { chainId: 1 } multiplexing: false ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1 }, multiplexing: false, }] ``` ### Request/response behavior **Inbound batch** - HTTP response status is always **200 OK**, even when every sub-request fails. Callers must inspect each array element for `"error"` fields. Source: [`erpc/http_server.go:L703-L707`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L703-L707). - Body is a JSON array in the original request order; each element is either `{"jsonrpc":"2.0","id":…,"result":…}` or `{"jsonrpc":"2.0","id":…,"error":{…}}`. - A panicking sub-goroutine produces `{"jsonrpc":"2.0","id":null,"error":{"code":-32603,…}}` — `id` is `null` because the request ID cannot be determined at panic time. - An empty input `[]` returns `[]` with HTTP 200; no error. Source: [`erpc/http_server.go:L429-L431`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L429-L431). - Response is streamed directly via `BatchResponseWriter.WriteTo` — the full array is never buffered in memory. **Outbound batch** - `batchMaxSize: 0` means `len(batchRequests) >= 0` is always true → immediate flush on every request (equivalent to no batching). Always set a non-zero value. - Earliest deadline across all queued requests sets the batch HTTP context deadline. A short-deadline request can cut off the entire batch; all receive `ErrEndpointRequestTimeout`. Source: [`clients/http_json_rpc_client.go:L362-L372`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L362-L372). - A request whose context is already cancelled when `queueRequest` is called is failed immediately and never added to the batch map. Source: [`clients/http_json_rpc_client.go:L241-L253`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L241-L253). - On network error, all batched requests receive the error after a 5 ms grace window that lets per-request failsafe sentinels (`ErrDynamicTimeoutExceeded`) become observable before error classification. Source: [`clients/http_json_rpc_client.go:L470-L476`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L470-L476). - If the application context is cancelled during shutdown, `processBatch` drains silently without signalling pending requests (intentional — supervisor is shutting down). Source: [`clients/http_json_rpc_client.go:L305-L330`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L305-L330). - Duplicate JSON-RPC `id` in the pending map triggers an immediate flush before re-queuing the conflicting request. Source: [`clients/http_json_rpc_client.go:L255-L262`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L255-L262). - A single-object upstream response is treated as a broadcast error for all queued requests. - A non-JSON upstream body causes all queued requests to receive `ErrUpstreamMalformedResponse`. **Multiplexer** - Follower response `id` is always overwritten with the follower's original request `id` before delivery. `CopyResponseForRequest` also copies metadata fields (`upstream`, `fromCache`, `attempts`, `retries`, `hedges`, `evmBlockRef`, `evmBlockNumber`) verbatim from the leader's response. Source: [`common/response.go:L581-L647`](https://github.com/erpc/erpc/blob/main/common/response.go#L581-L647). - `X-ERPC-Skip-Cache-Read` on a follower has no effect — the directive is evaluated only on the leader's path; followers always receive the leader's (possibly cached) result. Source: [`erpc/networks.go:L983-L1001`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L983-L1001). - A cache hit on the leader closes the multiplexer; all followers receive the cached response. Followers cannot force a cache miss. - Deduplication scope is per `Network` instance: one `sync.Map` (`inFlightRequests`) is allocated per network in `NewNetwork`. Source: [`erpc/networks_registry.go:L164`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L164). - `CacheHash()` `hashValue()` handles `bool`, `int`, `float64`, `string`, `[]interface{}`, and `map[string]interface{}` recursively. Param types outside this set cause `CacheHash()` to return an error, silently bypassing the multiplexer. Source: [`common/json_rpc.go:L1453-L1500`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1453-L1500). ### Best practices - Always set **both** `batchMaxSize` and `batchMaxWait` to non-zero values when enabling outbound batching — either alone leaves the other as a footgun (immediate or unbounded flushing). - Use `batchMaxWait: 50ms` as a starting point; tune up only if your upstream charges per-request and your traffic is bursty. - Do not use repetitive JSON-RPC `id` values (e.g. always `1`) with outbound batching — duplicate IDs trigger premature single-request flushes, defeating the accumulation benefit. - The multiplexer is on by default; leave it enabled for read-heavy workloads like dashboards, price feeds, and block polling. - Set `multiplexing: false` only when per-request upstream tracing is needed (debugging) or when your workload relies on non-idempotent methods that eRPC cannot detect. - Use `networkDefaults.multiplexing` to apply a single toggle across all networks in a project rather than repeating it per network. - Monitor `erpc_network_multiplexed_request_total` to quantify how many upstream calls are being saved — a high ratio signals the multiplexer is significantly reducing costs. ### Edge cases & gotchas 1. **Inbound batch always HTTP 200.** Even if every sub-request fails, status is 200. Callers must inspect each array element for `"error"` fields. Source: [`erpc/http_server.go:L703-L707`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L703-L707). 2. **Inbound empty array returns `[]`.** A body of `[]` produces a zero-element responses slice and writes `[]` with HTTP 200. No error. Source: [`erpc/http_server.go:L429-L431`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L429-L431). 3. **Outbound `batchMaxSize: 0` means immediate flush.** Every queued request flushes immediately — functionally equivalent to `supportsBatch: false` unless `batchMaxWait` is non-zero. Always set both fields. Source: [`clients/http_json_rpc_client.go:L294`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L294). 4. **Outbound duplicate IDs trigger premature flush.** Workloads with repetitive JSON-RPC `id` values (e.g., always `1`) will cause single-request batches, defeating the batching benefit. Source: [`clients/http_json_rpc_client.go:L255-L262`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L255-L262). 5. **Outbound earliest-deadline batch context.** A short-deadline request can cut off all longer-deadline requests in the same batch — all receive `ErrEndpointRequestTimeout`. Source: [`clients/http_json_rpc_client.go:L362-L372`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L362-L372). 6. **Outbound partial upstream response errors only missing items.** If the upstream returns fewer responses than sent, only missing items receive `"no response received for request ID"` errors; other requests succeed. Source: [`clients/http_json_rpc_client.go:L597-L605`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L597-L605). 7. **Outbound non-JSON upstream body — all requests fail.** All batched requests receive `ErrUpstreamMalformedResponse`. Source: [`clients/http_json_rpc_client.go:L632-L636`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L632-L636). 8. **Multiplexer enabled by default — `nil` is not `false`.** Because the field is `*bool`, omitting `multiplexing:` activates the multiplexer. Explicitly set `multiplexing: false` to disable. Source: [`common/config.go:L2034-L2038`](https://github.com/erpc/erpc/blob/main/common/config.go#L2034-L2038). 9. **Multiplexer: `skipCacheRead` on a follower has no effect.** The directive is evaluated only on the leader's path; followers always receive the leader's result. Source: [`erpc/networks.go:L983-L1001`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L983-L1001). 10. **Multiplexer: followers cannot force a cache miss.** The leader performs cache lookup; a cache hit closes the multiplexer and all followers receive the cached response via `CopyResponseForRequest`. Source: [`erpc/networks.go:L1003-L1019`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1003-L1019). 11. **Multiplexer: closed-state follower retries become the new leader.** A follower finding `inf.closed == true` retries `LoadOrStore`; after `cleanupMultiplexer` deletes the old entry, the retrying goroutine becomes the new leader. Source: [`erpc/networks.go:L2016-L2023`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2016-L2023). 12. **Multiplexer: unhashable param type silently skips dedup.** If `CacheHash()` returns `""` or an error, the request bypasses the multiplexer and proceeds to upstream selection normally. Source: [`erpc/networks.go:L1996-L1999`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1996-L1999). 13. **Multiplexer is per-network, not per-project or global.** There is no project-level toggle; use `networkDefaults.multiplexing` to apply a default across all networks in a project. Source: [`common/config.go:L593-L600`](https://github.com/erpc/erpc/blob/main/common/config.go#L593-L600). 14. **Outbound batch: upstream returns a single JSON object.** Interpreted as a broadcast error applying to all batched requests. Source: [`clients/http_json_rpc_client.go:L606-L636`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L606-L636). 15. **Multiplexer stress test verifies exactly 1 upstream call per cohort.** `TestNetwork_Multiplexer_FollowersReceiveResponse` runs 10, 50, and 3-wave×10 concurrent requests and asserts exactly one upstream call per cohort. Source: [`erpc/networks_multiplexer_test.go:L34-L363`](https://github.com/erpc/erpc/blob/main/erpc/networks_multiplexer_test.go#L34-L363). 16. **`copyWg.Wait()` prevents use-after-free.** `cleanupMultiplexer` calls `mlx.copyWg.Wait()` after marking `closed = true`, ensuring all followers have finished copying before `mlx.resp.Release()` is called. Source: [`erpc/networks.go:L2088-L2110`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2088-L2110). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_multiplexed_request_total` | counter | `project`, `network`, `category`, `finality`, `user`, `agent_name` | Incremented once per follower registration — each time a request is deduplicated into an in-flight identical request. The leader itself is **not** counted. | No dedicated batch metrics exist; outbound batch dispatch is transparent to the existing upstream-level counters (`erpc_upstream_request_duration_histogram`, etc.). **Trace spans** | Span name | Attributes | Notes | |---|---|---| | `Multiplexer.Close` | `multiplexer.hash` | Emitted inside `sync.Once`, fires only on the leader's goroutine. Source: [`erpc/multiplexer.go:L37-39`](https://github.com/erpc/erpc/blob/main/erpc/multiplexer.go#L37-L39) | | `Network.WaitForMultiplexResult` | `multiplexer.hash` | Emitted for every follower; spans the entire wait from registration to response copy. Source: [`erpc/networks.go:L2058-2060`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2058-L2060) | The leader's `Forward` span receives `multiplexer.hash` and `multiplexer.role = "leader"`; follower `Forward` spans receive `multiplexed = true` and `multiplexer.role = "follower"`. Source: [`erpc/networks.go:L986-998`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L986-L998). **Log messages** | Level | Message pattern | Context | |---|---|---| | `TRACE` | `"checking if multiplexing is possible"` | Every request when multiplexing is enabled | | `DEBUG` | `"could not get multiplexing hash for request"` | When `CacheHash()` returns error or empty | | `DEBUG` | `"found identical request initiating multiplexer"` | Follower successfully registered | | `TRACE` | `"multiplexed request result"` | After follower receives result | | `WARN` | `"multiplexer follower got nil response and no error, retrying"` | Unexpected state, follower retries | | `DEBUG` | `"queuing request %+v for batch (current batch size: %d)"` | Each request added to outbound batch | | `DEBUG` | `"processing batch with %d requests"` | Each outbound batch flush | | `TRACE` | `"starting batch timer"` | First request in an empty batch | | `TRACE` | `"committing batch to process total of %d requests"` | Size-limit flush (batch reached `batchMaxSize`) | | `WARN` | `"unexpected response received without ID"` | Element in upstream batch array has null or missing `id` | | `WARN` | `"unexpected response received with ID: %s"` | Element `id` from upstream not found in the pending request map | | `ERROR` | `"some requests did not receive a response (matching ID)"` | Upstream returned fewer responses than sent | ### Source code entry points - [`erpc/http_server.go:L398-L746`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L398-L746) — inbound batch detection (`body[0]=='['`), parallel goroutine dispatch with `recover()`, `wg.Wait()`, `BatchResponseWriter` invocation - [`erpc/http_batch_resp.go:L21-L130`](https://github.com/erpc/erpc/blob/main/erpc/http_batch_resp.go#L21-L130) — `BatchResponseWriter.WriteTo`: streaming inbound batch serialisation, per-element `*NormalizedResponse`, `*HttpJsonRpcErrorResponse`, and error paths - [`clients/http_json_rpc_client.go:L29-L637`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L29-L637) — `GenericHttpJsonRpcClient`: outbound batch queue, timer, size-flush, `processBatch`, `processBatchResponse`, ID matching - [`erpc/networks.go:L1989-L2110`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1989-L2110) — `handleMultiplexing`, `waitForMultiplexResult`, `cleanupMultiplexer`: hash-based leader election via `sync.Map.LoadOrStore`, follower registration with `copyWg`, cleanup ordering - [`erpc/multiplexer.go:L36-L88`](https://github.com/erpc/erpc/blob/main/erpc/multiplexer.go#L36-L88) — `Multiplexer.Close`: `sync.Once` guard, panic recovery, `done` channel close, `jrr.Clone()` - [`common/config.go:L1072-L1094`](https://github.com/erpc/erpc/blob/main/common/config.go#L1072-L1094) — `JsonRpcUpstreamConfig`: `SupportsBatch`, `BatchMaxSize`, `BatchMaxWait` fields - [`common/config.go:L1995-L2039`](https://github.com/erpc/erpc/blob/main/common/config.go#L1995-L2039) — `NetworkConfig.Multiplexing` field and `MultiplexingEnabled()` - [`common/json_rpc.go:L1385-L1409`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1385-L1409) — `JsonRpcRequest.CacheHash()`: `method:sha256(params)` with atomic caching - [`common/response.go:L581-L647`](https://github.com/erpc/erpc/blob/main/common/response.go#L581-L647) — `CopyResponseForRequest`: deep-clone with follower `id` overwrite - [`telemetry/metrics.go:L413-L417`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L413-L417) — `MetricNetworkMultiplexedRequests` counter - [`erpc/networks_registry.go:L164`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L164) — `NewNetwork`: allocates `inFlightRequests *sync.Map` used by the multiplexer - [`erpc/networks_multiplexer_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_multiplexer_test.go) — concurrent follower, stress, multi-wave, slow-upstream tests - [`clients/http_json_json_client_test.go:L105-L421`](https://github.com/erpc/erpc/blob/main/clients/http_json_json_client_test.go#L105-L421) — outbound batch race condition, timeout, partial response, single-object error, non-JSON response tests - [`erpc/networks_client_test.go:L130-L322`](https://github.com/erpc/erpc/blob/main/erpc/networks_client_test.go#L130-L322) — `TestNetwork_BatchRequests`: simple batch, duplicate IDs, single-object upstream error ### Related pages - [Timeout](/config/failsafe/timeout.llms.txt) — bounds how long a sub-request or batch waits before aborting. - [Retry](/config/failsafe/retry.llms.txt) — retries individual sub-requests on failure; independent of batch grouping. - [Hedge](/config/failsafe/hedge.llms.txt) — races backup requests; disabled for composite batch requests. - [Rate limiters](/config/rate-limiters.llms.txt) — caps upstream call volume; works alongside outbound batching to stay within provider limits. - [Cache](/config/database/evm-json-rpc-cache.llms.txt) — the multiplexer leader checks cache before upstream; followers benefit automatically. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — batching reduces the blast radius of per-request failures. --- --- # CLI & env vars > Source: https://docs.erpc.cloud/operation/cli > Start, validate, or inspect your eRPC config from the command line — then deploy with confidence knowing exactly what the engine will run. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # CLI & env vars Three commands cover the full config lifecycle: `start` runs the proxy, `validate` catches mistakes before they reach production, and `dump` shows the exact effective config — defaults filled, TypeScript resolved — that the engine would actually load. Point any of them at a YAML, TypeScript, or JavaScript file, or skip the file entirely and spin up a quick test node with `--endpoint`. ## Quick taste Illustrative, not a tuned production config — validate a config file in CI: **Config path:** `cli` **YAML — `erpc.yaml`:** ```yaml # shell erpc validate --config ./erpc.yaml --format json | jq .errors ``` **TypeScript — `erpc.ts`:** ```typescript // shell erpc validate --config ./erpc.ts --format json | jq .errors ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up config with CI validation and safe env var injection** ```text I want to validate my eRPC config in CI before every deploy, and inject secrets like API keys and Redis passwords safely via environment variables. My config is my eRPC config. Read the full reference first: https://docs.erpc.cloud/operation/cli.llms.txt ``` **Prompt Example #2: tune metrics cardinality and histogram buckets** ```text Audit the metrics section of my eRPC config: adjust histogram bucket boundaries to match our typical latency distribution (10ms–10s), drop the user and composite labels to reduce cardinality, and make sure errorLabelMode is right for Grafana. Reference: https://docs.erpc.cloud/operation/cli.llms.txt ``` **Prompt Example #3: debug a TypeScript config that silently drops a function** ```text My eRPC TypeScript config's selectionPolicy evalFunc seems to be ignored at runtime — the dump output shows a sentinel but requests aren't being filtered. Walk me through why TS functions can be silently dropped and how to verify they were registered correctly. Config: ./eRPC config. Reference: https://docs.erpc.cloud/operation/cli.llms.txt ``` **Prompt Example #4: configure graceful shutdown for Kubernetes rolling deploys** ```text My Kubernetes deployment sees connection errors during rolling updates. Configure the waitBeforeShutdown and waitAfterShutdown values in my eRPC config, and set up INSTANCE_ID via the downward API so shared-state UpdatedBy does not collide across pods. Reference: https://docs.erpc.cloud/operation/cli.llms.txt ``` **Prompt Example #5: explain which logLevel and LOG_LEVEL to use in each environment** ```text I have three environments (dev, staging, prod) and I'm unsure which log level to set in the config file vs which to override at runtime with LOG_LEVEL. Also explain why validate and dump always suppress logs. My config lives at my eRPC config. Reference: https://docs.erpc.cloud/operation/cli.llms.txt ``` --- ### CLI & env vars — full agent reference ### How it works **Startup sequence.** `main()` registers a `signal.NotifyContext` on SIGINT/SIGTERM (`cmd/erpc/main.go:L72`), builds a CLI app via `github.com/urfave/cli/v3`, and calls `cmd.Run`. For the `start`/default action, `baseCliAction` calls `getConfig` then `erpc.Init`. `erpc.Init` (`erpc/init.go:L19`) runs in order: 1. Set zerolog global level from `cfg.LogLevel`. 2. Log the final config as JSON at INFO (may contain redacted secrets). 3. Install histogram buckets and label filter. 4. Register a global network-alias resolver for metrics label consistency. 5. Init EVM JSON-RPC cache if configured (failures are warnings, not fatal). 6. Init shared-state registry if configured (same warn-on-fail pattern). 7. Build `ERPC` core: tracing, rate limiters, proxy pool, shared-state fallback, vendors registry, projects registry. 8. Call `erpcInstance.Bootstrap(appCtx)` — eager network bootstrap in background goroutines. 9. Start HTTP server goroutine. 10. Optionally start a standalone gRPC server if gRPC is enabled and does not share the HTTP v4 port. 11. Start Prometheus metrics server. 12. Block on `<-appCtx.Done()`, then sleep `server.waitAfterShutdown` before returning. **Config file search order.** When `--config` and a positional argument are both absent and `--require-config` is not set, `getConfig` probes (`cmd/erpc/main.go:L279-L293`): 1. `./erpc.yaml` 2. `./erpc.yml` 3. `./erpc.ts` 4. `./erpc.js` 5. `/erpc.yaml` 6. `/erpc.yml` 7. `/erpc.ts` 8. `/erpc.js` 9. `/root/erpc.yaml` 10. `/root/erpc.yml` 11. `/root/erpc.ts` 12. `/root/erpc.js` First path where `fs.Stat` succeeds wins. If none match and no `--endpoint` flag was supplied, eRPC starts with a synthetic `main` project using public RPC providers. **YAML loading.** `LoadConfig` reads the file, runs `os.ExpandEnv` on raw bytes (`common/config.go:L102`), then decodes with `gopkg.in/yaml.v3` in strict mode (`KnownFields(true)` — unknown keys are fatal). After decode: legacy migration hook (`LegacyTranslateFn`, wired to `legacy.TranslateFromConfig` at `cmd/erpc/main.go:L36`) fires first, potentially emitting zerolog Warn messages for deprecated fields, then `SetDefaults`, then `Validate`. Tests that exercise legacy YAML must set `LegacyTranslateFn` manually. **TypeScript/JS loading.** `loadConfigFromTypescript` (`common/config.go:L2686`): 1. esbuild compiles the file as an IIFE bundle (`Bundle:true`, `Format:IIFE`, `Target:ES2020`, `Platform:Node`, `GlobalName:"exports"`). 2. The `tsLoaderWalker` JS fragment is appended — it depth-first walks `exports.default`, assigns IDs (`fn_0`, `fn_1`, …) to every function-typed leaf, registers them in `globalThis.__erpcFns[id]`, and stamps `fn.__erpcFnId = id`. 3. Combined source is compiled to a `sobek.Program` (`userScript`) and run in a temporary runtime. 4. `JSON.stringify` with a replacer converts functions to `"__ts_fn__:fn_"` sentinels; functions not reached by the walker are dropped silently. 5. The resulting JSON is decoded through `yaml.Decoder` with `KnownFields(true)`. 6. `cfg.UserScript` is set; the policy-engine pool re-runs this program in each acquired sobek runtime to reconstruct live `__erpcFns` references — no `.toString()` round-trip, closures preserved. **`validate` subcommand.** Loads config, calls `erpc.GenerateValidationReport` which builds a resource tree and checks for orphan rate-limit budgets, public endpoints, and static-analysis issues. Output is JSON (default) or Markdown. Exits `0` when `errors` is empty, `1` otherwise. All zerolog output is silenced via `zerolog.SetGlobalLevel(zerolog.Disabled)` before `getConfig` — no warnings from `SetDefaults` or `Validate` appear on stderr. **`dump` subcommand.** Loads config, calls `policy.ResolveEffectiveSelectionPolicies` to fill in the effective `selectionPolicy` per network as the engine would derive it, then marshals to YAML (default) or JSON. Useful for verifying what a TypeScript config actually produces. Log output is also suppressed. **Graceful shutdown.** On SIGINT/SIGTERM: `signal.NotifyContext` cancels `appCtx`. The HTTP server's goroutine wakes, disables keep-alives, sleeps `server.waitBeforeShutdown` (default 10 s — gives Kubernetes time to mark the pod NotReady), then calls `srv.Shutdown(30 s budget)`, which GOAWAYs HTTP/2 (including h2c) connections and waits for in-flight requests. The metrics server shuts down with a 5 s budget. The OTel tracer provider shuts down in a goroutine with a 5 s budget. `erpc.Init` blocks on `<-appCtx.Done()`, then waits for the HTTP drain to finish, then sleeps `server.waitAfterShutdown` (default 10 s) before returning, so the process lives up to `waitBeforeShutdown + 30 s + waitAfterShutdown` after the signal. **pprof.** A `//go:build pprof` file registers standard `net/http/pprof` routes and starts a listener at `0.0.0.0:` (default `6060`; override with `ERPC_PPROF_PORT`). Mutex and block profiling are enabled at rate 1. The standard binary does **not** include pprof — build with `-tags pprof` to activate. ### Config schema **CLI subcommands** — [`cmd/erpc/main.go:L200-244`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L200-L244) | Subcommand | Flags | Behavior | |------------|-------|----------| | `erpc [config]` (root / no subcommand) | `--config`, `--endpoint/-e`, `--require-config` | Same as `start`: load config, run `erpc.Init`. | | `erpc start` | `--endpoint/-e` (repeatable), `--require-config`; root `--config` also honored via flag lookup | Start the proxy service. | | `erpc validate` | `--format json\|md` (default `json`) | Validate config; exit 1 on any errors; logs suppressed. | | `erpc dump` | `--format yaml\|json` (default `yaml`) | Dump effective config with resolved selection policies; exit 1 on load/marshal error or unsupported format. | **CLI flags** — [`cmd/erpc/main.go:L76-94`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L76-L94) | Flag | Type | Default | Behavior / footguns | |------|------|---------|---------------------| | `--config` | string | `""` | Path to config file. When non-empty, sets `requireConfig=true`; no fallback to auto-discovery. If the path does not exist, exits 1001. | | `--endpoint` / `-e` | []string | `[]` | Zero or more upstream endpoint URLs. Validated with `url.ParseRequestURI`; invalid URLs abort with exit 1001. Injected as synthetic upstreams into the first project when no providers/upstreams exist. | | `--require-config` | bool | `false` | If `true` and no config file found, aborts. Skips auto-discovery and `--endpoint`-only mode. | | `validate --format` | string | `"json"` | Output format: `json` or `md`. | | `dump --format` | string | `"yaml"` | Output format: `yaml`, `yml`, or `json`. Any other value triggers `"unsupported format"` and exits 1. | **`--set` / `-s` is not available.** Commented out at [`cmd/erpc/main.go:L86-90`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L86-L90). Passing it produces a framework-level flag error before any application code runs. **Top-level `Config` fields** — [`common/config.go:L38-68`](https://github.com/erpc/erpc/blob/main/common/config.go#L38-L68) | YAML path | Type | Default | Behavior / footguns | |-----------|------|---------|---------------------| | `logLevel` | string | `"INFO"` | Zerolog level. Invalid value defaults to `debug` with a warning. Overridable at runtime by `LOG_LEVEL` env var. Valid: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`, `disabled`. | | `clusterKey` | string | `"erpc-default"` | Logical replica group ID for shared-state scoping. Propagated to `database.sharedState.clusterKey` only if that field is empty. Precedence: explicit `database.sharedState.clusterKey` > `clusterKey` > hard-coded default. | | `server` | \*ServerConfig | empty struct then `SetDefaults` | HTTP/gRPC server config (bind addresses, timeouts, graceful-shutdown windows). See [HTTP server](/operation/http-server.llms.txt). | | `healthCheck` | \*HealthCheckConfig | mode=`networks`, defaultEval=`any:initializedUpstreams` | Health check endpoint behaviour. | | `admin` | \*AdminConfig | nil | Admin JSON-RPC API; CORS defaults to `*` origin with no credentials when section is present. | | `database` | \*DatabaseConfig | nil | EVM JSON-RPC cache and/or shared-state connector. | | `projects` | []\*ProjectConfig | synthetic `main` project with the public repository provider when empty | Ordered list of project configs. When empty, `SetDefaults` injects a `main` project. | | `rateLimiters` | \*RateLimiterConfig | nil | Rate limiter budgets. Budget IDs referenced by projects/upstreams/networks must exist here. | | `proxyPools` | []\*ProxyPoolConfig | nil | HTTP proxy pool definitions. | | `tracing` | \*TracingConfig | nil | OTel tracing; defaults when set: protocol=grpc, endpoint=localhost:4317, sampleRate=1.0, serviceName=erpc. | | `metrics.enabled` | \*bool | `true` (non-test builds) | If `false` or nil, metrics server is not started. In test builds the default is nil. | | `metrics.port` | \*int | `4001` | Prometheus scrape port. | | `metrics.hostV4` | \*string | `"0.0.0.0"` | IPv4 bind address for the metrics server. | | `metrics.hostV6` | \*string | `"[::]"` | IPv6 bind address. | | `metrics.errorLabelMode` | LabelMode | `"compact"` | Controls the `error` label on request-error counters. `"compact"` condenses codes; `"verbose"` emits full class names. | | `metrics.histogramBuckets` | string | `""` (built-in defaults) | Comma-separated float64 bucket boundaries. Non-float values are rejected by validation. | | `metrics.customizations` | []\*MetricsCustomizationConfig | nil | Ordered `{subject, action, labels, buckets}` entries controlling family exposure, per-family label sets, and per-family histogram buckets. `subject` is a metric name without the `erpc_` prefix, optionally ending in `*`; rules are applied by specificity, not order. | | `metrics.histogramDropLabels` | []string | nil | **Deprecated** — use `metrics.customizations`. Label names removed from every histogram to reduce cardinality. | | `metrics.histogramLabelOverrides` | map[string][]string | nil | **Deprecated** — use `metrics.customizations`. Per-metric label keep-list; key is metric name without `erpc_` prefix. | | `metrics.counterDropLabels` | []string | nil | **Deprecated** — use `metrics.customizations`. Label names removed from every counter carrying caller-controlled dimensions. Sums are preserved; the dimension is not. | | `metrics.counterLabelOverrides` | map[string][]string | nil | **Deprecated** — use `metrics.customizations`. Per-metric label keep-list for counters; key is metric name without `erpc_` prefix. | **Environment variables** | Env var | Where applied | Effect | |---------|---------------|--------| | `LOG_LEVEL` | `init()` and after config decode | Zerolog global level. Applied twice: first during config-loading so those logs respect it; second after decode to override `cfg.LogLevel`. Invalid value falls back to `debug`. Valid: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`, `disabled`. | | `LOG_WRITER` | `init()` | When `"console"`, switches from JSON to a human-readable colored writer (time format `"04:05.000ms"`). Must be set before process start; cannot be changed at runtime. | | `ERPC_NOLOGS` | `init()` (build tag `!test`) | When `"1"`, silences zerolog globally and replaces the writer with `io.Discard`. Intended for test runs. | | `ERPC_NOMETRICS` | `init()` (build tag `!test`) | When `"1"`, swaps the Prometheus default registry with a no-op. Irreversible within the process. | | `ERPC_PPROF_PORT` | `init()` (build tag `pprof`) | pprof listener port; default `6060`. Only effective when built with `-tags pprof`. Binds `0.0.0.0` — all interfaces. | | `ERPC_IGNORE_LOCAL_ENDPOINT_VALIDATION` | config analyzer | When `"true"`, skips validation of non-HTTP and local (loopback/localhost) upstream endpoints in `erpc validate`. [[`erpc/config_analyzer.go:L1024-1031`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go#L1024-L1031)] | | `ERPC_NOSTAR` | npm launcher (`npx start-erpc`, `@erpc-cloud/cli`) | When `"1"`, the launcher skips its one-time stderr line asking for a GitHub star. The line is also skipped when `CI` is set or stderr is not a TTY, and is shown at most once per machine (marker file `$XDG_CONFIG_HOME/erpc/star-prompt-shown`, default `~/.config/erpc/`). The Go binary ignores this variable. [`typescript/cli/src/star-prompt.ts`](https://github.com/erpc/erpc/blob/main/typescript/cli/src/star-prompt.ts) | | `INSTANCE_ID` | shared-state + consensus | First in the instance-identity chain. Used as `UpdatedBy` in shared-state writes and as `{instanceId}` in consensus dispute-log filenames. | | `POD_NAME` | shared-state + consensus | Second in the chain (Kubernetes pod name). | | `HOSTNAME` | shared-state + consensus | Third in the chain (OS hostname). | | `FORCE_TEST_LISTEN_V4` | `common/defaults.go` | When `"true"` in test builds, forces `server.listenV4=true`. | | `$VAR` / `${VAR}` in YAML | before YAML parse | `os.ExpandEnv` on raw bytes. Unset vars resolve to empty string. Footgun: if the expanded value contains `:` or `{`, quote the YAML value. | | `$VAR` / `${VAR}` in `server.responseHeaders` | HTTP server construction | Expanded once at server startup via `os.ExpandEnv`. If the expanded value is empty, the header entry is silently dropped from all responses. Runs after full config decode; distinct from YAML-level expansion. [[`erpc/http_server.go:L135-148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148)] | | `$VAR` / `${VAR}` in provider-generated upstream endpoints | provider resolution | Expanded when the vendor's `GenerateConfigs` returns each `UpstreamConfig.Endpoint` string. Distinct from YAML-level expansion — runs at request time, not config-load time. [[`thirdparty/provider.go:L67-71`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L67-L71)] | | `process.env.` in TS | sobek runtime creation | Full `os.Environ()` snapshot passed to TS/JS config runtime as a `process.env` object; also exposed as a flat `env` array of `"KEY=VALUE"` strings. A snapshot — not a live view. Because `.env` is loaded in `init()` before the TS bundle is evaluated, `.env` values are available here too. | **Instance-identity priority chain.** Two functions resolve instance ID: - Shared-state: `INSTANCE_ID` → `POD_NAME` → `HOSTNAME` → `os.Hostname()` → `"unknown"`. Whitespace is trimmed at each step. [`data/shared_state_registry.go:L82-98`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L82-L98) - Consensus: same env-var priority order but final fallback is SHA-256(unixNano+pid) truncated to 8 hex chars (computed once via `sync.Once`). Characters problematic for filenames (`:`, `/`, `\`, ` `, `*`, `?`, `"`) are sanitized to `_` before the value is used as the `{instanceId}` token in dispute-log filenames. [`consensus/export_utils.go:L26-48`](https://github.com/erpc/erpc/blob/main/consensus/export_utils.go#L26-L48) Setting `INSTANCE_ID` explicitly avoids both failure modes. **`validate` command output schema** (JSON): ```json { "errors": [], "warnings": [], "notices": [], "resources": { "totals": { "projectsTotal": 0, "networksTotal": 0, "upstreamsTotal": 0, "rateLimitBudgetsTotal": 0 }, "tree": { "projects": [{ "id": "", "networks": [{ "id": "", "upstreams": [{ "id": "" }] }] }], "rateLimiters": { "budgets": [{ "id": "", "rulesCount": 0 }] } } } } ``` Exit `0` if `errors` is empty, exit `1` otherwise. **Exit codes** — [`util/exit.go:L7-10`](https://github.com/erpc/erpc/blob/main/util/exit.go#L7-L10) - `1001` (`ExitCodeERPCStartFailed`) — CLI/config load failure or `erpc.Init` error. - `1002` (`ExitCodeHttpServerFailed`) — HTTP or gRPC server fatal error. ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. CI validation gate before deploy.** Production deployments run `erpc validate` in the pipeline before any image build or Helm upgrade. Exit code 0 means no errors; pipe through `jq .errors` for a clean failure message in CI logs without JSON noise: ```bash # exits 0 when errors=[], exits 1 when errors is non-empty erpc validate --config ./erpc.yaml --format json | jq '.errors' # Markdown for PR comments or human-readable output in CI erpc validate --config ./erpc.yaml --format md ``` **2. Production log level: error in prod, info in staging, info in dev.** Real fleets keep `logLevel: error` in production (high-QPS internal workloads) to suppress routine health-check noise, `info` in staging and dev where visibility matters. `LOG_LEVEL=debug` at runtime (without a deploy) is the escape hatch when diagnosing live issues: **Config path:** `logLevel` **YAML — `erpc.yaml`:** ```yaml # Production — suppress routine INFO chatter; errors surfaced by structured log logLevel: error # Staging / dev — info gives bootstrap/network visibility without trace flood # logLevel: info ``` **TypeScript — `erpc.ts`:** ```typescript // Production logLevel: 'error', // Staging / dev // logLevel: 'info', ``` **3. Tuned metrics for multi-region fleet.** Production edge deployments drop the `user` and `composite` histogram labels (high-cardinality from many API keys and composite request patterns) and set explicit bucket boundaries that match real p50/p99 latencies observed in the fleet. `errorLabelMode: compact` is always used in production to keep Prometheus cardinality bounded: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: enabled: true port: 4001 hostV4: "0.0.0.0" # Bucket edges aligned to observed p50 (~100ms) and p99 (~3s) latencies. # Coarser than the default to keep time-series count down on large fleets. histogramBuckets: "0.020,0.100,0.300,0.500,1,3,6,10" # compact keeps error labels bounded; verbose creates a label value per # error class — too many on multi-upstream deployments. errorLabelMode: compact # Drop high-cardinality labels from every family that carries them. customizations: - subject: "*" labels: - subject: user action: drop - subject: composite action: drop ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { enabled: true, port: 4001, hostV4: '0.0.0.0', // Bucket edges aligned to observed p50 (~100ms) and p99 (~3s) latencies. histogramBuckets: '0.020,0.100,0.300,0.500,1,3,6,10', errorLabelMode: 'compact', customizations: [ { subject: '*', labels: [ { subject: 'user', action: 'drop' }, { subject: 'composite', action: 'drop' }, ], }, ], }, ``` **4. Graceful shutdown for Kubernetes rolling deploys.** Both Kubernetes and PaaS production deployments use 30s for both shutdown windows. `waitBeforeShutdown` gives Kubernetes time to update endpoints before the server starts refusing connections; `waitAfterShutdown` lets in-flight requests drain. `INSTANCE_ID` via the downward API prevents `UpdatedBy` collisions across pods in shared-state writes: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: # Allow Kubernetes to mark the pod NotReady before traffic stops arriving. # Without this, rolling deploys produce connection errors during the gap. waitBeforeShutdown: 30s # Drain in-flight requests before the process exits. waitAfterShutdown: 30s ``` **TypeScript — `erpc.ts`:** ```typescript server: { // Allow Kubernetes to mark the pod NotReady before traffic stops arriving. waitBeforeShutdown: '30s', // Drain in-flight requests before the process exits. waitAfterShutdown: '30s', }, ``` Kubernetes pod spec fragment for the downward API: ```yaml env: - name: INSTANCE_ID valueFrom: fieldRef: fieldPath: metadata.name # stable pod name; avoids UpdatedBy = "unknown" ``` **5. Per-environment clusterKey for shared-state isolation.** Each deployment uses a distinct `clusterKey` so prod, staging, and dev never share lock state. The top-level key propagates automatically unless `database.sharedState.clusterKey` is set explicitly: **Config path:** `database.sharedState` **YAML — `erpc.yaml`:** ```yaml database: sharedState: # Unique per deployment — prod/stage/dev must not share lock state. # If this key collides across two fleets, they race each other's locks. clusterKey: prod-us-east-1 connector: driver: redis redis: uri: \${SHARED_STATE_REDIS_URL} ``` **TypeScript — `erpc.ts`:** ```typescript database: { sharedState: { // Unique per deployment — prod/stage/dev must not share lock state. clusterKey: 'prod-us-east-1', connector: { driver: 'redis', redis: { uri: '\${SHARED_STATE_REDIS_URL}' }, }, }, }, ``` **6. Quick smoke-test with a bare endpoint, no config file.** Spin up eRPC against a single node to verify routing — no YAML required. Useful for local testing before writing a full config: ```bash erpc --endpoint https://mainnet.infura.io/v3/$INFURA_KEY # equivalent: erpc start --endpoint https://mainnet.infura.io/v3/$INFURA_KEY ``` **7. Inspect the effective config produced by a TypeScript config.** TypeScript arrow functions in `selectionPolicy.evalFunc` show up as `__ts_fn__:fn_N` sentinels; everything else renders as plain YAML. Use this to verify closures were detected by the walker: ```bash erpc dump --config ./erpc.ts --format yaml # or JSON for programmatic diffing: erpc dump --config ./erpc.ts --format json | jq . ``` ### Request/response behavior The CLI layer itself does not process JSON-RPC requests. The behaviors below govern how the bootstrap interacts with the process environment. - **`.env` file** in `os.Getwd()` is loaded in `init()` before `main()` runs; values are available for YAML `$VAR` substitution. Non-existence is silently ignored; other errors are logged at ERROR. [[`cmd/erpc/main.go:L42-46`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L42-L46)] - **`LOG_LEVEL` env var overrides `cfg.LogLevel`** after config load; a config-file `logLevel: error` can be trumped by `LOG_LEVEL=debug` without editing the file. [[`cmd/erpc/main.go:L354-363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363)] - **`validate` and `dump` suppress all log output.** `zerolog.SetGlobalLevel(zerolog.Disabled)` is called before `getConfig` runs (`validate`: `cmd/erpc/main.go:L109`; `dump`: `cmd/erpc/main.go:L156`); `LOG_LEVEL` has no effect during these commands. - **YAML strict-mode** rejects unknown fields (`KnownFields(true)`); this applies to the JSON round-trip from TypeScript configs too. [[`common/config.go:L103`](https://github.com/erpc/erpc/blob/main/common/config.go#L103)] - **Shorthand upstream URLs** (`alchemy://KEY`, `infura://KEY`, etc.) are converted to `ProviderConfig` and removed from `p.Upstreams` at `SetDefaults` time; after load they appear in `p.Providers`, not `p.Upstreams`. [[`common/defaults.go:L1164-1172`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1164-L1172)] - **Key validation rules** enforced by `Config.Validate()`: `server.maxTimeout` must be non-zero; each project needs at least one upstream or provider; `selectionPolicy.evalTimeout` must be strictly less than `evalInterval`; `onlyNetworks` and `ignoreNetworks` on a provider are mutually exclusive; `database.sharedState.lockMaxWait` and `updateMaxWait` must each be less than `fallbackTimeout`; `database.sharedState.lockTtl` must be at least as long as `fallbackTimeout`; connector-level failsafe may not use `consensus` or `hedge.quantile`. [[`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15)] ### Best practices - Run `erpc validate --config ./erpc.yaml` in every CI pipeline before shipping config changes — it catches unknown field typos, missing rate-limit budget references, and `selectionPolicy` compile errors without starting a server. - Use `erpc dump --config ./erpc.ts --format yaml` when debugging TypeScript configs to see what the engine actually sees; TS function sentinels (`__ts_fn__:fn_N`) confirm functions were detected correctly. - Always quote YAML values that may contain env vars with special characters: `password: "${REDIS_PASSWORD}"` not `password: ${REDIS_PASSWORD}` — a `:` in the expanded value will break YAML parsing silently. - Set `INSTANCE_ID` (or `POD_NAME` via the Kubernetes downward API) explicitly in every deployment — without it, shared-state `UpdatedBy` falls back to `"unknown"` and collides across pods; consensus dispute-log filenames get unique hashes but shared-state writes do not. - Do not build with `-tags pprof` in production unless you immediately firewall-restrict `ERPC_PPROF_PORT` — the listener binds `0.0.0.0`, not localhost. - Set `LOG_WRITER=console` only for local development; JSON output is required by every log-aggregation platform (Datadog, Grafana Loki, etc.) and the env var cannot be changed at runtime. - In Kubernetes, add a `preStop` hook or rely on `server.waitBeforeShutdown` (default 10 s) to let the pod reach NotReady before requests stop arriving — skip this and you will see connection errors during rolling deploys. ### Edge cases & gotchas 1. **`--config` sets `requireConfig=true` implicitly.** If the specified path does not exist, the process exits 1001 with no fallback to auto-discovery. [[`cmd/erpc/main.go:L300-302`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L300-L302)] 2. **Positional argument works in all subcommands.** `erpc validate ./config.yaml` and `erpc dump ./config.yaml` both work — first positional arg is treated as a config path with `requireConfig=true`. [[`cmd/erpc/main.go:L303-305`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L303-L305)] 3. **YAML strict-mode rejects unknown fields.** A typo in any YAML key is a fatal error — this also applies to the JSON round-trip from TypeScript configs. 4. **Quoted YAML values required for env vars that may contain special chars.** `password: "${REDIS_PASSWORD}"` is safe; `password: ${REDIS_PASSWORD}` is not if the value contains `:` or `{`. 5. **TypeScript default-export must be the last statement.** If a later expression overwrites `exports.default`, the earlier config object is lost. Error: `"config object must be default exported from TypeScript code AND must be the last statement in the file"`. [[`common/config.go:L2715-2717`](https://github.com/erpc/erpc/blob/main/common/config.go#L2715-L2717)] 6. **TS functions in bare arrays are not walked.** The `tsLoaderWalker` only descends into object properties, not bare array function elements. In practice `selectionPolicy` functions are always object values so this rarely matters. 7. **Orphaned TS function silently dropped.** A function not reached by the walker is dropped by the JSON.stringify replacer — the config field will be absent with no error. [[`common/config.go:L2736-2739`](https://github.com/erpc/erpc/blob/main/common/config.go#L2736-L2739)] 8. **`validate`/`dump` suppress all log output.** `zerolog.SetGlobalLevel(zerolog.Disabled)` is called before `getConfig`. Warnings from `SetDefaults`, legacy migration, and validation do not appear. Use `jq .errors` on the JSON output. `LOG_LEVEL` has no effect here. 9. **`LOG_WRITER=console` must be set before process start.** Configured in `init()`, not hot-reloadable. In log-aggregation environments keep the default JSON writer. 10. **pprof binds `0.0.0.0`.** All interfaces, not localhost-only. Firewall-restrict or avoid `-tags pprof` in production. 11. **`ERPC_NOMETRICS=1` is irreversible.** Swaps the Prometheus default registry process-wide; cannot be undone within the same process. 12. **`INSTANCE_ID` not stable across restarts = orphaned shared-state locks.** Use a deployment-stable value (pod name, container ID). 13. **`dump --format csv` (or any unknown format) exits 1 via a distinct code path.** A marshal failure means config loaded but serialisation failed; an unsupported-format failure means serialisation was never attempted. Valid values: `yaml`, `yml`, `json`. 14. **Shared-state falls back to `"unknown"` while consensus generates a hash.** In environments with no env vars and `os.Hostname()` failing, shared-state `UpdatedBy` is `"unknown"` (collides across pods). Consensus dispute-log filenames get a unique 8-char hash. [[`data/shared_state_registry.go:L82-98`](https://github.com/erpc/erpc/blob/main/data/shared_state_registry.go#L82-L98)] [[`consensus/export_utils.go:L26-48`](https://github.com/erpc/erpc/blob/main/consensus/export_utils.go#L26-L48)] 15. **Provider endpoint env expansion runs after YAML-level expansion.** Pipeline: (1) `os.ExpandEnv` on raw YAML bytes → YAML decode → `SetDefaults` (providers registered). Then at request time: (2) provider's `GenerateConfigs` builds endpoint strings → `expandEnvVars` calls `os.ExpandEnv`. Double-expansion is possible if the vendor builds an endpoint that itself contains `$VAR` literals. [[`thirdparty/provider.go:L67-71`](https://github.com/erpc/erpc/blob/main/thirdparty/provider.go#L67-L71)] 16. **`--set` / `-s` is not implemented.** The flag was planned as a Helm-style dot-path override but is commented out. Passing `-s` or `--set` produces `"flag provided but not defined: -s"` from the CLI framework. [[`cmd/erpc/main.go:L86-90`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L86-L90)] 17. **Metrics server disabled in test builds.** `MetricsConfig.SetDefaults` sets `Enabled=true` only when `!util.IsTest()`. Tests that need metrics must set `metrics.enabled: true` explicitly. [[`common/defaults.go:L750-752`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L750-L752)] 18. **gRPC shares the HTTP handler when both addresses resolve to the same port.** No separate `grpcServer.Start` goroutine runs. [[`erpc/init.go:L125`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L125)] 19. **Eager network bootstrap runs on `appCtx`; novel chains trigger the lazy path.** Novel chain IDs arriving before bootstrap finishes block the request until init completes or the request context times out. [[`erpc/networks_registry.go:L195-212`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L195-L212)] 20. **TypeScript `process.env` is a snapshot, not a live view.** Built once when the sobek runtime is created from `os.Environ()`; a restart-less env var change requires all policy engine runtimes to be recreated. ### Observability The bootstrap/CLI layer emits no Prometheus metrics of its own. Key structured log messages (zerolog JSON unless `LOG_WRITER=console`): | Log message | Level | When | |-------------|-------|------| | `"executing command"` (fields: `action`, `version`, `commit`) | INFO | Start of every CLI action | | `""` with `config` field | INFO | Final config logged before init — may contain redacted secrets | | `"initializing eRPC core"` | INFO | Before `NewERPC` | | `"initializing transports"` | INFO | After core init, before server start | | `"shutting down gracefully..."` | INFO | On context cancel | | `"no projects found in config; will add a default 'main' project"` | WARN | Synthetic project injected | | `"no providers or upstreams found in project; will use default 'public' endpoints repository"` | WARN | Public fallback provider injected when project has no upstreams or providers | | `"failed to initialize evm json rpc cache: ..."` | WARN | Cache init failure (non-fatal) | | `"failed to initialize shared state registry: ..."` | WARN | Shared-state init failure (non-fatal) | | `"invalid log level '...', defaulting to 'debug'"` | WARN | Invalid `LOG_LEVEL` or `logLevel` value | | `"pprof server started at http://localhost:"` | INFO | Only when built with `-tags pprof` | | `"networks bootstrap completed"` | INFO | After all configured networks initialised | ### Source code entry points - [`cmd/erpc/main.go:L72-L305`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L72-L305) — signal handling, CLI command definitions, `getConfig`, auto-discovery, `--endpoint` injection - [`erpc/init.go:L19-L180`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L19-L180) — `Init(ctx, cfg)`: full startup + graceful drain sequence - [`common/config.go:L95-L110`](https://github.com/erpc/erpc/blob/main/common/config.go#L95-L110) — `LoadConfig`: `os.ExpandEnv`, YAML decode, legacy migration, `SetDefaults`, `Validate` - [`common/config.go:L2686-L2740`](https://github.com/erpc/erpc/blob/main/common/config.go#L2686-L2740) — `loadConfigFromTypescript`: esbuild, `tsLoaderWalker`, sobek eval, sentinel lifecycle - [`common/defaults.go:L49-L176`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L49-L176) — `Config.SetDefaults`: full defaults cascade, synthetic `main` project injection - [`common/validation.go:L15`](https://github.com/erpc/erpc/blob/main/common/validation.go#L15) — `Config.Validate`: exhaustive validation rules - [`cmd/erpc/pprof.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/pprof.go) — build-tag `pprof`: `init()` registering pprof routes and starting `0.0.0.0:` listener - [`cmd/erpc/initflags.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go) — build-tag `!test`: `ERPC_NOLOGS` and `ERPC_NOMETRICS` init hooks - [`util/exit.go:L7-L10`](https://github.com/erpc/erpc/blob/main/util/exit.go#L7-L10) — exit codes `1001` (start failed) and `1002` (HTTP/gRPC server fatal) - [`erpc/config_analyzer.go`](https://github.com/erpc/erpc/blob/main/erpc/config_analyzer.go) — `GenerateValidationReport`, `RenderValidationReportJSON`, `RenderValidationReportMarkdown` - [`common/runtime.go`](https://github.com/erpc/erpc/blob/main/common/runtime.go) — `NewRuntime()`: creates a sobek runtime, populates `process.env` map and `env` array from `os.Environ()`; used for TypeScript selection-policy evaluation - [`common/compiler.go`](https://github.com/erpc/erpc/blob/main/common/compiler.go) — `CompileTypeScript` (esbuild IIFE bundle), `CompileFunction` (sobek single-function eval), `CompileProgram` (sobek.Compile with paren-wrap) ### Related pages - [HTTP server](/operation/http-server.llms.txt) — server bind addresses, timeouts, and graceful shutdown knobs. - [Deployment](/deployment/docker.llms.txt) — Docker and Kubernetes deployment patterns, including `POD_NAME` downward API setup. - [Projects](/config/projects.llms.txt) — the config structure that `start` and `validate` both load. - [Rate limiters](/config/rate-limiters.llms.txt) — budget IDs that validation checks for orphan references. - [Observability](/operation/metrics.llms.txt) — Prometheus metrics exposed on `metrics.port`. --- --- # Cordoning > Source: https://docs.erpc.cloud/operation/cordoning > Pull any upstream out of routing instantly with one admin call — no metric window to wait for, no config redeploy required. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Cordoning When a vendor starts acting up — latency spikes, wrong responses, a quota incident — you want it gone from routing *right now*, not after a 15-minute error-rate window closes. One admin RPC call cordons the upstream instantly. Another call brings it back just as fast. No config change, no redeploy, no restart. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: pull a degraded upstream out of rotation right now** ```text One of my eRPC upstreams is having a vendor incident and I need to remove it from routing immediately without redeploying. Show me the admin API calls to cordon it, verify the change, and restore it when the incident is resolved. My admin endpoint is configured in my eRPC config. Read the full reference first: https://docs.erpc.cloud/operation/cordoning.llms.txt ``` **Prompt Example #2: cordon a single broken RPC method** ```text A specific upstream in my eRPC setup is timing out only on eth_getLogs but is fine for everything else. Show me how to cordon just that method without pulling the whole upstream out of rotation, and explain why erpc_listCordoned won't show it. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/cordoning.llms.txt ``` **Prompt Example #3: alert and dashboard on cordon state** ```text Set up Prometheus alerts and dashboard panels so I can see which eRPC upstreams are currently cordoned, how long they've been cordoned, and how many times they've been cordoned in the past 24 hours. Explain the erpc_upstream_cordoned gauge vs the event counter. Reference: https://docs.erpc.cloud/operation/cordoning.llms.txt ``` --- ### Cordoning — full agent reference ### How it works Two kinds of cordon exist and they never overwrite each other: - **Operator cordons** (`erpc_cordonUpstream` with `method: "*"`, the default) are one shared counter per upstream — the same primitive that shares block heights across pods. Key `/v2/operatorCordon///`, value = unix-ms when cordoned, `0` when lifted. Shared state does the rest: pub/sub propagation on `redis`/`postgresql` (milliseconds), background reconcile on `dynamodb` (seconds), and an initial fetch when the upstream bootstraps, so a restarted or scaled-out pod restores the cordon before it serves anything. Writes are local-first and pushed in the background, like every other shared counter; if the store is unreachable the cordon applies on this pod and reaches peers when the store returns. With the `memory` driver (the default when `database.sharedState` is omitted) the counter is in-process only. - **Automatic cordons** are set by in-process detectors (consensus sit-out, SVM health, EVM chain-identity mismatch) on the health tracker's `(upstream, method, finality=All)` cell, as are method-scoped operator cordons (`method: "eth_getLogs"`). They are per pod. While the shared operator cordon is held, a detector cannot lift the `"*"` cell — a consensus penalty ending never releases an operator cordon. Routing, `erpc_listCordoned` and the health check all read one lookup, `Tracker.CordonedReason(upstream, method)`: the wildcard `"*"` cell first, then the method cell. The policy reads it per upstream rather than from the slot's metrics bucket, so a wildcard cordon shadows every method slot at every selection-policy `evalScope`. The state feeds the selection policy through the `cordonedReason` field exposed on each upstream's JS metrics object. The built-in default policy calls `.removeCordoned()` as its first chain step, so a cordon takes effect within one eval interval (default 15 s) after it reaches a replica. A custom `evalFunc` must call `.removeCordoned()` explicitly or the cordon has no routing effect. `erpc_uncordonUpstream` lifts the shared operator cordon for the whole fleet and clears **every** cordon class on `"*"` (operator, punishment, and availability). That is the operator recovery path for any wildcard cordon. Availability cordons also clear automatically when their owner recovers: the EVM state poller lifts its own bit after a later major-move `eth_chainId` verify matches again, and the SVM state poller lifts when state probes answer again and shred-insert lag recovers. Method-scoped `Uncordon` still clears only the requested class bit (feature §4.5). Uncordoning a method never lifts a wildcard cordon. ### Behavior changes (upgrade note) - **One cordon bit per source.** Previously a single flag was shared across operator, consensus-sit-out (punishment), and detector (availability) sources, so one `Uncordon` could clear an unrelated cordon. Now each source holds its own bit and clears only its own; a sit-out ending never releases an operator cordon. - **The chain-identity cordon is an `availability` cordon and expires.** While it holds, every head the upstream reports is dropped. The poller checks `eth_chainId` every 5 minutes and lifts it after 2 matches in a row, the only way out: an admin uncordon restores routing but not its heads, and a mismatch cordons it again. - **A full `erpc_uncordonUpstream` also resets consensus sit-out state**, so the upstream can be re-punished immediately instead of waiting for the original penalty window to end. The reason string is kept only on the replica that took the call; peers and restarted pods report `"operator cordon (set on another replica)"`. Re-cordoning an already cordoned upstream keeps the original start, whichever replica serves it, so `erpc_upstream_cordon_duration_seconds` measures the whole incident. Use cordons for outages measured in minutes to days. For permanent exclusion, remove the upstream from config or set `ignoreMethods: ["*"]` and redeploy. ### Config schema Cordoning has no config-file fields. It is controlled entirely at runtime via admin RPC. The selection policy's `evalFunc` implicitly controls whether cordon state is respected — it requires `.removeCordoned()` in the chain. For `evalFunc` and `evalInterval` config fields, see [Selection & scoring](/config/projects/selection-policies.llms.txt). ### Worked examples **1. Incident response: cordon a vendor immediately.** You notice `erpc_upstream_error_rate` spiking on `alchemy-eth-1` before the error window is wide enough to trigger automatic exclusion. Cordon it now: ```bash curl -X POST http://localhost:4000/admin \ -H 'Content-Type: application/json' \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "erpc_cordonUpstream", "params": [{"projectId": "main", "upstream": "alchemy-eth-1", "reason": "vendor incident #12345"}] }' ``` ```json {"jsonrpc":"2.0","id":1,"result":{ "projectId": "main", "upstream": "alchemy-eth-1", "method": "*", "cordoned": true, "reason": "vendor incident #12345" }} ``` Omitting `method` cordons the upstream for all methods (`"*"`). **2. Method-scoped cordon: isolate a broken RPC method.** A vendor is fine for most calls but `eth_getLogs` is timing out past 30 s. Cordon just that method while the rest of the vendor's capacity keeps working: ```bash curl -X POST http://localhost:4000/admin \ -H 'Content-Type: application/json' \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "erpc_cordonUpstream", "params": [{"projectId": "main", "upstream": "drpc-eth-1", "method": "eth_getLogs", "reason": "p95 > 30 s"}] }' ``` A wildcard cordon overrides method-scoped cordons: an upstream with both `"*"` and `"eth_getLogs"` cordons is excluded for all methods. Uncordoning a specific method does not lift a wildcard cordon. **3. List and restore.** During an incident, list all whole-upstream cordons, then restore when the vendor confirms recovery: ```bash # list whole-upstream cordons in a project curl -X POST http://localhost:4000/admin \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":3,"method":"erpc_listCordoned", "params":[{"projectId":"main"}]}' ``` ```json { "projectId": "main", "cordoned": [ {"upstream": "alchemy-eth-1", "reason": "vendor incident #12345"} ] } ``` `erpc_listCordoned` only returns upstreams with a `"*"`-scope cordon (operator or automatic). Method-scoped cordons are invisible to it; read the `erpc_upstream_cordoned` gauge labels to enumerate them. ```bash # restore the upstream curl -X POST http://localhost:4000/admin \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":4,"method":"erpc_uncordonUpstream", "params":[{"projectId":"main","upstream":"alchemy-eth-1", "reason":"vendor confirmed resolved"}]}' ``` **4. Custom evalFunc — explicit `.removeCordoned()` required.** If you have replaced `selectionPolicy.evalFunc` with a custom function, you must call `.removeCordoned()` explicitly near the start of the chain. Without it the `cordonedReason` field on the upstream's metrics object is populated, but no step actually drops the upstream from the ordered list — the cordon has no routing effect. Source: [`internal/policy/default_policy.js:L1`](https://github.com/erpc/erpc/blob/main/internal/policy/default_policy.js#L1) — `.removeCordoned()` is the first call. ### Request/response behavior - `erpc_cordonUpstream` `method` param defaults to `"*"` when absent; `reason` defaults to `"admin: manual cordon"`. `"*"` sets the shared operator cordon; any other method sets a cordon on this replica only. [[`erpc/admin.go:L656-694`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L656-L694)] - `erpc_uncordonUpstream` `reason` defaults to `"admin: manual uncordon"` — a distinct string from the cordon default; it is used only for the local automatic cordon it lifts. - `erpc_listCordoned` only returns upstreams where `CordonedReason("*")` returns `cordoned=true` — method-scoped cordons are not listed. - Routing changes on the next policy eval tick (default 15 s) after the cordon reaches a replica; shared-state propagation to peers is milliseconds on `redis`/`postgresql` and seconds on `dynamodb`. - A cordoned upstream is placed at position `-1` in `erpc_selection_position` once `.removeCordoned()` drops it. - All admin RPCs require `admin.auth` configured; missing `admin:` block returns `"admin is not enabled for this project"` (401); present `admin:` but absent `admin.auth:` returns `"admin auth not configured"` (401). [[`erpc/admin.go:L26-30`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L26-L30)] ### Best practices - **Cordon early, not late.** The selection policy's metric-driven exclusion needs sample accumulation; cordoning is zero-lag. When you see a vendor degrading in dashboards, cordon it immediately rather than waiting for `errorRateAbove(0.7)` to trigger. - **Always supply a reason string.** The reason appears in `erpc_upstream_cordoned` gauge labels and in `erpc_listCordoned` output. A reason like `"incident-#12345 alchemy"` makes incident timelines clear and helps correlate with duration histograms post-incident. - **Prefer method-scoped cordons when feasible.** If a vendor is broken only for `eth_getLogs` but healthy for `eth_call`, a method-scoped cordon keeps the vendor in rotation for the methods it can serve — reducing pressure on remaining upstreams. - **Remember the 15 s propagation delay.** The tracker is updated immediately, but the ordered-list cache is rebuilt on the next eval tick. Build runbooks around this delay (e.g. wait 20 s before verifying traffic shifted). - **Use a remote `database.sharedState` connector for fleets.** Operator cordons reach every replica and survive restarts only through `redis`, `postgresql` or `dynamodb`; `memory` keeps them in-process. - **Do not use cordon for permanent exclusions.** For a vendor you want permanently removed, update the config; a shared cordon outlives the pod that set it. - **Custom evalFunc operators: `.removeCordoned()` must be explicit.** The default policy includes it; a custom `evalFunc` that omits it will silently ignore all admin cordons. ### Edge cases & gotchas 1. **Uncordoning a method does not lift a wildcard cordon.** `IsCordoned` checks the operator cordon and the `"*"` cell first, so the upstream stays out of rotation for all methods as long as either is active. Source: [`health/tracker.go:L900-939`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L900-L939). 2. **Automatic and method-scoped cordons are per pod; whole-upstream operator cordons are per fleet.** A consensus sit-out, chain-identity cordon or `method: "eth_getLogs"` cordon on one replica is not visible on others. An `erpc_uncordonUpstream` for `"*"` reaches every replica and clears all cordon classes there (operator + punishment + availability). EVM/SVM availability cordons also clear automatically on their owning poller when the underlying health/identity check recovers. 3. **The reason travels only with the pod that took the call.** Peers and restarted pods show `"operator cordon (set on another replica)"` in `erpc_listCordoned` and in the `erpc_upstream_cordoned` `reason` label. 4. **Custom evalFunc without `.removeCordoned()` ignores all cordons.** `cordonedReason` is populated on the JS upstream object, but no routing effect occurs unless `.removeCordoned()` (or equivalent logic) appears in the chain. 5. **Routing effect is delayed by up to `evalInterval`.** The tracker is updated immediately, but the ordered-list cache used by the request path is rebuilt on the next eval tick. Requests in flight can still reach the upstream for up to one eval interval. 6. **State-poller is unaffected by cordon.** The EVM state poller for a cordoned upstream continues running, keeping its latest/finalized block numbers fresh. When uncordoned, the upstream's metrics are current and re-admission scoring works immediately. 7. **Shadow mirroring is unaffected by cordon.** Shadow upstreams receive async-mirrored traffic regardless of cordon state; cordon only affects routing of real requests. 8. **`erpc_cordonUpstream` is idempotent on the same upstream.** Repeated calls update the local `reason` but do not reset the shared value or fire multiple `cordon` event counter increments, whichever replica serves them. Source: [`upstream/upstream.go:L1526-1536`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1526-L1536). 9. **The default policy's `.whenEmpty(() => upstreams)` safety net can re-admit a cordoned upstream.** If every other upstream is health-excluded (for example far behind the network head), the raw set is used rather than failing closed. 10. **`erpc_listCordoned` requires `admin.auth` configured.** If the `admin:` section is present but `admin.auth:` is absent, the request returns `"admin auth not configured"`. If the `admin:` section is entirely missing, it returns `"admin is not enabled for this project"`. Both are 401 responses. Source: [`erpc/admin.go:L26-30`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L26-L30). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_cordoned` | gauge | project, vendor, network, upstream, category (=method), reason | Set to 1 on cordon, 0 on uncordon; persists until uncordon or process restart | | `erpc_upstream_cordon_event_total` | counter | project, network, upstream, action | Edge transitions only: OFF→ON (`action="cordon"`) and ON→OFF (`action="uncordon"`); repeated cordons do not increment | | `erpc_upstream_cordon_duration_seconds` | histogram | project, network, upstream | Observed once per uncordon on each replica; value = `now − CordonedAtMs` as seen by that replica; buckets 1 s … 86400 s | | `erpc_selection_position{upstream=…}` | gauge | project, network, method, upstream | Set to `-1` for every excluded (including cordoned) upstream after each eval tick | | `erpc_selection_rejection_total{step="removeCordoned"}` | counter | project, network, method, upstream, step | Per tick × upstream dropped by the `.removeCordoned()` step | Log messages (DEBUG level, `health/tracker.go`): - `"cordoning upstream to disable routing"` / `"uncordoning upstream to enable routing"` — every automatic or method-scoped `Cordon` / `Uncordon` call. ### Source code entry points - [`upstream/upstream.go:L1503-1567`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1503-L1567) — `CordonAdmin` / `UncordonAdmin`, the shared counter (`operatorCordonVar`) that flips the `"*"` cell, and the `Uncordon` guard - [`health/tracker.go:L842-939`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L842-L939) — `Cordon` / `Uncordon`, `IsCordoned`, `CordonedReason` - [`data/shared_state_variable.go`](https://github.com/erpc/erpc/blob/main/data/shared_state_variable.go) — `CounterInt64SharedVariable`: the shared primitive (rollback threshold `0` accepts every change, including back to `0`) - [`erpc/admin.go:L590-736`](https://github.com/erpc/erpc/blob/main/erpc/admin.go#L590-L736) — `erpc_cordonUpstream`, `erpc_uncordonUpstream`, `erpc_listCordoned` handlers - [`internal/policy/eval.go`](https://github.com/erpc/erpc/blob/main/internal/policy/eval.go) — `cordonedReason` exposed to the JS eval context via `Tracker.CordonedReason` - [`internal/policy/default_policy.js:L1`](https://github.com/erpc/erpc/blob/main/internal/policy/default_policy.js#L1) — `.removeCordoned()` as first default policy step ### Related pages - [Admin API](/operation/admin.llms.txt) — authentication setup required before any cordon call will succeed. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — the `evalFunc` chain where `.removeCordoned()` must appear; also `evalInterval` that controls propagation delay. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the incident-response outcome cordoning helps achieve. - [Upstreams](/config/projects/upstreams.llms.txt) — permanent exclusion via `ignoreMethods: ["*"]` or config removal, the alternative when cordon is not the right tool. --- --- # Directives > Source: https://docs.erpc.cloud/operation/directives > Send an HTTP header or query param and change routing, caching, validation, or consensus for exactly that one request — no restarts, no config changes. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Directives Every request can carry its own instructions. Add an `X-ERPC-*` header or a `?param=` query string and eRPC instantly shifts routing, caching, integrity checks, or consensus behavior for that call only. No server restart. No config change. These directives can also be pinned as `directiveDefaults` on any network so every call starts with a sensible baseline. For production-facing projects, [`allowClientDirectives`](/config/projects.llms.txt) can restrict which directives clients may send — block cache-bypass or upstream-pinning headers while keeping integrity directives available. When eRPC is itself the edge (no trusted proxy in front to strip headers), the restriction can be scoped **per caller** instead of per project: set `allowClientDirectives: ""` on the project to deny everyone by default, then re-grant on the individual auth strategies that trusted callers authenticate with: ```yaml projects: - id: main allowClientDirectives: "" # default: nobody auth: strategies: - type: secret # operators: every directive allowClientDirectives: "*" secret: { id: ops, value: ${OPS_TOKEN} } - type: secret # partners: upstream pinning only allowClientDirectives: "use-upstream" secret: { id: partner, value: ${PARTNER_TOKEN} } - type: jwt # everyone else: inherits "" → denied jwt: { ... } ``` The grant travels on the authenticated `User`, so it is only ever issued by the strategy that actually verified the caller's credential. A caller whose identity comes from [`trustUserIdHeader`](/config/projects.llms.txt) carries no grant and always falls back to the project value — spoofing the identity header cannot widen directive access. After each response, eRPC echoes back what actually happened — which upstream won, cache hit or miss, retry and hedge counts — so you always know exactly what the proxy did. ## Quick taste Per request, the way directives are actually used — pin one call to specific upstreams via header or query string: **File:** `terminal` ```bash # via header: only Alchemy upstreams may serve this request curl https://rpc.example.com/main/evm/1 \\ -H 'X-ERPC-Use-Upstream: alchemy-*' \\ -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}' # same directive as a query parameter curl 'https://rpc.example.com/main/evm/1?use-upstream=alchemy-*' \\ -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}' ``` Directives that make sense as a permanent baseline can be pinned per network with `directiveDefaults` — headers and query params still override them per request: **Config path:** `projects[].networks[].directiveDefaults` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } directiveDefaults: # retry when upstream returns null/empty (e.g. not-yet-indexed block) retryEmpty: true # reject responses whose block number is behind the known tip enforceHighestBlock: true ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, directiveDefaults: { // retry when upstream returns null/empty (e.g. not-yet-indexed block) retryEmpty: true, // reject responses whose block number is behind the known tip enforceHighestBlock: true, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set sane directive defaults for a new network** ```text I'm adding a new EVM network to my eRPC config and want to pin sensible directiveDefaults — retryEmpty, enforceHighestBlock, enforceNonNullTaggedBlocks, and useUpstream routing for archival calls. Read the full reference first: https://docs.erpc.cloud/operation/directives.llms.txt ``` **Prompt Example #2: audit and tighten my existing directive defaults** ```text Review the directiveDefaults blocks in my eRPC config: check which integrity directives are on by default but may be incompatible with non-standard chains (zkSync, Filecoin, Kaia style), flag any retryPending: true set globally (dangerous), and suggest per-network overrides. Read the reference: https://docs.erpc.cloud/operation/directives.llms.txt ``` **Prompt Example #3: pin an archival upstream for indexer traffic** ```text My indexer sends eth_getLogs and eth_getBlockReceipts requests that should always hit an archival upstream tagged family:archival in my eRPC config. Configure directiveDefaults.useUpstream so those calls are pinned to that group and set the network's integrity level for indexing correctness. Reference: https://docs.erpc.cloud/operation/directives.llms.txt ``` **Prompt Example #4: debug why X-ERPC-Retry-Empty is not retrying** ```text My requests have X-ERPC-Retry-Empty: true in the header but eRPC is not retrying empty results. Walk me through why this might happen (boolean parse rules, EmptyResultMaxAttempts cap, gRPC path limitation) and how to verify via the X-ERPC-Attempts response header that retries are actually firing. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/directives.llms.txt ``` **Prompt Example #5: reduce diagnostic header noise in production logs** ```text Our load balancer logs every X-ERPC-Upstreams response header and it's adding megabytes to our access logs. Configure executionHeaders on the server to suppress the per-attempt trace while keeping the counter headers for dashboards. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/directives.llms.txt ``` **Prompt Example #6: lock down client directives on a public-facing project** ```text My eRPC project serves public traffic and I want to prevent clients from sending X-ERPC-Skip-Cache-Read or X-ERPC-Use-Upstream headers to bypass caching or pin upstreams. Configure allowClientDirectives so integrity directives are still allowed but operational ones are blocked. Reference: https://docs.erpc.cloud/operation/directives.llms.txt ``` --- ### Directives — full agent reference ### How it works **Parsing pipeline.** For every HTTP request eRPC runs three steps. First, `ApplyDirectiveDefaults` copies any `directiveDefaults` config block into the request struct (lowest priority). Second, `SetAllowClientDirectiveMatcher` stores a pre-compiled matcher function from the project-level `allowClientDirectives` pattern (compiled once at project registration via `NewWildcardMatcher`). Third, `EnrichFromHttp` scans all registered header and query names, skipping any directive whose query-param key is rejected by the matcher. If no directives are present it returns immediately after extracting User-Agent — zero allocations, zero locks. When directive inputs are present the struct is cloned before mutation so batch sub-requests that share the same pointer do not race. Precedence from lowest to highest: `directiveDefaults` config → HTTP header → URL query parameter. A query-param value always wins over the same header, which always wins over config. `ApplyDirectiveDefaults` is idempotent — once `r.directives` is non-nil every subsequent call is a no-op, so per-request overrides can never be clobbered by a second config pass. Source: [`common/request.go:563-676`](https://github.com/erpc/erpc/blob/main/common/request.go#L563-L676). **Boolean parsing rule.** For every boolean directive header the only truthy value is the exact string `"true"` (case-insensitive, whitespace stripped). `"1"` and `"yes"` are not truthy. `X-ERPC-Force-Trace` is handled by the tracing subsystem separately and accepts all three. Always use `"true"` to avoid this asymmetry. Confirmed: [`common/request_test.go:406-427`](https://github.com/erpc/erpc/blob/main/common/request_test.go#L406-L427). **`directiveDefaults` placement.** Settable at `projects[].networks[].directiveDefaults` (per network) or `projects[].networks[].failsafe.directiveDefaults` (failsafe scope). Every `*bool` field has three states: nil (omitted — request field stays at Go zero `false`), pointer to `false` (explicitly written), pointer to `true`. The nil check in `ApplyDirectiveDefaults` is a "was this field set?" guard, not a multi-level inheritance chain. **gRPC path.** `EnrichFromHttp` is never called on the gRPC path. gRPC callers receive only `directiveDefaults`; per-request header overrides are not available. Source: [`erpc/request_processor.go:35-67`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go#L35-L67). ### Config schema Config struct: [`common/config.go:2105-2152`](https://github.com/erpc/erpc/blob/main/common/config.go#L2105-L2152). Applied by `ApplyDirectiveDefaults` at [`common/request.go:563-676`](https://github.com/erpc/erpc/blob/main/common/request.go#L563-L676). #### Complete directive registry | # | HTTP header | Query param | Type | Config field | Default | Effect | Consumed at | |---|---|---|---|---|---|---|---| | 1 | `X-ERPC-Retry-Empty` | `retry-empty` | bool | `retryEmpty` | `false` | Retry on null/empty upstream response. Subject to `EmptyResultMaxAttempts` cap. | [`erpc/network_executor.go:427-442`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L427-L442) | | 2 | `X-ERPC-Retry-Pending` | `retry-pending` | bool | `retryPending` | `false` (struct comment "true by default" is **stale**) | Retry `eth_getTransactionReceipt` / `eth_getTransactionByHash` / `eth_getTransactionByBlockHashAndIndex` / `eth_getTransactionByBlockNumberAndIndex` while tx is pending. `EmptyResultMaxAttempts` cap applies. | [`erpc/network_executor.go:445-459`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L445-L459) | | 3 | `X-ERPC-Skip-Cache-Read` | `skip-cache-read` | string (bool in config YAML normalized to string) | `skipCacheRead` | `""` (no skip) | `"true"` = skip all; `"false"`/`""` = use cache; other string = connector-ID WildcardMatch pattern. YAML `true`/`false` normalized to strings via `fmt.Sprintf("%v", v)`. Header NOT trimmed; query IS trimmed. | [`common/request.go:898-914`](https://github.com/erpc/erpc/blob/main/common/request.go#L898-L914) | | 4 | `X-ERPC-Use-Upstream` | `use-upstream` | string | `useUpstream` | `""` (no filter) | Selector matched against upstream `id`; for purely-positive patterns also against upstream `Tags` (any tag match wins). Negated patterns (`!`) match ID only. Header NOT trimmed; query IS trimmed. No match → `ErrUpstreamsExhausted`. Scopes the [served tip](/reference/evm/block-tracking.llms.txt#selector-scoped-served-tip) to the matched upstreams; a simple group selector also gets its own [lane](/reference/lanes.llms.txt). Stateful methods with multiple matching upstreams fail with `ErrNotImplemented`. | [`upstream/upstream.go:1526-1534`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1526-L1534) | | 5 | `X-ERPC-Skip-Interpolation` | `skip-interpolation` | bool | `skipInterpolation` | `false` | Suppresses block-tag → hex substitution in forwarded params. Internal block refs still computed/cached. | [`architecture/evm/json_rpc.go:132`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L132) | | 6 | `X-ERPC-Skip-Consensus` | `skip-consensus` | bool | `skipConsensus` | `false` | Bypasses consensus branch; uses standard `retry(hedge(upstreamSweep))`. Retry/hedge/breaker/timeout still apply. | [`erpc/network_executor.go:179-188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L179-L188) | | 7 | `X-ERPC-Enforce-Highest-Block` | `enforce-highest-block` | bool | `enforceHighestBlock` | **`true`** (SetDefaults) | `eth_blockNumber`: answered from and pinned to the served tip ([details](/reference/evm/block-tracking.llms.txt#eth_blocknumber)). `eth_getBlockByNumber` with `"latest"`/`"finalized"` needs no enforcement: the tag is interpolated to the request's Head. | [`architecture/evm/eth_blockNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go) | | 8 | `X-ERPC-Enforce-GetLogs-Range` | `enforce-getlogs-range` | bool | `enforceGetLogsBlockRange` | **`true`** (SetDefaults) | Pre-forward: rejects `eth_getLogs`/`trace_filter` if block range exceeds `getLogsMaxAllowedRange`. Consumed via legacy `EvmIntegrityConfig` (not a true per-request override — see Edge cases). | [`architecture/evm/eth_getLogs.go:280-288`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L280-L288) | | 9 | `X-ERPC-Enforce-Non-Null-Tagged-Blocks` | `enforce-non-null-tagged-blocks` | bool | `enforceNonNullTaggedBlocks` | **`true`** (SetDefaults) | Treats null block for tag-based `eth_getBlockByNumber` as an error. Disable for chains that legitimately return null for certain tags (e.g., zkSync). | [`architecture/evm/eth_getBlockByNumber.go:304`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go#L304) | | 10 | `X-ERPC-Integrity` | `integrity` | string | — | `""` | Per-request data-integrity selection — a level (`off`/`intrinsic`/`corroborated`/`authoritative`) or a configured profile name; honored only when the network's integrity `headerMode` permits. See [Integrity checks](/config/failsafe/integrity.llms.txt). | [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go) | #### `server.executionHeaders` — response diagnostic header mode | Value | Effect | Source | |---|---|---| | `"all"` (default) | Full counter headers + `X-ERPC-Upstreams` per-attempt trace | [`erpc/http_server.go:1081-1086`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1081-L1086) | | `"summary"` | All counter headers; `X-ERPC-Upstreams` trace suppressed only | [`erpc/http_server.go:1105-1127`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1105-L1127) | | `"off"` | No `X-ERPC-*` diagnostics (version/commit still emitted) | [`erpc/http_server.go:1105-1127`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1105-L1127) | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Global network defaults: retryEmpty on, retryPending explicitly off.** Production fleets set `retryEmpty: true` at `networkDefaults` so every network retries null/empty upstream responses (e.g., a not-yet-indexed block) without per-network config. `retryPending: false` is explicit because the struct's stale "true by default" comment causes confusion — production configs state it clearly: **Config path:** `projects[].networkDefaults.directiveDefaults` **YAML — `erpc.yaml`:** ```yaml networkDefaults: directiveDefaults: # Retry null/empty results globally — covers block-availability races # on eth_getLogs, eth_getBlockByNumber, eth_getTransactionReceipt. retryEmpty: true # retryPending default is false despite stale struct comment; # pin it explicitly so intent is clear to future maintainers. retryPending: false ``` **TypeScript — `erpc.ts`:** ```typescript networkDefaults: { directiveDefaults: { // Retry null/empty results globally — covers block-availability races // on eth_getLogs, eth_getBlockByNumber, eth_getTransactionReceipt. retryEmpty: true, // retryPending default is false despite stale struct comment; // pin it explicitly so intent is clear to future maintainers. retryPending: false, }, } ``` **2. Non-standard chain: relax tagged-block enforcement.** zkSync Era and similar ZK-rollups can legitimately return null for certain block tags, so they disable `enforceNonNullTaggedBlocks` per-network while inheriting all other defaults: **Config path:** `projects[].networks[].directiveDefaults` **YAML — `erpc.yaml`:** ```yaml networks: - evm: chainId: 324 # zkSync Era mainnet directiveDefaults: # zkSync can return null for certain block tags — don't treat as error enforceNonNullTaggedBlocks: false ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ evm: { chainId: 324, // zkSync Era mainnet }, directiveDefaults: { // zkSync can return null for certain block tags — don't treat as error enforceNonNullTaggedBlocks: false, }, }] ``` **3. Indexer workload — full receipt integrity.** When backfilling a chain for an indexer you want to catch any upstream that sends partial or misordered receipts. Configure the network's [`integrity`](/config/failsafe/integrity.llms.txt) block so every call on that network is validated automatically, and keep the kept enforcement directives on at `directiveDefaults`: **Config path:** `projects[].networks[].directiveDefaults` **YAML — `erpc.yaml`:** ```yaml directiveDefaults: retryEmpty: true # tx-receipt polling — only enable per-indexer-network, not globally retryPending: true enforceHighestBlock: true enforceNonNullTaggedBlocks: true ``` **TypeScript — `erpc.ts`:** ```typescript directiveDefaults: { retryEmpty: true, // tx-receipt polling — only enable per-indexer-network, not globally retryPending: true, enforceHighestBlock: true, enforceNonNullTaggedBlocks: true, } ``` **4. Per-request upstream pinning.** A dApp wants to read its own just-submitted transaction from the same upstream it used to broadcast, bypassing the normal load-balanced pool. Send the header at call time — no config change needed: ```http POST /1/main HTTP/1.1 X-ERPC-Use-Upstream: alchemy-mainnet X-ERPC-Retry-Pending: true ``` The upstream selector supports wildcards and tags: `"alchemy-*"`, `"alchemy-mainnet|quicknode-*"`, `"family:archival"` (tag match), `"!drpc"` (exclude one by ID). **5. Per-call cache bypass for fresh data.** A price-feed service needs uncached `eth_call` results on every tick. Send `X-ERPC-Skip-Cache-Read: true` per request; write-back still fires so the next caller gets the fresh value from cache: ```http POST /1/main HTTP/1.1 X-ERPC-Skip-Cache-Read: true ``` To bypass only the in-memory tier and keep Redis warm reads: `X-ERPC-Skip-Cache-Read: memory*`. **6. Skipping consensus for internal tooling.** A monitoring script wants low-latency reads and trusts a single upstream. Bypass the consensus quorum for that call: ```http POST /1/main HTTP/1.1 X-ERPC-Skip-Consensus: true ``` Retry, hedge, circuit-breaker, and timeout still apply — only the dispute/agreement step is skipped. ### Request/response behavior **Request headers — canonical truthy value.** Every boolean directive header requires `"true"` (any case, optional surrounding whitespace). `"1"` and `"yes"` evaluate to `false` and silently have no effect. Exception: `X-ERPC-Force-Trace` (tracing subsystem, not a directive) accepts `"true"`, `"1"`, or `"yes"`. Always use `"true"`. **Directive-adjacent request inputs** (not in the directive registry): | Input | Kind | Values / behavior | Source | |---|---|---|---| | `X-ERPC-Force-Trace` | header | `"true"`, `"1"`, or `"yes"` → bypass OTel trace sampling for that request (attribute `erpc.force_trace = true`) | [`common/tracing_util.go:107-115`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L107-L115) | | `force-trace` | query param | same three truthy values | [`common/tracing_core.go:31`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L31) | | `user-agent` | query param | overrides `User-Agent` header for agent-name metrics tracking | [`common/request.go:1299-1314`](https://github.com/erpc/erpc/blob/main/common/request.go#L1299-L1314) | | `User-Agent` | header | stored raw or simplified per `project.userAgentMode`; drives agent-name metric labels | [`common/request.go:1300-1311`](https://github.com/erpc/erpc/blob/main/common/request.go#L1300-L1311) | | `networkId` | JSON body field | `"evm:42161"`-style network selection when architecture/chain are absent from the URL path | [`erpc/http_server.go:613-634`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L613-L634) | **Response headers always emitted (every HTTP response, not controlled by `executionHeaders`):** | Header | Value | Source | |---|---|---| | `Content-Type` | `application/json` | [`erpc/http_server.go:259`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L259) | | custom `server.responseHeaders` | static values, env-expanded at startup | [`erpc/http_server.go:263-266`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L263-L266) | **Execution diagnostic headers** (controlled by `server.executionHeaders`; single responses get the per-response set, batch responses get ONE aggregated set — counters summed across sub-calls, `X-ERPC-Duration` = slowest sub-call, no `X-ERPC-Upstream`): | Header | Value | When | |---|---|---| | `X-ERPC-Version` | eRPC version string | always | | `X-ERPC-Commit` | git commit SHA | always | | `X-ERPC-Attempts` | total physical ops (upstream + cache) | always | | `X-ERPC-Upstream-Attempts` / `X-ERPC-Upstream-Retries` / `X-ERPC-Upstream-Hedges` | counters | always | | `X-ERPC-Network-Attempts` / `X-ERPC-Network-Retries` / `X-ERPC-Network-Hedges` | counters | always | | `X-ERPC-Cache-Attempts` / `X-ERPC-Cache-Retries` / `X-ERPC-Cache-Hedges` | counters | only when > 0 | | `X-ERPC-Consensus-Slots` / `X-ERPC-Consensus-Disputes` / `X-ERPC-Consensus-Low-Participants` | counters | only when > 0 | | `X-ERPC-Cache` | `HIT` or `MISS`; on batch responses also `PARTIAL:` (n sub-calls served from cache) | when response metadata present | | `X-ERPC-Upstream` | winning upstream id | single responses only, when known | | `X-ERPC-Duration` | milliseconds (batch: the slowest sub-call) | NormalizedResponse only | | `X-ERPC-Upstreams` | per-attempt trace: `upstreamId=reason:outcome:durationMs[:won]` segments joined by `;`. Known `reason` values: `primary`, `hedge`, `retry`, `consensus_slot`, `sweep`. Known `outcome` values: `success`, `timeout`, `exec_revert`, `rate_limited`. `:won` suffix appended only when the attempt's response contributed to the final answer (in a batch: to its own sub-call's answer). Batch: segments concatenate in sub-call order, capped at 50 with `X-ERPC-Upstreams-Truncated: `. | `all` mode only; when `len(attempts) > 0` | Example `X-ERPC-Upstreams` value: `alchemy=primary:success:50ms:won;quicknode=hedge:timeout:5000ms;drpc=consensus_slot:exec_revert:20ms`. `reason` precedence when several apply to one attempt: `consensus_slot` > `hedge` > `sweep` > `retry` > `primary` — the outermost fan-out cause wins, so an attempt that hedged or retried *inside* a consensus participant slot still reads `consensus_slot` (the attempt record's `IsHedge`/`IsRetry` fields preserve the inner mechanics). **Cost / billing headers** (opt-in via `server.costHeaders: true`; emitted on single AND batch responses; omitted on early errors that never routed a call): | Header | Value | |---|---| | `X-ERPC-Calls` | routed JSON-RPC sub-calls in this HTTP response (batch size; `1` for a single request) | | `X-ERPC-Billable` | how many of them were billable. Successful, empty-but-valid and execution-revert responses bill (cache hits included — their *cost* is zero, not their billability; a revert is real work the node performed); protocol, transport, rate-limit and cancellation failures do not | | `X-ERPC-Methods` | distinct JSON-RPC methods, sorted, comma-joined | | `X-ERPC-Credits` | `vendor:method=` segments, sorted, `;`-joined — the vendor credit units consumed by **every physical upstream attempt** (retries, hedges and consensus slots included; skipped / breaker-open attempts provably never dialed and cost 0). Read from the per-request aggregate (`NormalizedRequest.CreditUnitsByVendor`). Omitted when nothing accrued (e.g. pure cache hits). Units come from vendors implementing `CreditUnitsProvider` (built-in tables: Alchemy CUs, QuickNode credits, dRPC CUs), merged per method with `providers[].settings.creditUnits` overrides; vendors with no table default to a **flat 1 credit per request** (opt out with `creditUnits: {"*": 0}`) | | `X-ERPC-Credits-Total` | grand total credit units across all vendors and sub-calls in this response; present alongside `X-ERPC-Credits` | | `X-ERPC-Credits-Version` | the eRPC version the built-in vendor tables shipped with; only present alongside `X-ERPC-Credits` | Example: `X-ERPC-Calls: 5` · `X-ERPC-Billable: 4` · `X-ERPC-Cache: PARTIAL:2` · `X-ERPC-Credits: alchemy:eth_call=52;quicknode:eth_getLogs=40` · `X-ERPC-Credits-Total: 92`. Cost-header gotchas: emitted only for routed requests — early parse/auth errors get none (there is no routed call to account for). Pricing is the **vendor's** logic (`common.CreditUnitsProvider.CreditUnits(req, upstreamCfg)`; nothing is hard-coded in the eRPC layer). A timed-out attempt still accrues credits — it dialed the vendor — while `skipped`/`breaker_open` attempts provably never left the process and cost 0. Vendors without pricing cost a flat 1 credit per request unless opted out (`creditUnits: {"*": 0}`). Source: `costHeaders` in [`erpc/http_server.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go), `attemptCreditUnits` in [`upstream/upstream.go`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go), tests in [`erpc/http_server_cost_test.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server_cost_test.go) and [`upstream/credit_units_test.go`](https://github.com/erpc/erpc/blob/main/upstream/credit_units_test.go). Responses also carry `X-ERPC-Network-Id` and `X-ERPC-Network-Alias` (the network's alias, else its id) when every routed sub-call resolved to one network. **Over WebSocket** the same headers arrive as *cost frames*, opt-in per connection: send `X-ERPC-Cost-Frames: 1` on the upgrade request while `server.costHeaders` is `true`. Then every text message eRPC sends starts with a header block in HTTP/1.1 wire form — `Name: value\r\n` lines, then `\r\n` — followed by the unchanged JSON body. Responses (single and batch) carry exactly the header set above for the same calls; a message that routed no call (batch parse error, empty batch) starts with just `\r\n`; calls that get no reply (id-less requests) get a metering-only message, their header block with an empty body; each `eth_subscription` notification carries `X-ERPC-Calls: 1`, `X-ERPC-Billable: 1`, `X-ERPC-Methods: eth_subscription`, `X-ERPC-Subscription: ` and the network headers, no credits. Without the header (or with `costHeaders` off) WebSocket output is plain JSON. See [WebSocket cost frames](/operation/websocket.llms.txt#cost-frames). **Error shapes produced by directive checks.** Failed validation directives return `ErrEndpointContentValidation`. A `UseUpstream` selector that matches no upstream returns `ErrUpstreamsExhausted` (wrapping `ErrUpstreamNotAllowed` per candidate) — there is no distinct "selector matched nothing" error code. ### Best practices - **Start with `enforceHighestBlock: true`** — it is on by default and catches the most common upstream data-quality issues with negligible overhead. - **Raise the network's [`integrity`](/config/failsafe/integrity.llms.txt) level only for indexing workloads** — higher levels (e.g. bloom recomputation, log-field checks) are CPU-intensive and penalize latency for general-purpose proxy traffic. Use `X-ERPC-Integrity` to opt a single request into a higher level. - **Use `retryEmpty: true` for block-polling calls** but verify `EmptyResultMaxAttempts` is set appropriately; unbounded retries on a degraded upstream can exhaust the timeout budget. - **Never set `retryPending: true` globally** — it converts every pending-tx lookup into a polling loop. Pin it per request (`X-ERPC-Retry-Pending: true`) or to a dedicated network for transaction-tracking flows. - **Pin `useUpstream` at config via `directiveDefaults` for known-good archival nodes** rather than relying on callers to send the header — this prevents a misconfigured client from silently routing archival calls to full nodes. - **Always send `"true"`, never `"1"` or `"yes"`**, for `X-ERPC-*` boolean directive headers. - **On gRPC, per-request overrides are not available.** Wire all desired defaults into `directiveDefaults` in config; `EnrichFromHttp` is never called on the gRPC path. - **Lock down client directives on public-facing projects** with `allowClientDirectives: "!skip-cache-read & !use-upstream"` to prevent clients from bypassing your cache or pinning to specific upstreams while still allowing integrity directives. ### Edge cases & gotchas 1. **`RetryPending` default is `false`, not `true`.** The struct comment at `common/request.go:125` ("true by default") is stale. No `SetDefaults` entry exists. Must be explicitly enabled via `directiveDefaults.retryPending: true` or `X-ERPC-Retry-Pending: true`. 2. **`X-ERPC-Use-Upstream` header is NOT trimmed; query IS.** A header with leading/trailing spaces will not match any upstream. Source: [`common/request.go:741`](https://github.com/erpc/erpc/blob/main/common/request.go#L741) vs [`:812`](https://github.com/erpc/erpc/blob/main/common/request.go#L812). 3. **`"1"` and `"yes"` are NOT truthy for directive headers.** Only `"true"` (any case). This differs from `X-ERPC-Force-Trace`. Source: [`common/request_test.go:406-427`](https://github.com/erpc/erpc/blob/main/common/request_test.go#L406-L427). 4. **`UseUpstream` failure produces `ErrUpstreamsExhausted`, not a selector-specific error.** Operators must parse the error message text to diagnose selector mismatches. Source: [`common/errors.go:1432-1440`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1432-L1440). 5. **`X-ERPC-Skip-Consensus: false` actively disables consensus bypass.** Sending the header with the value `"false"` is NOT the same as omitting the header. A header value `"false"` parses to `false` and overrides a `directiveDefaults.skipConsensus: true` config entry — the consensus branch then runs normally. Omitting the header leaves `SkipConsensus` at its config-default value. Tested: [`common/request_test.go:409`](https://github.com/erpc/erpc/blob/main/common/request_test.go#L409), [`erpc/skip_consensus_directive_test.go:125-153`](https://github.com/erpc/erpc/blob/main/erpc/skip_consensus_directive_test.go#L125-L153). 6. **`EnforceGetLogsBlockRange` cannot be overridden per-request via HTTP.** `SetDefaults` copies `DirectiveDefaults` values into `Evm.Integrity`; the architecture layer reads from the network config struct, not the per-request directive. Source: [`common/defaults.go:1957-1964`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1957-L1964). 7. **Batch responses emit ONE aggregated `X-ERPC-*` header set.** Counters sum across sub-calls, `X-ERPC-Cache` becomes `PARTIAL:` when mixed, `X-ERPC-Duration` is the slowest sub-call, the trace caps at 50 segments (`X-ERPC-Upstreams-Truncated` carries the overflow count), and the single-winner `X-ERPC-Upstream` is not emitted. Per-sub-call attribution still needs the per-response `id` fields in the body. 8. **`executionHeaders: summary` removes only `X-ERPC-Upstreams`.** All counter and metadata headers still emit. Use `"off"` to suppress everything. 9. **Selector-scoped served-tip lanes are capped.** Past the per-network [lane cap](/reference/lanes.llms.txt), the tip is still scoped to the matched upstreams but gets no lane — no error. 10. **`nil *bool` in `DirectiveDefaultsConfig` ≠ `false *bool`.** Nil means "not set — skip"; a `*false` pointer means "explicitly disable". Only non-nil pointers are applied in `ApplyDirectiveDefaults`. Source: [`common/request.go:570-580`](https://github.com/erpc/erpc/blob/main/common/request.go#L570-L580). 11. **`allowClientDirectives` filters HTTP-supplied directives only.** Config-set `directiveDefaults` always apply regardless of the filter. The pattern is pre-compiled at project registration via `NewWildcardMatcher` and evaluated against each directive's query-param key (e.g. `skip-cache-read`, `use-upstream`). `nil` = all allowed; `""` = none allowed; `"!skip-cache-read & !use-upstream"` = all except those two. Does not filter `X-ERPC-Force-Trace` (processed before project resolution). Source: `isDirectiveAllowed` method on `NormalizedRequest` in `common/request.go`, `NewWildcardMatcher` in `common/matcher.go`, `AllowClientDirectives` in `common/config.go`. See [projects config](/config/projects.llms.txt). ### Observability Directives have no dedicated Prometheus metrics; their effects appear in existing counters. | Metric | Type | When it fires | |---|---|---| | `erpc_upstream_request_retries_total{reason="empty_result"}` | counter | Each retry triggered by `RetryEmpty` | | `erpc_upstream_request_retries_total{reason="pending_tx"}` | counter | Each retry triggered by `RetryPending` | | `erpc_upstream_request_retries_total{reason="integrity_validation"}` | counter | Each retry due to a failed integrity check | | `erpc_network_consensus_rounds_total` | counter | Consensus rounds; `SkipConsensus=true` prevents increment | **Trace / log.** `X-ERPC-Force-Trace: true` (or `force-trace` query param) forces OTel sampler to record the span regardless of sampling rate (attribute `erpc.force_trace = true`). Source: [`common/tracing_util.go:89-100`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L89-L100). `Request.Lock` / `Request.RLock` detail spans are emitted inside directive mutations ([`common/request.go:924-934`](https://github.com/erpc/erpc/blob/main/common/request.go#L924-L934)). At `trace` level, `applied request directives` is logged with `Interface("directives", ...)` after every `EnrichFromHttp` call. Source: [`erpc/http_server.go:659`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L659). ### Source code entry points - [`common/request.go:116-215`](https://github.com/erpc/erpc/blob/main/common/request.go#L116-L215) — `RequestDirectives` struct: all directive fields + library-only fields - [`common/request.go:563-676`](https://github.com/erpc/erpc/blob/main/common/request.go#L563-L676) — `ApplyDirectiveDefaults`: idempotency guard, nil-check per `*bool` field, copy-from-config - [`common/request.go:702-893`](https://github.com/erpc/erpc/blob/main/common/request.go#L702-L893) — `EnrichFromHttp`: fast-path scan, clone-on-write, all header + query parsers - [`common/config.go:2105-2175`](https://github.com/erpc/erpc/blob/main/common/config.go#L2105-L2175) — `DirectiveDefaultsConfig` struct; `skipCacheRead` custom YAML/JSON unmarshal - [`common/defaults.go:1454-1471`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1454-L1471) — `DirectiveDefaultsConfig.SetDefaults`: three `true` defaults (`enforceHighestBlock`, `enforceGetLogsBlockRange`, `enforceNonNullTaggedBlocks`) - [`erpc/http_server.go:1081-1272`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1081-L1272) — `executionHeadersMode`, `setResponseHeaders`, `writeCounterHeaders`, `writeResponseMetadataHeaders`, `writeUpstreamTraceHeaders` - [`erpc/network_executor.go:179-188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L179-L188) — `SkipConsensus` branch - [`erpc/network_executor.go:374-462`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L374-L462) — `shouldRetryWithReason`: `RetryEmpty` / `RetryPending` checks and `EmptyResultMaxAttempts` cap - [`erpc/networks.go:564-655`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L564-L655) — selector-scoped served tip: `EvmRoutableUpstreams`, `requestSelector`, `servedTipLaneFor` - [`upstream/upstream.go:1505-1548`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L1505-L1548) — `shouldSkip`: `UseUpstream` selector check via `UpstreamMatchesSelector` - [`common/matcher.go:34-112`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L34-L112) — `WildcardMatch`, `MatchesSelector`, `UpstreamMatchesSelector` - [`erpc/skip_consensus_directive_test.go`](https://github.com/erpc/erpc/blob/main/erpc/skip_consensus_directive_test.go) — end-to-end `SkipConsensus` tests - [`common/request_test.go:391-541`](https://github.com/erpc/erpc/blob/main/common/request_test.go#L391-L541) — unit tests for boolean parse rules, header/query precedence, `ValidateTransactionsRoot` override ### Related pages - [Auth](/config/auth.llms.txt) — credential headers (`X-ERPC-Secret-Token`, `Authorization`, `X-Siwe-*`) parsed separately before directives. - [Rate limiters](/config/rate-limiters.llms.txt) — caps total request volume; important when `retryEmpty`/`retryPending` loops could multiply upstream calls. - [Consensus](/config/projects/consensus.llms.txt) — the branch that `skipConsensus` bypasses. - [Selection policies](/config/projects/selection-policies.llms.txt) — controls which upstreams are eligible before `useUpstream` further restricts the set. - [Matcher syntax](/config/matcher.llms.txt) — the WildcardMatch grammar used by `useUpstream` and `skipCacheRead` patterns. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — a use case that combines `retryEmpty`, `enforceHighestBlock`, and `useUpstream`. --- --- # Healthcheck > Source: https://docs.erpc.cloud/operation/healthcheck > One endpoint that tells Kubernetes exactly when your pod is ready, draining, or broken — with eight probe strategies from "any upstream alive" to live chain-ID verification. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Healthcheck eRPC's `/healthcheck` endpoint gives Kubernetes and your monitoring stack a single, honest answer about upstream health. Choose from eight evaluation strategies — from "at least one upstream appeared" (safe at cold start) to live `eth_chainId` verification — and let the response format scale from a plain `OK` byte to full per-upstream diagnostics. On graceful shutdown, the endpoint returns 503 automatically so pods drain cleanly before traffic stops. **What you get** - Eight named eval strategies for startup, readiness, and liveness probes - Drain-aware 503 that stops traffic routing before connections close - Independent auth so monitoring systems don't need project API secrets - Scoped probes: global, per-project, or per-network in one endpoint ## Quick taste Illustrative, not a tuned production config — networks mode with CIDR-locked auth: **Config path:** `healthCheck` **YAML — `erpc.yaml`:** ```yaml healthCheck: # return per-network JSON instead of a plain OK/fail byte mode: networks # safe at cold start: passes as soon as any upstream has registered defaultEval: "any:initializedUpstreams" auth: strategies: - type: network network: # kubelet probes come from the node IP, not 127.0.0.1 allowLocalhost: true allowedCIDRs: - "10.0.0.0/8" ``` **TypeScript — `erpc.ts`:** ```typescript healthCheck: { // return per-network JSON instead of a plain OK/fail byte mode: "networks", // safe at cold start: passes as soon as any upstream has registered defaultEval: "any:initializedUpstreams", auth: { strategies: [{ type: "network", network: { // kubelet probes come from the node IP, not 127.0.0.1 allowLocalhost: true, allowedCIDRs: ["10.0.0.0/8"], }, }], }, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up Kubernetes readiness and startup probes** ```text Configure Kubernetes readiness, startup, and liveness probes for my eRPC deployment so the pod drains cleanly before shutdown and doesn't receive traffic until at least one upstream is initialized. Use separate eval strategies for startup vs readiness, set waitBeforeShutdown to match probe thresholds, and lock the healthcheck endpoint to pod/node CIDRs. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/operation/healthcheck.llms.txt ``` **Prompt Example #2: tune eval strategy for my traffic pattern** ```text Audit my eRPC healthcheck config in my eRPC config: I'm seeing false-positive 502s from my readiness probe right after deploys before traffic warms up. Recommend the right eval strategy (or strategy combination) for startup vs. steady-state, explain the tradeoffs of any:initializedUpstreams vs errorRate vs all:activeUpstreams for my setup, and update the config accordingly. Reference: https://docs.erpc.cloud/operation/healthcheck.llms.txt ``` **Prompt Example #3: verify chain integrity before routing traffic** ```text Add a strict chain-ID verification probe to my eRPC deployment so no upstream gets traffic unless it's confirmed to be on the right EVM chain. Use all:evm:eth_chainId on the readiness probe and show me how to size timeoutSeconds for my upstream count. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/healthcheck.llms.txt ``` **Prompt Example #4: expose verbose diagnostics for monitoring dashboard** ```text Switch my eRPC healthcheck to verbose mode and add network-scoped auth so my internal monitoring system can query per-upstream metrics and EVM diagnostics without sharing project API secrets. Lock access to private RFC-1918 CIDRs. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/healthcheck.llms.txt ``` **Prompt Example #5: debug why my healthcheck returns 502 after restart** ```text My eRPC readiness probe returns HTTP 502 for the first minute after every pod restart. Diagnose whether this is the error-rate cold-start problem (no traffic yet), the lazy-init delay on first per-network probe, or a misconfigured eval strategy, and fix my config at my eRPC config so restarts are clean. Reference: https://docs.erpc.cloud/operation/healthcheck.llms.txt ``` --- ### Healthcheck — full agent reference ### How it works **Trigger paths.** Any HTTP request that is not `POST` or `OPTIONS` is treated as a healthcheck by the URL parser. A trailing `/healthcheck` path segment also forces the healthcheck branch regardless of method. Valid probe paths, from broadest to narrowest scope: - `GET /` — global (all projects) - `GET /healthcheck` — same as above - `GET //healthcheck` — per-project - `GET ////healthcheck` — per-network (e.g. `GET /main/evm/1/healthcheck`) For domain-aliased deployments where a domain preselects all three of project + arch + chain, `GET /` resolves to a per-network probe after alias expansion. **Draining guard.** Before any evaluation the handler checks a `draining` flag. When the server context is cancelled (SIGTERM received), `draining` flips to `true` and the endpoint immediately returns HTTP 503 with plain-text body `"shutting down"`. This is the Kubernetes readiness-probe hook: the pod is removed from the load balancer pool while in-flight requests complete. Because 503 means "draining" and 502 means "unhealthy", Kubernetes can distinguish the two states and avoid triggering a pod restart during normal rollout. **Auth.** When `healthCheck.auth` is configured, an independent `AuthRegistry` is created at startup. On every probe call the registry authenticates using the real client IP (resolved from trusted-proxy headers). Auth is completely separate from per-project auth — monitoring systems can reach the healthcheck without sharing application credentials. **Scope resolution.** With no `projectId`, the handler fetches all registered projects (HTTP 500 only if zero projects exist). With `projectId` set, a missing project returns the same 404 structure as the proxy path. When both `architecture` and `chainId` are in the URL, only that network is evaluated and the project result mirrors it; otherwise `evaluateProjectHealth` aggregates across all upstreams. **Lazy upstream initialization.** When a per-network probe arrives and no upstreams are registered for that network yet, the handler calls `PrepareUpstreamsForNetwork` — the exact same path used by the first real RPC request. This prevents a false-negative "no upstreams initialized" on the very first probe after pod startup. The first probe for a new network may take hundreds of milliseconds; subsequent probes are fast. **Provider-only project shortcut.** If a project has providers configured but zero statically-defined upstreams and zero initialized upstreams, the handler marks the project healthy immediately (message: `"no upstreams initialized yet, and no networks configured, but there are providers configured, send first actual request to initialize the upstreams"`). This prevents provider-based projects from appearing unhealthy before the first real RPC call. **Evaluation strategies.** The `?eval=` query parameter (or `healthCheck.defaultEval`, or the hard-coded default `any:initializedUpstreams`) selects the evaluation strategy. An unknown eval value returns HTTP 502 with `"unknown evaluation strategy: "` — not HTTP 400. The `?eval=` parameter always overrides `healthCheck.defaultEval` per-request. **Error-rate strategies.** These compute `errorsTotal / requestsTotal` from the health tracker's `*`-method and `DataFinalityStateAll` bucket. Only upstreams with at least one request are included; upstreams with zero requests are completely excluded — they do not count toward threshold violations, but they also do not count as healthy for the `all:…` variants. If all upstreams have zero traffic, the result is unhealthy: `"no error rate data available yet"`. **Chain-ID strategy.** `checkEvmChainId` fans out concurrent `eth_chainId` RPC calls (semaphore capped at 10, 5-second per-upstream timeout) and compares each response to `ups.Config().Evm.ChainId`. For `any:`, one success passes the probe; for `all:`, every upstream must pass. With partial success under `any:`, the message is `"N / M upstreams passed (K failed)"`. **Active-upstreams strategy.** `all:activeUpstreams` checks: (1) at least one upstream or provider is configured; (2) all statically declared upstreams are initialized; (3) none are cordoned. For provider-only setups, check (2) is skipped. When evaluating a specific network, only upstreams whose chain ID matches are counted — cross-network upstreams are not penalized. **Response modes.** Controlled by `healthCheck.mode`: - **`simple`** — HTTP 200 with plain ASCII `OK`; HTTP 502 with a JSON-RPC `ErrHealthCheckFailed` error body on failure. - **`networks`** — HTTP 200/502 with `Content-Type: application/json`; body `{"projectId": [{id, alias, blockTimeMs, state}]}`. - **`verbose`** — Full JSON `{status, message, details}` with per-upstream metrics and EVM diagnostics. Metrics use `*`-wildcard aggregate (all methods, all finality states); method-level breakdown requires Prometheus. **HTTP status code semantics:** | Code | Condition | Body | |---|---|---| | 200 | All evaluated projects/networks healthy | `OK` (simple), JSON list (networks), full JSON (verbose) | | 502 | One or more projects/networks unhealthy | JSON-RPC error (simple), JSON with `state:"ERROR"` entries (networks/verbose) | | 503 | Server draining (readiness hook) | `shutting down` — always plain text | ### Config schema All fields are under `healthCheck.` at the top level of the eRPC config. Struct at [`common/config.go:L186-208`](https://github.com/erpc/erpc/blob/main/common/config.go#L186-L208). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `healthCheck.mode` | `"simple"` \| `"networks"` \| `"verbose"` | `"networks"` (set by `HealthCheckConfig.SetDefaults`) | Controls response verbosity. **Footgun:** a nil `HealthCheckConfig` (no `healthCheck:` key at all) falls back to `"simple"` inside `handleHealthCheck` — but `SetDefaults` sets `"networks"` if the key is present. Source: [`common/defaults.go:L738-741`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L738-L741), [`erpc/healthcheck.go:L399-403`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L399-L403) | | `healthCheck.defaultEval` | string | `"any:initializedUpstreams"` (hard-coded fallback when both query param and config field are empty) | Default eval strategy when `?eval=` is absent. Must be one of the 8 strategy constants. An unrecognized value returns HTTP 502 with `"unknown evaluation strategy: "`. Source: [`erpc/healthcheck.go:L107-112`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L107-L112), [`common/config.go:L189`](https://github.com/erpc/erpc/blob/main/common/config.go#L189) | | `healthCheck.auth` | `*AuthConfig` | `nil` (endpoint open) | Creates an independent `AuthRegistry` for the healthcheck path. All auth strategies supported by `AuthConfig` work here. **Footgun:** kubelet probes originate from the node IP, not `127.0.0.1` — `allowLocalhost: true` alone does not cover node-originated probes; add the node/pod CIDR to `allowedCIDRs`. Source: [`common/config.go:L188`](https://github.com/erpc/erpc/blob/main/common/config.go#L188), [`erpc/http_server.go:L201-207`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L201-L207) | **Eval strategy constants** (for `healthCheck.defaultEval` or `?eval=` query parameter). Source: [`common/config.go:L200-208`](https://github.com/erpc/erpc/blob/main/common/config.go#L200-L208). | Value | Go constant | Healthy when | |---|---|---| | `any:initializedUpstreams` | `EvalAnyInitializedUpstreams` | ≥ 1 upstream registered in the registry | | `any:errorRateBelow90` | `EvalAnyErrorRateBelow90` | ≥ 1 traffic-bearing upstream has error rate < 90% | | `all:errorRateBelow90` | `EvalAllErrorRateBelow90` | All traffic-bearing upstreams have error rate < 90% | | `any:errorRateBelow100` | `EvalAnyErrorRateBelow100` | ≥ 1 traffic-bearing upstream has error rate < 100% | | `all:errorRateBelow100` | `EvalAllErrorRateBelow100` | All traffic-bearing upstreams have error rate < 100% | | `any:evm:eth_chainId` | `EvalAnyEvmEthChainId` | ≥ 1 upstream returns the expected chain ID (live call, semaphore=10, 5s timeout) | | `all:evm:eth_chainId` | `EvalAllEvmEthChainId` | Every upstream returns the expected chain ID | | `all:activeUpstreams` | `EvalAllActiveUpstreams` | All static upstreams initialized AND none cordoned | ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. The production standard: verbose mode + 30s drain window (high-volume fleet).** Every Some production deployments use `verbose` mode so internal dashboards can inspect per-upstream metrics on a single URL, paired with a 30s drain window that safely outlasts the longest in-flight RPC batch: **Config path:** `server + healthCheck` **YAML — `erpc.yaml`:** ```yaml server: # drain window must exceed readinessProbe.periodSeconds × failureThreshold # so the pod is fully deregistered before connections close waitBeforeShutdown: 30s waitAfterShutdown: 30s healthCheck: # verbose exposes per-upstream metrics + evmDiagnostics in a single response — # no Prometheus scrape needed for incident triage mode: verbose ``` **TypeScript — `erpc.ts`:** ```typescript server: { // drain window must exceed readinessProbe.periodSeconds × failureThreshold // so the pod is fully deregistered before connections close waitBeforeShutdown: "30s", waitAfterShutdown: "30s", }, healthCheck: { // verbose exposes per-upstream metrics + evmDiagnostics in one response — // no Prometheus scrape needed for incident triage mode: "verbose", }, ``` **2. Kubernetes startup + readiness split (recommended general shape).** Traffic-facing clusters separate startup (just needs an upstream registered) from readiness (needs live traffic flowing). This avoids a 502 storm on cold start before any upstream has been hit: **Config path:** `server + healthCheck + k8s probes` **YAML — `erpc.yaml`:** ```yaml server: # 30s outlasts the readiness window (5s × 2 + 20s buffer) waitBeforeShutdown: 30s healthCheck: # networks mode is cheaper for k8s probes — no per-upstream JSON overhead mode: networks # default: any:initializedUpstreams — safe at cold start, used by readiness defaultEval: "any:initializedUpstreams" auth: strategies: - type: network network: # kubelet probes originate from the node IP, not 127.0.0.1 — # allowLocalhost: true alone is not enough, add node/pod CIDRs allowLocalhost: true allowedCIDRs: - "10.0.0.0/8" ``` **TypeScript — `erpc.ts`:** ```typescript server: { waitBeforeShutdown: "30s" }, healthCheck: { // networks mode is cheaper for k8s probes — no per-upstream JSON overhead mode: "networks", // safe at cold start: passes as soon as any upstream is registered defaultEval: "any:initializedUpstreams", auth: { strategies: [{ type: "network", network: { // kubelet probes originate from the node IP, not 127.0.0.1 — // allowLocalhost: true alone is not enough, add node/pod CIDRs allowLocalhost: true, allowedCIDRs: ["10.0.0.0/8"], }, }], }, }, ``` Kubernetes probe manifest to pair with the config above: ```yaml startupProbe: httpGet: path: /healthcheck?eval=any:initializedUpstreams port: 4000 initialDelaySeconds: 10 periodSeconds: 10 timeoutSeconds: 5 # allow up to 60s for the very first upstream to initialize failureThreshold: 6 readinessProbe: httpGet: # uses defaultEval from config (any:initializedUpstreams) path: /healthcheck port: 4000 periodSeconds: 5 timeoutSeconds: 5 failureThreshold: 2 successThreshold: 1 livenessProbe: # TCP socket — never use httpGet here: 503 during normal drain triggers restart tcpSocket: port: 4000 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 ``` **3. Strict chain-ID verification before routing traffic.** Use when upstreams could silently be on the wrong chain — after a provider migration, when serving high-value transactions, or any time a misconfigured chain would cause irreversible damage. The fan-out runs at concurrency 10 with a 5s per-upstream timeout: ```yaml readinessProbe: httpGet: # all: variant: every upstream must return the expected chain ID path: /healthcheck?eval=all:evm:eth_chainId port: 4000 periodSeconds: 15 # budget ceil(N_upstreams / 10) × 5s + 2s margin # e.g. 6 upstreams → ceil(6/10)×5 + 2 = 7s; use 15 for safety timeoutSeconds: 15 failureThreshold: 2 ``` **4. Multi-region edge with per-network probe.** Multi-region edge clusters use `networks` mode so load-balancer health checks see a compact JSON list. The per-network URL lets the LB probe only the chain it cares about, avoiding false positives from an unrelated chain's degradation: **Config path:** `healthCheck` **YAML — `erpc.yaml`:** ```yaml healthCheck: # compact JSON list: {"projectId": [{id, alias, blockTimeMs, state}]} # fast for LB health checks; verbose is too heavy at LB poll frequency mode: networks ``` **TypeScript — `erpc.ts`:** ```typescript healthCheck: { // compact JSON list: {"projectId": [{id, alias, blockTimeMs, state}]} // fast for LB health checks; verbose is too heavy at LB poll frequency mode: "networks", }, ``` Probe URL (narrows to one chain — first call for an uninitialized network triggers lazy init, budget extra `timeoutSeconds`): ``` GET /myproject/evm/1/healthcheck?eval=any:evm:eth_chainId ``` **5. Verbose diagnostics endpoint for monitoring with RFC-1918 auth.** Internal SRE dashboards and alert rules need per-upstream detail without sharing application API keys. Lock to private CIDRs — both `allowLocalhost` and RFC-1918 ranges are needed because monitoring agents typically run on a pod IP, not `127.0.0.1`: **Config path:** `healthCheck` **YAML — `erpc.yaml`:** ```yaml healthCheck: mode: verbose # all:activeUpstreams fails if any declared upstream is uncordoned but uninitialized # — stronger than error-rate strategies which require prior traffic defaultEval: "all:activeUpstreams" auth: strategies: - type: network network: allowLocalhost: true allowedCIDRs: - "10.0.0.0/8" - "172.16.0.0/12" - "192.168.0.0/16" ``` **TypeScript — `erpc.ts`:** ```typescript healthCheck: { mode: "verbose", // all:activeUpstreams fails if any declared upstream is uncordoned but uninitialized // — stronger than error-rate strategies which require prior traffic defaultEval: "all:activeUpstreams", auth: { strategies: [{ type: "network", network: { allowLocalhost: true, allowedCIDRs: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], }, }], }, }, ``` ### Request/response behavior **Response shape — `networks` mode (HTTP 200):** ```json { "projectId": [ {"id": "evm:1", "alias": "mainnet", "blockTimeMs": 12000.0, "state": "OK"}, {"id": "evm:42161", "state": "ERROR"} ] } ``` **Response shape — `verbose` mode (HTTP 200):** ```json { "status": "OK", "message": "all systems operational", "details": { "projectId": { "status": "OK", "message": "...", "config": {"networks": 2, "upstreams": 3, "providers": 0}, "initializer": {"...": "InitializerStatus"}, "upstreams": { "upsId": { "network": "evm:1", "metrics": {"...": "aggregate across all methods"}, "evmDiagnostics": {"...": "EVM state poller data"} } }, "networks": { "evm:1": {"status": "OK", "alias": "mainnet", "blockTimeMs": 12000.0} } } } } ``` **Response shape — `simple` mode, unhealthy (HTTP 502):** The body is a structured `ErrHealthCheckFailed` JSON-RPC error — not a plain string. Clients that parse JSON-RPC errors get structured data even in simple mode. **Drain response (HTTP 503, any mode):** `http.Error(w, "shutting down", 503)` sets `Content-Type: text/plain`. Clients that always expect JSON will fail to parse this. This is intentional — it must be distinguishable from a normal 502 unhealthy response. ### Best practices - Use **separate strategies for startup vs. readiness probes**: `any:initializedUpstreams` for startup (no traffic required), `any:errorRateBelow90` for readiness (requires live traffic). Mixing them leads to either false-positive failures at startup or missed degradation in production. - **Never put the healthcheck path on a liveness probe.** The endpoint returns 503 during normal graceful shutdown, which triggers pod restart on every rollout. Use a TCP socket liveness probe instead. - **Add node/pod CIDRs to `allowedCIDRs`** when using `healthCheck.auth` — kubelet probes originate from the node IP, not `127.0.0.1`, so `allowLocalhost: true` alone will silently reject them. - **Budget extra `timeoutSeconds`** when using `any:evm:eth_chainId` or `all:evm:eth_chainId` with many upstreams: the fan-out runs at concurrency 10 with a 5s per-upstream timeout, so worst-case latency is `ceil(N/10) × 5s`. - **Set `waitBeforeShutdown` ≥ `periodSeconds × failureThreshold + 1s`** on your readiness probe. Without this, traffic may still be routed to the pod after 503 has been returned, causing request failures during rollout. - **Use `mode: verbose`** only for monitoring dashboards or debugging. In high-cardinality deployments the verbose response can be large; `networks` mode is sufficient for Kubernetes probes. - **For provider-based projects** (upstreams created dynamically on first RPC call), `any:initializedUpstreams` will return unhealthy until the first real request triggers initialization. Accept this false-negative window or use the startup probe to absorb it. ### Edge cases & gotchas 1. **Draining returns 503 plain text, not JSON.** `http.Error(w, "shutting down", 503)` sets `Content-Type: text/plain`. Clients that always expect JSON will fail to parse this response. This is the readiness-probe hook — liveness probes on `/healthcheck` will trigger pod restart during normal graceful shutdown. 2. **`any:initializedUpstreams` does not confirm the upstream can serve requests.** An upstream registers even if its chain-ID probe is still pending or has failed. Use `all:activeUpstreams` or a chain-ID strategy for stronger guarantees. Source: [`erpc/healthcheck.go:L59-77`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L59-L77) 3. **Error-rate strategies require prior traffic.** Fresh instances return `"no error rate data available yet"` (HTTP 502) until at least one upstream has processed a request. Use `any:initializedUpstreams` for startup probes. Source: [`erpc/healthcheck.go:L465-471`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L465-L471) 4. **First per-network probe may be slow.** `PrepareUpstreamsForNetwork` triggers internal chain-ID RPC probes on first call; allow extra `timeoutSeconds` on the startup probe for this network initialization. Source: [`erpc/healthcheck.go:L175-181`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L175-L181) 5. **Global healthcheck fails if no projects are registered.** If all projects fail to register at startup, `GET /healthcheck` returns HTTP 500 even though the HTTP server itself is up. Source: [`erpc/healthcheck.go:L122-127`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L122-L127) 6. **Unknown eval value returns HTTP 502, not HTTP 400.** `evaluateNetworkHealth` falls through to its `default:` branch — watch for the exact prefix `"unknown evaluation strategy: "` when debugging misconfigured eval strings. Source: [`erpc/healthcheck.go:L550-551`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L550-L551) 7. **Healthcheck auth always exposes full error details.** Unlike most proxy errors that respect `server.includeErrorDetails`, project/network resolution errors from the healthcheck handler always include the project ID in the error body. Source: [`erpc/healthcheck.go:L130-133`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L130-L133) 8. **Duplicate network alias is silently dropped.** If two `NetworkConfig` entries share the same `alias`, only the first registration wins; the second is dropped with a WARN log. Source: [`erpc/networks_registry.go:L340-344`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L340-L344) 9. **`all:activeUpstreams` with provider-only projects bypasses the initialization check.** Even if the provider has 0 initialized upstreams, `hasUninitializedUpstreams` is forced `false`. The probe can still fail if 0 upstreams AND 0 providers are configured. Source: [`erpc/healthcheck.go:L663-670`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L663-L670) 10. **`verbose` mode metrics use `*` wildcard aggregate.** `metricsTracker.GetUpstreamMethodMetrics(ups, "*", DataFinalityStateAll)` is rolled up across all methods and finality states. Method-level breakdown requires Prometheus. Source: [`erpc/healthcheck.go:L259-262`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L259-L262) 11. **`any:evm:eth_chainId` with partial success is healthy.** If some upstreams fail but at least one passes, the result is HTTP 200 with message `"N / M upstreams passed (K failed)"`. Under `all:`, any single failure makes the probe unhealthy. Source: [`erpc/healthcheck.go:L896-905`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go#L896-L905) 12. **`LastEvalAt` is non-zero after Bootstrap.** The health tracker records the timestamp of the most recent evaluation in `LastEvalAt`. Health-check exporters and external probers can use this field to detect stale selection state (no policy evaluation tick has occurred since startup). Source: [`erpc/healthcheck_test.go:L26-L45`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck_test.go#L26-L45) ### Observability The healthcheck handler does not emit any dedicated Prometheus metrics. The general `erpc_unexpected_panic_total` counter fires if the handler panics. | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_unexpected_panic_total` | counter | subsystem | Handler panics only; not expected in normal operation | **OTel tracing:** `handleHealthCheck` runs within the `Http.ReceivedRequest` span started by the top-level handler. `common.EnrichHTTPServerSpan` sets the `http.status_code` attribute before the response is written. **Log messages:** - `"entering draining mode → healthcheck will fail"` — INFO when app context is cancelled - `"failed to encode health check response"` — ERROR on JSON encoding failure - `"registered network alias"` — DEBUG on each successful alias registration. Source: [`erpc/networks_registry.go:L347`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L347) - `"skipping duplicate alias registration with different target"` — WARN on duplicate network alias ### Source code entry points - [`erpc/healthcheck.go:L1-L913`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck.go) — `handleHealthCheck`, `evaluateNetworkHealth`, `evaluateProjectHealth`, `formatHealthDataForMode`, `checkEvmChainId`; all response struct definitions - [`erpc/http_server.go:L78-L83`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L78-L83) — draining flag set when app context is done; INFO log `"entering draining mode → healthcheck will fail"` - [`erpc/http_server.go:L201-L207`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L201-L207) — healthcheck auth registry construction at startup - [`erpc/http_server.go:L836-L849`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L836-L849) — URL path parsing: healthcheck detection logic (non-POST/OPTIONS + trailing `/healthcheck`) - [`common/config.go:L186-L208`](https://github.com/erpc/erpc/blob/main/common/config.go#L186-L208) — `HealthCheckConfig` struct, `HealthCheckMode` constants, eval-strategy constants - [`common/defaults.go:L738-L741`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L738-L741) — `HealthCheckConfig.SetDefaults`; canonical default mode `"networks"` - [`erpc/healthcheck_test.go`](https://github.com/erpc/erpc/blob/main/erpc/healthcheck_test.go) — integration tests for all eval strategies, drain mode, auth, provider-only, specific network scoping - [`erpc/networks_registry.go:L247-L255`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L247-L255) — `ResolveAlias` used to expand per-project network aliases during healthcheck path parsing ### Related pages - [Auth](/config/auth.llms.txt) — same strategy schema used for `healthCheck.auth` - [Server configuration](/operation/server.llms.txt) — `server.waitBeforeShutdown` must be tuned alongside readiness probe thresholds - [Rate limiters](/config/rate-limiters.llms.txt) — independent from healthcheck but affects upstream error rates that feed into `errorRate*` eval strategies - [Deployment](/deployment.llms.txt) — Kubernetes deployment patterns including probe configuration - [Observability](/operation/metrics.llms.txt) — Prometheus metrics for upstream health beyond what healthcheck exposes --- --- # Monitoring & metrics > Source: https://docs.erpc.cloud/operation/monitoring > Every subsystem in eRPC — upstreams, cache, rate limits, consensus, hedging — emits Prometheus metrics. One scrape target, full visibility, zero instrumentation work. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Monitoring & metrics eRPC publishes 122 Prometheus metrics covering every subsystem: upstream health and latency, cache hit rates, rate limiting, block-head lag, consensus outcomes, and selection-policy scoring. One scrape target on port 4001 and a ready-made Grafana dashboard are all you need to go from blind to fully instrumented. **What you get** - Real-time upstream health: lag, latency p95, error rate, cordon and circuit-breaker state - Cache effectiveness: hit/miss ratios, age-guard rejects, memory-connector pressure - Traffic and rate-limit visibility: local budget triggers, upstream 429 passthroughs, fail-open events - Consensus and resilience: misbehavior detection, retry pressure, hedge win/discard counts - Cardinality controls: drop high-cost labels globally and restore them per-histogram ## Quick taste Illustrative, not a tuned production config — enable metrics on port 4001 with compact error labels: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: # start the Prometheus scrape endpoint enabled: true # default port; Prometheus scrapes http://:4001/metrics port: 4001 # compact keeps error label values short and bounded — never use verbose in production errorLabelMode: compact ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { // start the Prometheus scrape endpoint enabled: true, // default port; Prometheus scrapes http://:4001/metrics port: 4001, // compact keeps error label values short and bounded — never use verbose in production errorLabelMode: "compact", } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up metrics scraping from scratch** ```text I have a new eRPC deployment and want to enable Prometheus metrics so I can scrape upstream health, cache hit rates, and request latency from my Grafana stack. Enable the metrics endpoint on port 4001 with compact error labels and histogram buckets tuned to my expected p50-p99 range (sub-second to a few seconds). Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/operation/monitoring.llms.txt ``` **Prompt Example #2: reduce histogram cardinality for managed Prometheus** ```text My Grafana Cloud scraper is hitting its /metrics body-size limit. Drop high-cardinality histogram labels globally from my eRPC config, but preserve the user label on the network-level duration histogram so I keep per-client latency SLOs. Also tighten histogram buckets to my observed p50-p99 range. Reference: https://docs.erpc.cloud/operation/monitoring.llms.txt ``` **Prompt Example #3: debug a metric that always reads zero** ```text My erpc_ristretto_cache_current_cost gauge is always 0 even though my memory cache connector is configured and traffic is flowing. Diagnose why and fix my eRPC config so the metric emits real values. Reference: https://docs.erpc.cloud/operation/monitoring.llms.txt ``` **Prompt Example #4: audit bundled alerting rules for stale metric names** ```text Review the bundled Prometheus alerting rules for my eRPC instance and fix any references to deprecated or stale metric names. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/monitoring.llms.txt ``` **Prompt Example #5: understand why error labels look different across series** ```text Some of my erpc_network_failed_request_total series have verbose error label values (containing block numbers and IP addresses) while others have compact codes. Explain why this happens and update my eRPC config to make all new series use compact labels. Reference: https://docs.erpc.cloud/operation/monitoring.llms.txt ``` --- ### Monitoring — full agent reference ### How it works The metrics HTTP server binds `:` (all interfaces) and registers the Prometheus handler as the root handler. Because there is no path routing, every URL path on the metrics port — `GET /`, `GET /metrics`, `GET /health` — returns the identical full Prometheus text exposition. There is no TLS, no auth, and no gzip on the metrics endpoint. All 141 metric families are declared unregistered at package-init time and registered by `telemetry.Configure` during `erpc.Init`, once `metrics.customizations` and the bucket list are known. Prometheus freezes a family's label-set hash for the life of the registry, so label-set changes have to happen before the first registration — which is also why a family a customization drops is simply never registered and costs no series at all. Changing `metrics.customizations` at runtime does nothing to families already registered; it takes a restart. An idle-eviction sweep runs every ~5 minutes and calls `DeleteLabelValues` on stale `erpc_upstream_request_duration_seconds` and `erpc_rate_limits_total` series to prevent cardinality runaway under method-flood attacks. Counters emitted through `telemetry.CounterHandle` (upstream request/error totals, network success/hedge counters, etc.) are swept on the same cadence with their own, more conservative threshold — `metrics.counterIdleEvictionAfter`, default `24h` — so counter series whose label combinations go quiet (stale `method` × `user` × `agent_name` tuples) are eventually released instead of being re-emitted on every scrape for the process lifetime. A swept series that becomes active again restarts at zero, the same semantics as a process restart. Remaining high-cardinality metrics are bounded only by distinct (project, network, upstream, method) tuples. **`LabeledHistogram` label filtering.** `WithLabelValues` always receives the full canonical label set in schema order; the wrapper projects down to the active (post-filter) subset before forwarding to the underlying `prometheus.HistogramVec`. Call sites never need to know which labels survived. Length mismatches panic immediately to surface wiring bugs. `ActiveLabelValues` returns the projected subset so handle-caches key on the effective labels, preventing duplicate cache entries when multiple full-label tuples collapse to the same series. **Idle-series eviction detail.** Sweep fires every 10 rotation ticks of `rotateMetricsLoop` (default tick = 30s, so sweep ≈ every 5 min). `sweepIdle` walks `upsMetrics` and `ntwMetrics` sync.Maps and deletes entries not accessed in the last 30 min. For `upstream_request_duration_seconds` and `rate_limits_total` it additionally calls `DeleteLabelValues` on the Prometheus registry. Cordoned entries and wildcard (`"*"`) rollups are never evicted. **`errorLabelMode` global.** `compact` mode produces short stable codes like `ErrEndpointCapacityExceeded` or `ErrUpstreamRequest/ErrJsonRpcExceptionInternal/-32000`. `verbose` mode emits the full message chain, potentially including block numbers or IP addresses — unbounded cardinality risk. Default before `erpc.Init` runs is `verbose`; `Init` sets it to the config value (default `compact`). Series created before `Init` carry `verbose` labels and will coexist until they expire naturally. `compact` label output in full: `StandardError` → `string(be.Base().Code)` (e.g. `ErrEndpointCapacityExceeded`); for `ErrFailsafeRetryExceeded`/`ErrUpstreamRequest`/`ErrUpstreamRequestSkipped` appends cause code (`ErrUpstreamRequest/ErrEndpointTransportFailure`); for `ErrJsonRpcExceptionInternal` cause appends numeric code (`ErrUpstreamRequest/ErrJsonRpcExceptionInternal/-32000`). `context.DeadlineExceeded` → `ContextDeadlineExceeded`. `context.Canceled` → `ContextCanceled`. Plain error → `GenericError`. Unknown → `UnknownError`. Source: [`common/errors.go:L46-66`](https://github.com/erpc/erpc/blob/main/common/errors.go#L46-L66). **Handle caching.** `CounterHandle`, `GaugeHandle`, and `ObserverHandle` in [`telemetry/handles.go`](https://github.com/erpc/erpc/blob/main/telemetry/handles.go) cache `prometheus.Counter`/`Gauge`/`Observer` children in `sync.Map`s keyed by `{Vec pointer, '\x1f'-joined label values}`. This avoids a per-observation map lookup and mutex contention inside the Prometheus library. For `LabeledHistogram` observers the key uses post-filter label values so the cache is filter-aware. `ResetHandleCache` wipes all three maps and is called after `SetHistogramBuckets` when Vecs are re-created. Source: [`telemetry/handles.go:L86-105`](https://github.com/erpc/erpc/blob/main/telemetry/handles.go#L86-L105). **Repeat `Configure` is a no-op on registered families.** A second `telemetry.Configure` (or `SetHistogramBuckets`) skips every family already registered with the same registerer, leaving its label set, buckets, and accumulated values untouched. Only families still unregistered — because an earlier call was `Configure(nil)` or `SetHistogramBuckets`, which register histograms only — pick up the new configuration. Source: [`telemetry/manager.go:L226-256`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go#L226-L256). **`networkAlias` resolver.** At startup `erpc.Init` installs a `common.NetworkAliasResolver` callback that maps raw EVM chain IDs to human-readable network aliases. Components that only know a numeric chainId (e.g. the gRPC cache connector) use this resolver so their metric `network` labels match the alias used by every other metric in the system. Source: [`erpc/init.go:L95-110`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L95-L110). ### Config schema All fields under `metrics.` in the YAML root config. Struct: [`common/config.go:L2898-2970`](https://github.com/erpc/erpc/blob/main/common/config.go#L2898-L2970). Defaults: [`common/defaults.go:L908-931`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L908-L931). Validation: [`common/validation.go:L139-170`](https://github.com/erpc/erpc/blob/main/common/validation.go#L139-L170). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `metrics.enabled` | `*bool` | `true` in production; `nil` (disabled) under `go test` | Whether to start the `/metrics` HTTP server. When false or nil, no server starts; metrics still accumulate in-process. Source: [`common/defaults.go:L909-911`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L909-L911) | | `metrics.port` | `*int` | `4001` | TCP port for the metrics HTTP server. Required when `enabled=true`; `erpc.Init` aborts if nil. Default `4001` = main HTTP port (4000) + 1. Source: [`common/defaults.go:L918-920`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L918-L920) | | `metrics.hostV4` | `*string` | `"0.0.0.0"` | **Defined but not used.** The server always binds `":"` (all interfaces) regardless of this value. Use a firewall or network policy to restrict scrape access. Source: [`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189) | | `metrics.listenV4` | `*bool` | `nil` | **Dead field.** Defined in struct but never read in production code. | | `metrics.hostV6` | `*string` | `"[::]"` | **Defined but not used.** Same caveat as `hostV4`. Source: [`common/defaults.go:L915-917`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L915-L917) | | `metrics.listenV6` | `*bool` | `nil` | **Dead field.** Defined in struct but never read in production code. | | `metrics.errorLabelMode` | `string` | `"compact"` | Controls the `error` label via `common.ErrorSummary`. `"compact"` → short stable codes (bounded cardinality, recommended). `"verbose"` → full human-readable messages including block numbers / IPs (unbounded cardinality risk). Applied at `erpc.Init`. Note: the in-code default before `Init` runs is `verbose` — a mix of both modes appears until verbose series expire. Source: [`common/defaults.go:L921-923`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L921-L923) | | `metrics.histogramBuckets` | `string` | `""` → `[0.05, 0.5, 5, 30]` | Comma-separated float64 bucket boundaries for every histogram that does not declare its own buckets: `upstream_request_duration_seconds`, `network_request_duration_seconds`, `consensus_duration_seconds`, `cache_set_success/error_duration_seconds`, `cache_get_success_hit/miss/error_duration_seconds`. Invalid float → warning + fallback to defaults. Source: [`telemetry/metrics.go:L943-948`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L943-L948) | | `metrics.customizations` | `[]object` | `nil` | The single knob for shaping `/metrics`. Each entry is `{subject, action?, labels?, buckets?}`. Startup-only — everything is resolved before the first registration, so a change needs a restart. Overlapping entries resolve by specificity (exact name > longer prefix > shorter prefix > `*`), not by list order. Source: [`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go) | | `metrics.customizations[].subject` | `string` | required | An exact family name (`"upstream_request_total"`), a prefix ending in `*` (`"consensus_*"`), or `*` for everything. The `erpc_` prefix is optional. Stock collectors are named in full (`"go_goroutines"`, `"process_*"`, `"promhttp_*"`) and obey the same rules. `*` is only legal as the final character; a subject may not be repeated. | | `metrics.customizations[].action` | `"keep"` \| `"drop"` | none | `drop` removes the matched families; `keep` spares them from a broader `drop`. A dropped eRPC family is never registered, so it costs no series, no collection time and no scrape bytes; a dropped stock collector is filtered out of the scrape response instead. Omit `action` to customize labels or buckets only. | | `metrics.customizations[].labels` | `[]object` | `nil` | `{subject, action}` entries projecting the matched families' label sets, same precedence applied to label names — `agent_*: drop` then `agent_name: keep` drops the group and spares one label. Sums are preserved when a label is dropped (the series that differed only in it collapse into one), but the dimension stops being queryable, so verify nothing downstream groups by it first. Counters and histograms are projected; gauges are not. | | `metrics.customizations[].buckets` | `[]float64` | `nil` | Bucket boundaries for the matched histograms, overriding both `metrics.histogramBuckets` and what the metric declares in code. Must be strictly increasing. | | `metrics.counterIdleEvictionAfter` | `Duration` | `24h` | Idle threshold after which counter series emitted via `telemetry.CounterHandle` are evicted from the registry (`DeleteLabelValues`), bounding `/metrics` growth from caller-controlled label values (`method`, `user`, `agent_name`). `0` disables. Swept on the health tracker's sweep cadence. Source: [`common/config.go:L2946-2955`](https://github.com/erpc/erpc/blob/main/common/config.go#L2946-L2955) | | `metrics.histogramDropLabels`, `metrics.histogramLabelOverrides`, `metrics.counterDropLabels`, `metrics.counterLabelOverrides` | `[]string` / `map[string][]string` | `nil` | **Deprecated** — replaced by `customizations`. Still honored: each is desugared onto the same rule engine (the `*DropLabels` pair as kind-scoped `*` label drops, the `*Overrides` pair as exact-subject keeps). An equally broad `customizations` entry outranks them. Source: [`common/config.go:L2928-2944`](https://github.com/erpc/erpc/blob/main/common/config.go#L2928-L2944) | **Hardcoded server constants (not configurable):** - Bind address: `":"` (all interfaces) — [`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189) - Handler: the Prometheus handler registered as root, over a gatherer wrapped by `telemetry.Gatherer`; every URL path returns full metrics output — [`erpc/init.go:L190-195`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L190-L195) - Protocol: plain HTTP only — no TLS, no auth, no gzip - `ReadHeaderTimeout`: 10 seconds - Graceful shutdown budget: 5 seconds — [`erpc/init.go:L207`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L207) **Histogram bucket constants** — only `DefaultHistogramBuckets` are configurable via `metrics.histogramBuckets`. The rest are compiled in, but any of them can be overridden per family with `customizations[].buckets`: | Bucket set | Values | Applies to | |---|---|---| | `DefaultHistogramBuckets` (configurable) | 0.05, 0.5, 5, 30 | `upstream_request_duration_seconds`, `network_request_duration_seconds`, `consensus_duration_seconds`, `cache_set_success_duration_seconds`, `cache_set_error_duration_seconds`, `cache_get_success_hit_duration_seconds`, `cache_get_success_miss_duration_seconds`, `cache_get_error_duration_seconds` | | `EvmGetLogsRangeHistogramBuckets` | 1, 10, 100, 500, 1000, 5000, 10000, 30000 blocks | `network_evm_get_logs_range_requested`, `network_evm_trace_filter_range_requested` | | `CatchUpWaitHistogramBuckets` | 0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64 s | `network_data_unavailable_wait_seconds` | | hedge delay (inline) | 0.01, 0.03, 0.05, 0.2, 0.3, 0.5, 0.7, 1, 3 s | `network_hedge_delay_seconds` (dormant) | | timeout duration (inline) | 0.05, 0.1, 0.3, 0.5, 1, 3, 5, 10, 30 s | `network_timeout_duration_seconds` | | selection eval (inline) | 0.0005, 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1 s | `selection_eval_duration_seconds` | | readmit age (inline) | 1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600 s | `selection_readmit_age_seconds` | | cordon duration (inline) | 1, 10, 60, 300, 900, 1800, 3600, 7200, 21600, 86400 s | `upstream_cordon_duration_seconds` | | rate-limiter remote (inline) | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5 s | `rate_limiter_remote_duration_seconds` | | response size (inline) | 4096, 65536, 1048576, 16777216, 104857600 bytes | `upstream_response_size_bytes` | | consensus counts (LinearBuckets) | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 | `consensus_responses_collected`, `consensus_agreement_count` | Source: [`telemetry/metrics.go:L731-932`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L731-L932). ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Single-region deployment — compact labels, tighter buckets.** Used by edge and data-indexing deployments where latency spans ~5ms cache hits through ~10s heavy getLogs. The default `[0.05, 0.5, 5, 30]` buckets are too coarse for sub-100ms percentile analysis, so buckets are customised to match observed p50–p99: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: enabled: true # default port; Prometheus scrapes http://:4001/metrics port: 4001 # ALWAYS compact in production — verbose embeds block numbers and IPs in labels, # creating unbounded cardinality that crashes managed Prometheus scrapers errorLabelMode: compact # buckets tuned to observed p50~5ms, p99~3s for an indexing fleet; # adjust for your workload — coarser is fine for purely human dashboards histogramBuckets: "0.010,0.030,0.050,0.100,0.250,0.500,1,3,5,10,30" ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { enabled: true, // default port; Prometheus scrapes http://:4001/metrics port: 4001, // ALWAYS compact in production — verbose embeds block numbers and IPs in labels, // creating unbounded cardinality that crashes managed Prometheus scrapers errorLabelMode: "compact", // buckets tuned to observed p50~5ms, p99~3s for an indexing fleet; // adjust for your workload — coarser is fine for purely human dashboards histogramBuckets: "0.010,0.030,0.050,0.100,0.250,0.500,1,3,5,10,30", } ``` **2. Multi-region aggregator — cardinality reduction with surgical label restore.** Used when many API keys (users) flow through one node and Grafana Cloud caps scrape body size. Drop `user` and `composite` globally; restore `user` only on `network_request_duration_seconds` to keep per-client latency SLOs without multiplying every other histogram's cardinality. Coarser buckets (8 boundaries) halve bucket count vs. the 11-boundary indexer shape above: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: enabled: true port: 4001 errorLabelMode: compact # 8 boundaries tuned for p50~100ms, p99~6s on a multi-region aggregator histogramBuckets: "0.020,0.100,0.300,0.500,1,3,6,10" customizations: # user × composite × other labels can create thousands of series; # dropping these two fleet-wide is the single biggest cardinality win - subject: "*" labels: - subject: user action: drop - subject: composite action: drop # restore user ONLY here so per-client latency SLOs remain queryable - subject: network_request_duration_seconds labels: - subject: user action: keep ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { enabled: true, port: 4001, errorLabelMode: "compact", // 8 boundaries tuned for p50~100ms, p99~6s on a multi-region aggregator histogramBuckets: "0.020,0.100,0.300,0.500,1,3,6,10", customizations: [ { // user × composite × other labels can create thousands of series; // dropping these two fleet-wide is the single biggest cardinality win subject: "*", labels: [ { subject: "user", action: "drop" }, { subject: "composite", action: "drop" }, ], }, { // restore user ONLY here so per-client latency SLOs remain queryable subject: "network_request_duration_seconds", labels: [{ subject: "user", action: "keep" }], }, ], } ``` **3. Edge node with fast p50 — sub-10ms granularity for cache-hit visibility.** When the cache hit rate is high, most responses return in under 5ms. The default 50ms lower bucket obscures all cache-hit latency in a single bucket. Tighter low-end boundaries make p50/p75 meaningful: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: enabled: true port: 4001 errorLabelMode: compact # fine sub-10ms buckets for cache-hit p50 visibility; top end covers heavy getLogs histogramBuckets: "0.005,0.050,0.500,1,3,10,30" ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { enabled: true, port: 4001, errorLabelMode: "compact", // fine sub-10ms buckets for cache-hit p50 visibility; top end covers heavy getLogs histogramBuckets: "0.005,0.050,0.500,1,3,10,30", } ``` **4. Disabling metrics entirely for test or embedded use.** Set `ERPC_NOMETRICS=1` before process start to replace the default Prometheus registry with an empty no-op registry — all `erpc_*` metrics and the stock `go_*`/`process_*` collectors are silenced. Alternatively set `enabled: false` to skip the HTTP server while keeping in-process counters alive (useful for integration tests that read metrics programmatically). **5. Scrape config and alerting.** The bundled files at [`monitoring/prometheus/`](https://github.com/erpc/erpc/tree/main/monitoring/prometheus) set `scrape_interval: 10s` targeting `host.docker.internal:4001`. Bring up the full Grafana + Prometheus stack with `docker compose up grafana prometheus` from the repo root. Six bundled alert rules fire on: high upstream error rate (>5% for 5 min), p95 latency > 1s, high/low request rate, and rate-limit events — but **two rules reference stale metric names** (`erpc_upstream_request_self_rate_limited_total`, `erpc_network_request_self_rate_limited_total`); replace them with `erpc_rate_limits_total`. ### Best practices - Always set `errorLabelMode: compact` in production. `verbose` mode can embed block numbers and IP addresses in label values, creating unbounded cardinality that crashes managed Prometheus scrapers. - Start with a `subject: "*"` customization dropping `user` and `agent_name` if your deployment has many API keys or clients — these two labels multiply every projected family's series count by the number of distinct values. - Managed Prometheus scrapers (Grafana Cloud, hosted Prometheus) typically cap the `/metrics` response body at 10–64 MB, and the cap is usually enforced on the response **whole**: past it the scrape is rejected outright, so every series for that instance goes dark rather than degrading. Counters — not histograms — are normally the bulk of a large payload, because an unbounded label like a client-supplied user-agent is re-emitted on every scrape for the life of the process. Reach for a label `drop` customization (and `counterIdleEvictionAfter`) before raising the scraper's limit; the label set is unbounded and will re-cross any new ceiling. Dropping whole families with `action: drop` is stronger still — a family that is never registered contributes nothing. - Counter labels are more likely to be load-bearing downstream than histogram labels. `agent_name` or `user` on a request counter often feeds billing or per-tenant attribution, so check consumers before dropping, and add an exact-subject `keep` for the specific counters that need it. - Never expect a customization to take effect after startup — the label set of a registered family is frozen for the registry's lifetime. Plan the list before first deploy. - Use an exact subject to surgically restore a dropped label on exactly one family (e.g. keep `user` only on `network_request_duration_seconds` for per-client SLO analysis). Precedence is by specificity, so the carve-out can be appended anywhere in the list. - Tighten `histogramBuckets` to your actual observed p50–p99 range (e.g. `"0.01,0.05,0.1,0.5,1,2,5"`) — the default `[0.05, 0.5, 5, 30]` is intentionally coarse for broad compatibility, not precision. - Do not alert on `erpc_network_hedge_delay_seconds` — it is registered but dormant (no production `Observe` call). Use `erpc_network_hedged_request_total` and `erpc_network_request_duration_seconds` for hedge-related alerting instead. ### Key metrics by scenario **Is eRPC healthy right now?** | Metric | What to check | |---|---| | `erpc_network_failed_request_total{severity="critical"}` | Non-zero critical-severity failures at the network layer | | `erpc_upstream_request_errors_total{severity="critical"}` | Critical upstream errors by upstream | | `erpc_upstream_cordoned` | Any gauge value `1` = upstream manually removed from routing | | `erpc_unexpected_panic_total` | Any non-zero rate = internal panic recovered | **Upstream performance and availability** | Metric | What to check | |---|---| | `erpc_upstream_block_head_lag` | Blocks behind the corroborated network head (second-highest non-benched upstream); alert on persistent lag | | `erpc_upstream_finalization_lag` | Finalized blocks behind the corroborated network finalized head | | `erpc_upstream_request_duration_seconds` | p95 latency per upstream; bundled alert fires when p95 > 1s | | `erpc_upstream_request_errors_total` | Error rate per upstream; bundled alert fires at 5% error rate | | `erpc_selection_position` | `0` = primary, `1+` = runner-up, `-1` = excluded this tick | | `erpc_selection_excluded_seconds` | Seconds continuously excluded; alert on > 600 (stuck 10 min) | **Cache effectiveness** | Metric | What to check | |---|---| | `erpc_cache_get_success_hit_total` | Hit count; ratio against miss = effective hit rate | | `erpc_cache_get_success_miss_total` | Miss count by policy and connector | | `erpc_cache_get_age_guard_reject_total` | Item rejected because block-timestamp TTL exceeded; tuning signal | | `erpc_ristretto_cache_current_cost` | Memory connector fill level (requires `memory.emitMetrics: true`) | **Rate limiting and traffic shaping** | Metric | What to check | |---|---| | `erpc_rate_limits_total{origin="upstream"}` | Remote 429 passthroughs from upstream | | `erpc_rate_limits_total{origin=""}` | Local budget denials | | `erpc_rate_limiter_failopen_total` | Rate limiter failed open due to timeout or full semaphore | | `erpc_rate_limiter_remote_inflight` | In-flight Redis DoLimit calls; rising without drop signals Redis overload | **Consensus and resilience** | Metric | What to check | |---|---| | `erpc_consensus_misbehavior_detected_total` | Non-zero rate = upstream diverging from consensus | | `erpc_consensus_total{outcome="dispute"}` | Rounds with no consensus reached | | `erpc_network_retry_attempt_total` | Retry pressure by reason (retryable_error, block_unavailable, etc.). On **EVM**, catch-up on `finality="finalized"` is wasted work — canonical data has no availability race — so it is worth alerting on. On **SVM** it is expected: consensus finality and RPC indexing are separate steps, so a rooted Solana slot can still be waiting on the provider's indexer and answers `-32004`/`-32014`. Split the query by `network` before alerting. | | `erpc_upstream_breaker_state_change_total{transition="closed_to_open"}` | Circuit-breaker trips; frequent churn = bad upstream | **Block tracking and tip** | Metric | What to check | |---|---| | `erpc_network_dynamic_block_time_milliseconds` | EMA block-time estimate (α=0.1, min 3 samples); 0 = startup or halted chain; sanity-clamped to [10ms, 120s] | | `erpc_upstream_stale_latest_block_total` | Upstream returned a block number behind the network leader | | `erpc_upstream_block_head_large_rollback` | Size of the last rollback > 1024 blocks, per `finality` axis (`latest`/`finalized`). Sticky — alert on `changes()`, not on `> 0` | | `erpc_network_served_tip_advance_age_seconds` | Seconds since the served tip last changed; sustained high on a live chain = stuck tip | | `erpc_network_served_tip_regression_total` | Non-zero = the regression guard held or gave up holding | | `erpc_upstream_head_benched_total` | Upstream head benched: it stayed behind peers that kept advancing | **Solana (SVM) upstreams** SVM upstreams feed the same tracker as EVM, so the gauges below populate — but **the metric names say "block" while the values are slots**. There is no separate `erpc_svm_*` family. | Metric | What to check | |---|---| | `erpc_upstream_latest_block_number` | The upstream's **processed slot** | | `erpc_upstream_finalized_block_number` | The upstream's **finalized (rooted) slot** | | `erpc_upstream_block_head_lag` | Processed **slots** behind the freshest upstream | | `erpc_upstream_finalization_lag` | Finalized **slots** behind the freshest upstream | | `erpc_upstream_cordoned` | An SVM upstream is cordoned by its own state poller after 2 consecutive all-silent state polls **or** when shred-insert lag exceeds 100 slots; the `reason` label distinguishes them | | `erpc_upstream_stale_latest_block_total` | A `getSlot` answer was corrected to the highest known slot for its commitment | Ingestion lag (`maxShredInsertSlot − processedSlot`) has **no gauge** — it is logged and drives cordoning only. See [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt). **Request multiplexing and static responses** | Metric | What to check | |---|---| | `erpc_network_multiplexed_request_total` | Request de-duplicated into an in-flight identical request | | `erpc_network_static_response_served_total` | Response served from a configured static rule (no upstream) | | `erpc_network_timeout_fired_total` | Timeout policy killed a request; `scope` ∈ network/upstream | **Upstream selection and probing** | Metric | What to check | |---|---| | `erpc_upstream_selection_total` | Upstream chosen for attempt; `reason` ∈ primary/retry/hedge/consensus_slot/sweep | | `erpc_upstream_attempt_outcome_total` | Terminal outcome per attempt; `outcome` ∈ success/empty/transport_error/server_error/client_error/rate_limited/missing_data/exec_revert/block_unavailable/breaker_open/cancelled/timeout/skipped; `is_hedge`/`is_retry` ∈ `"true"`/`"false"` | | `erpc_selection_probe_errors_total` | Probe to excluded upstream errored; `reason` ∈ timeout/throttled/auth/skipped/error | | `erpc_selection_probe_skipped_total` | Probe candidate skipped pre-fire; `reason` ∈ write_method/opt_out/sampled_out/max_concurrent/no_method | **gRPC BDS resilience** | Metric | What to check | |---|---| | `erpc_grpc_bds_hard_timeout_total` | BDS gRPC call hit 20s hard timeout — indicates H2 stream wedging | | `erpc_grpc_bds_conn_replacements_total` | BDS connection force-replaced by stuck-call watchdog | **Shadow testing** | Metric | What to check | |---|---| | `erpc_shadow_response_mismatch_total` | Shadow upstream diverged from primary; check `emptyish`/`larger` labels | | `erpc_shadow_response_error_total` | Shadow upstream errored | **CORS** | Metric | What to check | |---|---| | `erpc_cors_requests_total` | CORS-triggered requests; note: `project` label = URL path not project ID | | `erpc_cors_preflight_requests_total` | OPTIONS preflight; same `project` mislabeling | | `erpc_cors_disallowed_origin_total` | Request from an origin not on the allowlist | ### Edge cases & gotchas 1. **`hostV4`/`hostV6` are unused.** The server always binds all interfaces (`":"`). Setting `metrics.hostV4: 127.0.0.1` does NOT restrict scrape access to loopback. Use a firewall or network policy instead. ([`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189)) 2. **`metrics.enabled` defaults to `nil` (disabled) under `go test`.** Integration tests that start a full `erpc.Init` will NOT spin up a metrics server unless they set `Enabled: true` explicitly. ([`common/defaults.go:L909-911`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L909-L911)) 3. **`errorLabelMode` change does not retroactively fix accumulated series.** Any series created before `erpc.Init` sets the mode carry `verbose` labels; subsequent series carry `compact` labels. Both appear as parallel label-value sets until the verbose series expire. 4. **`erpc_rate_limiter_budget_decision_total` is a dead metric.** Registered at startup so it appears in `/metrics` but has zero production call sites and always returns 0. ([`telemetry/metrics.go:L515-519`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L515-L519)) 5. **`erpc_network_hedge_delay_seconds` is dormant.** Registered and appears in `/metrics` but the only `Observe` call is in a test file. Do not alert on it. ([`telemetry/metrics.go:L813`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L813)) 6. **`erpc_cors_requests_total` `project` label receives the URL path, not the project ID.** Values look like `/myproject/evm/1` instead of `myproject`. Dashboard queries on CORS metrics must use path-style values. ([`erpc/http_server.go:L1020`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1020)) 7. **`erpc_ristretto_cache_current_cost` requires `memory.emitMetrics: true`.** Without this flag the gauge is registered but always 0 — the collection goroutine never starts. This is the only metric requiring an explicit config opt-in to be meaningful. ([`data/memory.go:L71`](https://github.com/erpc/erpc/blob/main/data/memory.go#L71)) 8. **`erpc_upstream_cordoned` `category` label is the cordon scope (method string), not a request-category.** `"*"` = wholesale cordon; a specific method string = per-method cordon. Do not join this `category` with `category` on request-accounting metrics. ([`health/tracker.go:L458-465`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L458-L465)) 9. **`erpc_auth_failed_total` covers client-facing auth denials.** Filter by `strategy` and `reason` (e.g. `strategy="jwt",reason="token_expired"`). ([`auth/auth_metrics.go`](https://github.com/erpc/erpc/blob/main/auth/auth_metrics.go)) 10. **`erpc_upstream_attempt_outcome_total` `is_hedge` and `is_retry` are `"true"`/`"false"` strings, not `"1"`/`"0"`.** Use `{is_hedge="true"}` in Prometheus queries. ([`upstream/upstream.go:L80-85`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L80-L85)) 11. **Idle sweep protects only `upstream_request_duration_seconds` and `rate_limits_total` Prometheus series.** All other high-cardinality metrics (e.g. `upstream_request_total`, `network_request_duration_seconds`) are never `DeleteLabelValues`'d — cardinality bounded only by distinct label tuples. 12. **Two bundled alerting rules reference stale metric names.** `erpc_upstream_request_self_rate_limited_total` and `erpc_network_request_self_rate_limited_total` no longer exist. Use `erpc_rate_limits_total` as the replacement. ([`monitoring/prometheus/alert.rules:L1`](https://github.com/erpc/erpc/blob/main/monitoring/prometheus/alert.rules#L1)) 13. **`erpc_upstream_block_head_large_rollback` is silent for rollbacks ≤ 1024 blocks, and sticky above them.** `DefaultToleratedBlockHeadRollback = 1024` is the threshold. The gauge is `Set` to the rollback *size* and is never reset, so it holds that value for the life of the process: `> 0` means "this process saw a rollback at some point", not "a rollback is happening now", and `rate()`/`increase()` are meaningless on it. Alert on `changes(...[window])` instead. Split by the `finality` label — the `finalized` axis is dominated by upstreams whose write granularity exceeds 1024 blocks, which registers as a large rollback by construction. ([`architecture/evm/evm_state_poller.go:L27`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L27)) 14. **`erpc_selection_*` metrics carry a `method` label.** If the ingress exposes many distinct RPC methods to untrusted callers, a flood of unique method names creates unbounded series. Add `method` to a Prometheus relabeling drop rule for untrusted deployments. 15. **A customization that changes a label set is ignored once the family is registered.** `Configure` skips families it already registered, because Prometheus keeps the frozen label-set hash for the registry's lifetime. Plan the list before first deploy. ([`telemetry/manager.go:L243-286`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go#L243-L286)) 16. **`erpc_network_evm_block_range_requested_total` uses a dynamic tip-relative `bucket` label.** When tip is known, `ComputeBlockHeatmapBucket` produces human-readable labels (`"TIP"`, `"L100k"`, `"100k-200k"`, `"119m-120m"`, etc.) — potentially unbounded. When tip is unknown it falls back to static 100k-aligned labels. Plan Prometheus cardinality accordingly. ([`erpc/block_heatmap.go:L87`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L87)) 17. **`ERPC_NOMETRICS=1` drops the default `go_*`/`process_*` collectors too.** It replaces the entire default registry with a fresh empty one before `telemetry.Configure` registers anything. ([`cmd/erpc/initflags.go:L22-28`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go#L22-L28)) 18. **`erpc_upstream_cordoned` `vendor` label is `"n/a"` when vendor is not configured.** Ensure dashboard JOINs between cordoned metrics and upstream request metrics match `"n/a"` for unvendored upstreams. ([`upstream/upstream.go:L275-286`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L275-L286)) 19. **Idle sweep fires at rotation-tick granularity, not in real-time.** With default 5-minute window and 10 rolling buckets, each tick is 30 seconds; sweep fires every 10 ticks ≈ every 5 minutes. An idle series is evicted up to `idleEvictionAfter + 5 min` (≈35 min) after its last observation, not exactly at 30 minutes. ([`health/tracker.go:L557-563`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L557-L563)) 20. **Cordoned upstreams are never swept.** If an upstream is cordoned, its tracker entry is preserved regardless of idle time. The `erpc_upstream_cordoned{...} = 1` gauge remains in `/metrics` until the upstream is uncordoned and subsequently stays idle for `idleEvictionAfter`. ([`health/tracker.go:L603-608`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L603-L608)) 21. **`ParseHistogramBuckets` silently sorts the input.** If buckets are provided out of order they are sorted automatically; no warning is emitted. The result is valid Prometheus buckets, but it may differ from the intended order if you relied on a specific sequence. ([`telemetry/metrics.go:L997-1015`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L997-L1015)) 22. **`erpc_network_dynamic_block_time_milliseconds` is bounded [10ms, 120s] and requires min 3 samples.** The EMA (α=0.1) needs at least 3 block-time samples (4 total block observations) before the gauge emits. Chains faster than 10ms report the 10ms floor; chains with no new blocks for >2 min report the 120s ceiling. Returns 0 during startup before enough samples accumulate. ([`health/tracker.go:L1381-1458`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1381-L1458)) 23. **`erpc_cors_preflight_requests_total` and `erpc_cors_disallowed_origin_total` share the same `project` mislabeling as `erpc_cors_requests_total`.** All three CORS counters set `project` to `r.URL.Path` (e.g. `/myproject/evm/1`), not the project ID. ([`erpc/http_server.go:L1069`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1069)) 24. **`erpc_upstream_request_duration_seconds` full schema includes `user` but `erpc_upstream_response_size_bytes` does not.** The response-size histogram is intentionally tight (`project`, `network`, `category`, `finality` only) — per-user breakdown of response size is not actionable. If per-user latency analysis on `upstream_request_duration_seconds` is required, pair a fleet-wide `user` drop with an exact-subject `keep` for that family rather than skipping the drop entirely. ([`telemetry/metrics.go:L914-920`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L914-L920)) 25. **The bundled Prometheus scrape config contains a Railway placeholder.** `monitoring/prometheus/prometheus.yml` includes a `REPLACE_SERVICE_ENDPOINT_HERE:REPLACE_SERVICE_PORT_HERE` target that causes parse errors in strict Prometheus configs. Remove or replace it before using the bundled config in production. 26. **`erpc_grpc_bds_hard_timeout_total` threshold is hard-coded at 20 seconds.** The `bdsHardCallTimeout` constant at [`clients/grpc_bds_resilience.go:L34`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L34) is not configurable without recompile. A non-zero rate indicates H2 stream wedging; the watchdog then force-replaces the connection (`erpc_grpc_bds_conn_replacements_total`). 27. **On SVM networks, `finality="finalized"` catch-up retries are normal, not waste.** The EVM guidance — that catch-up on canonical data indicates a misconfiguration — does not transfer. Solana consensus finality (a rooted slot) and RPC indexing are independent, so `getBlock` on a just-rooted slot legitimately returns `-32004 BlockNotAvailable` or `-32014 BlockStatusNotAvailableYet` until the provider's indexer catches up. Alert on the trend, not on non-zero. See [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt). 28. **`erpc_upstream_*_block_number` and `*_lag` gauges carry slots on SVM networks.** The names are architecture-neutral and were coined for EVM. A dashboard that labels them "blocks" will mislead on Solana, where a skipped slot advances the slot counter but not the block height. 29. **There is no metric for SVM shred-insert (ingestion) lag.** It gates cordoning and appears in the cordon WARN log (`shredInsertSlotLag`), but no gauge exposes it. Monitor `erpc_upstream_cordoned` and read the `reason` label instead. **Metrics server log lines** (useful when diagnosing startup failures): - `"starting metrics server on port: %d"` — Info, [`erpc/init.go:L184`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L184) - `"error starting metrics server: %s"` — Error, [`erpc/init.go:L200`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L200) - `"shutting down metrics server..."` — Info, [`erpc/init.go:L206`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L206) - `"metrics server forced to shutdown: %s"` — Error, [`erpc/init.go:L210`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L210) - `"metrics server stopped"` — Info, [`erpc/init.go:L212`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L212) - `"failed to apply metrics configuration; no metric families are registered"` — Error, a malformed `metrics.customizations` entry; nothing was registered, [`erpc/init.go:L63-69`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L63-L69) - `"failed to apply metrics configuration; falling back to default histogram buckets"` — Warn, an unparseable `metrics.histogramBuckets`; every family is still registered, [`erpc/init.go:L63-69`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L63-L69) ### Observability **The metrics endpoint:** `http://:/` (any path) — the Prometheus handler is mounted at the root, so every HTTP path on the port returns the full Prometheus text exposition. Canonical Prometheus convention scrapes `/metrics` but any path works. Plain HTTP only, no auth. **Stock collectors** (from prometheus/client_golang default registry, present unless `ERPC_NOMETRICS=1`): - `go_*` — Go runtime memory/GC/goroutine stats - `process_*` — OS process CPU/memory/fd stats - `promhttp_metric_handler_*` — metrics handler self-scrape stats **Bundled alerting rules** (`monitoring/prometheus/alert.rules`): | Alert | Expression | Threshold | |---|---|---| | HighErrorRate | `rate(erpc_upstream_request_errors_total[5m]) / rate(erpc_upstream_request_total[5m]) > 0.05` | 5% error rate for 5 min | | SlowRequests | `histogram_quantile(0.95, rate(erpc_upstream_request_duration_seconds_bucket[5m])) > 1` | p95 > 1s for 5 min | | HighRequestRate | `rate(erpc_upstream_request_total[5m]) by (upstream) > 1000` | >1000 rps per upstream for 5 min | | LowRequestRate | `rate(erpc_upstream_request_total[5m]) by (upstream) < 1` | <1 rps per upstream for 15 min | | HighRateLimiting | stale metric name — replace with `erpc_rate_limits_total` | — | | NetworkRateLimiting | stale metric name — replace with `erpc_rate_limits_total` | — | **Full 122-metric catalog at [/reference/metrics](/reference/metrics.llms.txt).** Top-20 operational metrics: | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_request_received_total` | counter | project, network, category, finality, user, agent_name | Request received for a network | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, error, severity, finality, user, agent_name | Request failed at network level; `severity` ∈ critical/warning/info | | `erpc_network_successful_request_total` | counter | project, network, vendor, upstream, category, attempt, finality, emptyish, user, agent_name | Request succeeded at network level | | `erpc_network_request_duration_seconds` | LabeledHistogram | project, network, vendor, upstream, category, finality, user | End-to-end request duration | | `erpc_upstream_request_total` | counter | project, vendor, network, upstream, category, attempt, composite, finality, user, agent_name | Each attempt sent to an upstream | | `erpc_upstream_request_errors_total` | counter | project, vendor, network, upstream, category, error, severity, composite, finality, user, agent_name | Upstream attempt returned an error | | `erpc_upstream_request_duration_seconds` | LabeledHistogram | project, vendor, network, upstream, category, composite, finality, user | Duration of each upstream attempt; idle series swept every 30 min | | `erpc_upstream_block_head_lag` | gauge | project, vendor, network, upstream | Blocks behind the corroborated network head (second-highest non-benched upstream) | | `erpc_upstream_finalization_lag` | gauge | project, vendor, network, upstream | Finalized blocks behind the corroborated network finalized head | | `erpc_upstream_cordoned` | gauge | project, vendor, network, upstream, category, reason | `1` while cordoned; `0` when active | | `erpc_upstream_breaker_state_change_total` | counter | project, upstream, transition | Circuit-breaker state transition | | `erpc_selection_position` | gauge | project, network, method, upstream | `0`=primary, `1+`=runner-up, `-1`=excluded | | `erpc_selection_excluded_seconds` | gauge | project, network, method, upstream | Seconds continuously excluded; 0 when in rotation | | `erpc_cache_get_success_hit_total` | counter | project, network, category, connector, policy, ttl | Cache get hit | | `erpc_cache_get_success_miss_total` | counter | project, network, category, connector, policy, ttl | Cache get miss | | `erpc_rate_limits_total` | counter | project, network, vendor, upstream, category, finality, user, agent_name, budget, scope, auth, origin | All rate-limit events; idle series swept by health tracker | | `erpc_consensus_misbehavior_detected_total` | counter | project, network, upstream, category, finality, response_type, larger_than_consensus | Upstream returned data diverging from consensus; `response_type` ∈ NonEmpty/Empty/ConsensusError/InfrastructureError | | `erpc_consensus_total` | counter | project, network, category, outcome, finality | Consensus round completed; `outcome` ∈ success/consensus_on_error/dispute/low_participants/generic_error/caller_abandoned | | `erpc_consensus_short_circuit_total` | counter | project, network, category, reason, finality | Round short-circuited; `reason` ∈ sendrawtx_first_success/consensus_error_threshold/unassailable_lead | | `erpc_consensus_wait_capped_total` | counter | project, network, category, trigger, finality | Round resolved early by timer; `trigger` ∈ result/empty | | `erpc_network_retry_attempt_total` | counter | project, network, category, reason, finality | Network-scope retry; `reason` ∈ empty_result/pending_tx/retryable_error/block_unavailable/missing_data | | `erpc_network_data_unavailable_wait_seconds` | LabeledHistogram | project, network, category, reason, finality | Catch-up delay before data-not-yet-available retry | | `erpc_upstream_request_skipped_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream pre-forward checks decided to skip this attempt | | `erpc_upstream_request_missing_data_error_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned missing-data/not-synced error | | `erpc_upstream_request_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned an empty/null result | | `erpc_upstream_response_size_bytes` | LabeledHistogram | project, network, category, finality | Decoded post-gzip result-body byte count; buckets: 4k, 64k, 1M, 16M, 100M | | `erpc_upstream_selection_total` | counter | project, network, upstream, category, reason, finality | Upstream picked for an attempt; `reason` ∈ primary/retry/hedge/consensus_slot/sweep | | `erpc_upstream_attempt_outcome_total` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | Terminal outcome; `outcome` ∈ success/empty/transport_error/server_error/client_error/rate_limited/missing_data/exec_revert/block_unavailable/breaker_open/cancelled/timeout/skipped; `is_hedge`/`is_retry` ∈ `"true"`/`"false"` | | `erpc_rate_limiter_failopen_total` | counter | project, network, user, agent_name, budget, category, reason | Rate limiter failed open; `reason` ∈ admission_full/limit_timeout | | `erpc_rate_limiter_budget_max_count` | gauge | budget, method, scope | Budget's configured req/s; `scope` = ScopeString() (comma-joined flags: user/network/ip) | | `erpc_rate_limiter_remote_duration_seconds` | LabeledHistogram | budget, result | Remote rate-limit check (e.g. Redis DoLimit) duration; `result` ∈ ok/over_limit/fail_open | | `erpc_network_dynamic_block_time_milliseconds` | gauge | project, network | EMA block-time (α=0.1, min 3 samples); 0 = startup/halted; clamped [10ms, 120s] | | `erpc_network_evm_block_range_requested_total` | counter | project, network, vendor, upstream, category, user, finality, bucket, size | Block-range heatmap; `bucket` = tip-relative label when tip known (`"TIP"`, `"L100k"`, `"100k-200k"`, …) or static 100k-aligned label | | `erpc_network_evm_get_logs_forced_splits_total` | counter | project, network, dimension, user, agent_name | eth_getLogs forcibly split; `dimension` ∈ block_range/addresses/topics0 | | `erpc_upstream_stale_upper_bound_total` | counter | project, vendor, network, upstream, category, confidence | Request skipped: upstream latest < requested upper bound; `confidence` ∈ blockHead/finalizedBlock | | `erpc_upstream_stale_lower_bound_total` | counter | project, vendor, network, upstream, category, confidence | Request skipped: lower bound below upstream's available range | | `erpc_grpc_bds_hard_timeout_total` | counter | project, upstream, method | BDS gRPC call hit 20s hard timeout — H2 stream wedging indicator | | `erpc_grpc_bds_conn_replacements_total` | counter | project, upstream | BDS connection force-replaced by stuck-call watchdog | | `erpc_shadow_response_mismatch_total` | counter | project, vendor, network, upstream, category, finality, emptyish, larger | Shadow upstream diverged from primary; `emptyish`/`larger` ∈ `"true"`/`"false"` | | `erpc_selection_probe_errors_total` | counter | network, upstream, method, reason | Probe to excluded upstream errored; `reason` ∈ timeout/throttled/auth/skipped/error | | `erpc_upstream_wrong_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned empty while consensus showed others had data | | `erpc_auth_failed_total` | counter | project, network, strategy, reason, agent_name | Client-facing auth denial; `agent_name` always `unknown`; closed `reason` sets | | `erpc_unexpected_panic_total` | counter | scope, extra, error | Recovered panic; `scope` ∈ request-handler/final-error-writer/top-level-handler/timeout-handler/validate-pattern/redis-pubsub/shared-state-registry/matcher | | `erpc_network_served_tip_block_number` | gauge | project, network, lane, axis | Served tip as served; `lane="all"` = network-wide; `axis` ∈ latest/finalized | | `erpc_network_served_tip_lag_blocks` | gauge | project, network, lane, axis | Blocks the served tip sits below the second-highest voter, clamped at 0; `latest` reads 0 while the lane has no read demand | | `erpc_network_served_tip_advance_age_seconds` | gauge | project, network, lane, axis | Seconds since the served tip last changed; absent until the first change | | `erpc_network_served_tip_regression_total` | counter | project, network, lane, axis, outcome | Regression-guard transitions; `outcome` ∈ held/failed_open | | `erpc_upstream_head_benched_total` | counter | project, vendor, network, upstream | Upstream head benched: it stayed behind peers that kept advancing | ### Source code entry points - [`telemetry/metrics.go`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go) — all 141 metric definitions, bucket constants, `DefaultHistogramBuckets`, `ParseHistogramBuckets` - [`telemetry/manager.go`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go) — the definition index, the `Define*` factories, `Configure`, `SetHistogramBuckets`, `Gatherer` - [`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go) — `metrics.customizations` parsing, validation and precedence; `MetricPolicy` - [`telemetry/gather_filter.go`](https://github.com/erpc/erpc/blob/main/telemetry/gather_filter.go) — `FilteredGatherer`, applying drop rules to collectors the manager does not own - [`erpc/init.go`](https://github.com/erpc/erpc/blob/main/erpc/init.go) — metric initialization sequence: `metricsOptions` → `telemetry.Configure` → exposure logging → network alias resolver install - [`erpc/init.go`](https://github.com/erpc/erpc/blob/main/erpc/init.go) — metrics HTTP server construction: the Prometheus handler over `telemetry.Gatherer` on `:`, `ReadHeaderTimeout` 10s, graceful shutdown 5s - [`telemetry/labeled_histogram.go:L58-L190`](https://github.com/erpc/erpc/blob/main/telemetry/labeled_histogram.go#L58-L190) — `LabeledHistogram` struct, `WithLabelValues`/`DeleteLabelValues`/`ActiveLabelValues`, label filter projection - [`telemetry/handles.go:L86-L105`](https://github.com/erpc/erpc/blob/main/telemetry/handles.go#L86-L105) — `CounterHandle`/`GaugeHandle`/`ObserverHandle` label-bound child caches; `ResetHandleCache` - [`health/tracker.go:L481-L667`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L481-L667) — `DefaultIdleEvictionAfter`; `rotateMetricsLoop`, `sweepIdle`, `sweepIdleObservers` — idle-series eviction for `upstream_request_duration_seconds` and `rate_limits_total` - [`health/tracker.go:L1381-L1458`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1381-L1458) — `erpc_network_dynamic_block_time_milliseconds` EMA algorithm (α=0.1, min 3 samples, bounds 10ms–120s) - [`common/config.go:L2543-L2564`](https://github.com/erpc/erpc/blob/main/common/config.go#L2543-L2564) — `MetricsConfig` struct definition - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) — `MetricsConfig.SetDefaults` - [`common/errors.go:L17-L114`](https://github.com/erpc/erpc/blob/main/common/errors.go#L17-L114) — `errorLabelMode` global; `SetErrorLabelMode`; `ErrorSummary` (produces `error` label values for all error-labeled metrics) - [`cmd/erpc/initflags.go:L22-L28`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go#L22-L28) — `ERPC_NOMETRICS=1` env var handling - [`erpc/block_heatmap.go:L14-L175`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L14-L175) — `ComputeBlockHeatmapBucket` tip-relative bucket label algorithm for `erpc_network_evm_block_range_requested_total` - [`clients/grpc_bds_resilience.go:L30-L34`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L30-L34) — `bdsHardCallTimeout` = 20s hard-coded constant for `erpc_grpc_bds_hard_timeout_total` ### Related pages - [Metrics reference](/reference/metrics.llms.txt) — full 122-metric catalog with all labels and fire conditions. - [Rate limiters](/config/rate-limiters.llms.txt) — `erpc_rate_limits_total` and `erpc_rate_limiter_*` metrics originate here. - [Selection policies](/config/projects/selection-policies.llms.txt) — `erpc_selection_*` metrics live here. - [Hedge](/config/failsafe/hedge.llms.txt) — `erpc_network_hedged_request_total` and `erpc_network_hedge_winner_total`. - [Consensus](/config/projects/consensus.llms.txt) — `erpc_consensus_*` metric family. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — operational scenario where these metrics matter most. --- --- # Production checklist > Source: https://docs.erpc.cloud/operation/production > Go live confidently — a short list of settings that separate a hardened eRPC deployment from a dev-mode one. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Production checklist eRPC ships sane defaults, but a handful of settings must be deliberately set before serving real traffic. Miss them and you risk OOM kills on memory-limited pods, dropped connections during rolling restarts, or upstream API keys leaking to callers. Every item below is a one-line change with a disproportionate operational payoff. **What you get:** - Zero-dropped-connection rolling restarts - GC-safe memory headroom instead of container OOM kills - Bounded Prometheus cardinality that won't blow up your TSDB - Real client IPs for per-IP rate limits behind load balancers - Error responses that don't leak upstream credentials **Pre-launch checklist:** 1. Set `GOMEMLIMIT` to ~90 % of container memory limit 2. Set `server.waitBeforeShutdown` and `server.waitAfterShutdown` to `30s` 3. Set `server.includeErrorDetails: false` for external-facing deployments 4. Configure `server.trustedIPForwarders` + `server.trustedIPHeaders` behind any proxy 5. Set `metrics.errorLabelMode: compact` (already the default — verify it stays) 6. Set explicit `evm.chainId` on every network and upstream to avoid startup burst 7. Ensure `terminationGracePeriodSeconds` ≥ `waitBeforeShutdown` + `waitAfterShutdown` + drain time ## Quick taste Illustrative, not a tuned production config — a typical hardened server block: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: maxTimeout: 150s # LB drain window — sleep this long on SIGTERM before stopping the HTTP server waitBeforeShutdown: 30s # keep process alive after shutdown so proxies can close open connections waitAfterShutdown: 30s # never expose upstream error details (may contain embedded API credentials) includeErrorDetails: false trustedIPForwarders: - "10.0.0.0/8" # real client IP header from your load balancer, used by IP-based rate limits trustedIPHeaders: - "X-Forwarded-For" metrics: enabled: true port: 4001 # compact keeps error labels bounded — verbose embeds block numbers / IPs errorLabelMode: compact ``` **TypeScript — `erpc.ts`:** ```typescript server: { maxTimeout: "150s", // LB drain window — sleep this long on SIGTERM before stopping the HTTP server waitBeforeShutdown: "30s", // keep process alive after shutdown so proxies can close open connections waitAfterShutdown: "30s", // never expose upstream error details (may contain embedded API credentials) includeErrorDetails: false, trustedIPForwarders: ["10.0.0.0/8"], // real client IP header from your load balancer, used by IP-based rate limits trustedIPHeaders: ["X-Forwarded-For"], }, metrics: { enabled: true, port: 4001, // compact keeps error labels bounded — verbose embeds block numbers / IPs errorLabelMode: "compact", } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: harden a fresh deployment before go-live** ```text I'm about to put eRPC in front of real traffic on Kubernetes. Walk through every item on the production checklist and apply it to my config at my eRPC config: set GOMEMLIMIT to 90% of my container memory limit, set waitBeforeShutdown and waitAfterShutdown to 30s, set includeErrorDetails to false, configure trustedIPForwarders and trustedIPHeaders for my load balancer, set errorLabelMode to compact, and add explicit evm.chainId on every network. Read the full reference first: https://docs.erpc.cloud/operation/production.llms.txt ``` **Prompt Example #2: audit an existing config for production gaps** ```text Audit my eRPC config at my eRPC config against the production hardening checklist. For each item — GOMEMLIMIT, shutdown drain waits, error detail leakage, trusted-IP forwarding, Prometheus cardinality, explicit chainId — tell me whether it's correctly set, what the current value is, and what to change if anything is wrong. Reference: https://docs.erpc.cloud/operation/production.llms.txt ``` **Prompt Example #3: fix dropped connections during rolling restarts** ```text My eRPC pods drop in-flight requests during Kubernetes rolling restarts. Walk me through configuring the graceful drain correctly: waitBeforeShutdown, waitAfterShutdown, and terminationGracePeriodSeconds so no requests are cut mid-flight. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/production.llms.txt ``` **Prompt Example #4: reduce Prometheus cardinality explosion** ```text My eRPC metrics are generating too many Prometheus series and threatening our TSDB. Configure metrics.customizations to drop user and agent_name fleet-wide, keep per-user latency on the network histogram only, and drop any metric families no dashboard reads. Also confirm errorLabelMode is compact. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/production.llms.txt ``` **Prompt Example #5: add dynamic response headers for multi-region routing** ```text I run eRPC in multiple regions and want each response to carry X-ERPC-Region and X-ERPC-Machine headers so callers can see which region served them. Add server.responseHeaders using the REGION and MACHINE_ID env vars, and configure trustedIPHeaders for my platform.s client-IP header. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/operation/production.llms.txt ``` --- ### Production checklist — full agent reference ### How it works **GOMEMLIMIT and GC tuning.** eRPC's Kubernetes and Docker manifests ship without `GOMEMLIMIT`. With Go's default GC (`GOGC=100`) and a 3 Gi container limit, the heap can approach the hard limit before a GC cycle fires — the OS OOM killer then terminates the container before Go can reclaim memory. Set `GOMEMLIMIT` to 90 % of the container memory limit (e.g. `2700MiB` for a `3Gi` pod) so Go triggers a soft GC pass instead. Pair it with `GOGC=30` to reduce heap swing below the ceiling; values below 10 cause GC thrash. Source: [`kube/erpc.yml:L33-36`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L33-L36) **Server timeouts.** Three fields govern the full request lifecycle: `server.maxTimeout` (default `150s`) is a custom `TimeoutHandler` wrapping the entire HTTP handler chain — it is mandatory and validation rejects `0`. `server.readTimeout` (default `30s`) covers header and body read; `server.writeTimeout` (default `120s`) covers response write. These are Go `http.Server` fields. A `maxTimeout` hit returns JSON-RPC `-32603` with HTTP 200 for POST requests. Integer YAML values are interpreted as **milliseconds** — `maxTimeout: 150` means 150 ms, not 150 s; always use the string form. **Graceful drain (healthcheck probes).** On SIGTERM the shutdown sequence is: (1) `draining` flag flips immediately — healthcheck returns HTTP 503 and client WebSocket connections are closed with `1001` once their in-flight requests answer; (2) process sleeps `server.waitBeforeShutdown` (default `10s`) to let load-balancer drain the endpoint; (3) `http.Server.Shutdown` starts with a hardcoded 30 s budget; (4) after `appCtx` is done, `Init` sleeps `server.waitAfterShutdown` (default `10s`) before process exit. For Kubernetes with Cilium/Envoy, set both waits to `30s`. `terminationGracePeriodSeconds` must exceed `waitBeforeShutdown + waitAfterShutdown + expected drain time` or the process receives SIGKILL mid-drain. Sources: [`erpc/http_server.go:L78-83`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L78-L83), [`erpc/http_server.go:L209-221`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L209-L221), [`erpc/init.go:L223-225`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L223-L225) **Trusted-IP forwarding.** When eRPC runs behind a load-balancer, `server.trustedIPForwarders` defaults to loopback only (`["127.0.0.1/8", "::1/128"]`). IP-based rate limits and `network` auth strategies apply to the proxy IP unless you add the LB CIDR to the forwarders list and name the forwarding header in `server.trustedIPHeaders`. The resolver walks headers in preference order, strips trailing trusted proxies from the XFF list right-to-left, and picks the nearest untrusted hop. **Error details in responses.** `server.includeErrorDetails` defaults to `true`. Upstream error messages frequently contain endpoint URLs with embedded API keys. Set to `false` before exposing eRPC to external callers. Errors are still logged internally at full verbosity regardless of this setting. **Prometheus metrics and alerting.** The metrics server starts on port `4001` (all interfaces). `metrics.errorLabelMode: compact` (the default) produces short stable error codes — `verbose` mode embeds full messages including block numbers or IP addresses, creating unbounded Prometheus cardinality. Six alert rules ship in `monitoring/prometheus/alert.rules`; two reference stale metric names (`erpc_upstream_request_self_rate_limited_total`, `erpc_network_request_self_rate_limited_total`) — use `erpc_rate_limits_total` instead. The monitoring container (Prometheus + Grafana combined) runs both processes under `tail -f /dev/null`; not suitable for production — run them as separate services. **Chain ID explicit configuration.** Without explicit `evm.chainId` in network and upstream config, eRPC calls `eth_chainId` on every upstream at startup. With many replicas and upstreams this produces a startup request burst. Set `evm.chainId` explicitly to eliminate it. **Config file discovery.** At startup eRPC searches for a config file in this order: `--config ` CLI flag → first positional argument → first match among `./erpc.yaml`, `./erpc.yml`, `./erpc.ts`, `./erpc.js`, `/erpc.yaml`, `/erpc.yml`, `/erpc.ts`, `/erpc.js`, `/root/erpc.yaml`, `/root/erpc.yml`, `/root/erpc.ts`, `/root/erpc.js`. If `--require-config` is set (or an explicit path was given) and no file is found, startup fails. Source: [`cmd/erpc/main.go:L279-L294`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L294) **CLI subcommands.** Three subcommands are available: `erpc [config]` / `erpc start` starts the server; `erpc validate [--format json|md]` parses config, runs `erpc.GenerateValidationReport`, and exits non-zero on errors — useful for CI gates before a production deploy; `erpc dump [--format yaml|json]` parses config, resolves effective selection policies, and writes the merged config to stdout. Source: [`cmd/erpc/main.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go) **Runtime log environment variables.** Two env vars control logging at runtime without touching the config file: `LOG_LEVEL` overrides `cfg.LogLevel` and is parsed as a zerolog level (`trace`, `debug`, `info`, `warn`, `error`); `LOG_WRITER=console` switches to a human-readable zerolog console writer with `04:05.000ms` time format (useful in local dev or when piping to a log aggregator that cannot parse JSON). Source: [`cmd/erpc/main.go:L354-L363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) ### Config schema Fields relevant to production hardening. All under `server.` or `metrics.` unless noted. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `server.maxTimeout` | `*Duration` | `150s` — [`common/defaults.go:L694-697`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L694-L697) | Global per-request deadline. **Required non-zero** — validation rejects `0` with `"server.maxTimeout is required"`. On timeout returns JSON-RPC `-32603` with HTTP 200 (POST) or 504 (non-POST). Integer YAML values are milliseconds. | | `server.readTimeout` | `*Duration` | `30s` — [`common/defaults.go:L698-701`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L698-L701) | `http.Server.ReadTimeout`. Covers reading headers + body. | | `server.writeTimeout` | `*Duration` | `120s` — [`common/defaults.go:L702-705`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L702-L705) | `http.Server.WriteTimeout`. Covers writing the response. | | `server.waitBeforeShutdown` | `*Duration` | `10s` — [`common/defaults.go:L709-712`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L709-L712) | Sleep between SIGTERM and starting `http.Server.Shutdown`. Healthcheck returns 503 immediately on SIGTERM; this window lets the LB drain the endpoint. | | `server.waitAfterShutdown` | `*Duration` | `10s` — [`common/defaults.go:L713-716`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L713-L716) | Sleep in `Init` after shutdown, before `os.Exit`. Keeps the process alive for proxy to close open connections. | | `server.includeErrorDetails` | `*bool` | `true` — [`common/defaults.go:L717-719`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L717-L719) | When `true`, error responses include `error.data` with the full upstream error. **Footgun:** upstream errors often embed API key fragments. Set `false` for external-facing deployments. | | `server.trustedIPForwarders` | `[]string` | `["127.0.0.1/8", "::1/128"]` — [`common/defaults.go:L725-729`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L725-L729) | CIDR ranges of trusted proxies. Only headers from these peers are parsed for the real client IP. | | `server.trustedIPHeaders` | `[]string` | `[]` — [`common/defaults.go:L730-733`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L730-L733) | Ordered header names (e.g. `X-Forwarded-For`, `CF-Connecting-IP`) read XFF-style for real client IP. | | `server.responseHeaders` | `map[string]string` | `nil` | Static headers on every response. Values are `os.ExpandEnv`-expanded once at startup. Headers with empty-after-expansion values are **silently dropped** — no warning. | | `server.executionHeaders` | `*ExecutionHeadersMode` | `"all"` — [`common/defaults.go:L720-723`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L720-L723) | `"all"` = full `X-ERPC-*` diagnostic headers; `"summary"` = counters + metadata only; `"off"` = no diagnostic headers. | | `metrics.enabled` | `*bool` | `true` (production); `nil` under `go test` — [`common/defaults.go:L909-911`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L909-L911) | Whether the `/metrics` HTTP server starts. | | `metrics.port` | `*int` | `4001` — [`common/defaults.go:L918-920`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L918-L920) | Metrics server port. Always binds `0.0.0.0:` regardless of `metrics.hostV4`. | | `metrics.errorLabelMode` | `string` | `"compact"` — [`common/defaults.go:L921-923`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L921-L923) | `"compact"` = short stable error codes (bounded cardinality). `"verbose"` = full messages including block numbers / IPs (unbounded cardinality risk). | | `metrics.customizations` | `[]object` | `nil` | Shapes `/metrics`: `{subject, action?, labels?, buckets?}` entries dropping whole families, projecting label sets, or overriding histogram buckets. Resolved before the first registration — startup-only. Supersedes `histogramDropLabels`/`histogramLabelOverrides`/`counterDropLabels`/`counterLabelOverrides`, which are deprecated but still honored. | | `GOMEMLIMIT` (env) | string | not set in any manifest — [`kube/erpc.yml:L33-36`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L33-L36) | Set to ~90% of container memory limit. Without it, Go GC may allow heap to approach the hard limit before triggering, causing OOM kill. | | `LOG_LEVEL` (env) | string | value of `cfg.LogLevel` | Overrides the config file's `logLevel`. Parsed as a zerolog level: `trace`, `debug`, `info`, `warn`, `error`. Useful for elevating verbosity on a running pod without a config change. Source: [`cmd/erpc/main.go:L354-L363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) | | `LOG_WRITER` (env) | string | `""` (JSON lines) | Set to `"console"` for human-readable output with `04:05.000ms` time format. Default is structured JSON. Source: [`cmd/erpc/main.go:L53-L57`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L53-L57) | **Hardcoded constants (not configurable):** - `http.Server.IdleTimeout` = 300 s — [`erpc/http_server.go:L185`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L185) - `MaxHeaderBytes` = 1 MiB — [`erpc/http_server.go:L186`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L186) - Graceful shutdown budget = 30 s — [`erpc/http_server.go:L1642`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1642) - Metrics shutdown budget = 5 s — [`erpc/init.go:L207`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L207) - Metrics server binds `0.0.0.0:` — `hostV4`/`hostV6` config fields are defined but unused — [`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189) ### Worked examples All patterns below are distilled from real production fleets; comments explain the non-obvious choices. **1. Kubernetes deployment — full hardened server block.** A customer-facing multi-region edge deployment behind a load balancer. Both drain waits at 30s match a typical LB drain window; `terminationGracePeriodSeconds: 90` in the pod spec leaves buffer. The `responseHeaders` block injects per-machine routing metadata without any per-request overhead: ```yaml # Pod environment — set alongside your eRPC container spec. # GOMEMLIMIT omitted from all bundled kube manifests; add it yourself. env: - name: GOMEMLIMIT # 90% of the container memory limit (3Gi pod → 2700MiB). # Without this Go GC allows the heap to reach the hard limit before # triggering a collection, causing OOM kills instead of soft GC passes. value: "2700MiB" - name: GOGC # Reduce heap swing below GOMEMLIMIT ceiling; values < 10 cause GC thrash. value: "30" resources: limits: memory: "3Gi" requests: memory: "1Gi" ``` **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: maxTimeout: 150s # LB drain window — most load balancers and k8s ingresses need 20-30s to drain an endpoint. waitBeforeShutdown: 30s # Keep the process alive after shutdown so proxies can close open connections. waitAfterShutdown: 30s # CRITICAL for external-facing deployments — upstream errors routinely embed API keys. includeErrorDetails: false # RFC-1918 covers most private meshes and cloud VPCs; tighten if your LB # uses a narrower range. trustedIPForwarders: - "10.0.0.0/8" - "172.16.0.0/12" - "192.168.0.0/16" # some platforms inject the real client IP in their own header (e.g. Fly-Client-IP, CF-Connecting-IP); prefer it over X-Forwarded-For # which can be spoofed by the caller. trustedIPHeaders: - "CF-Connecting-IP" # Env vars are expanded once at startup; if REGION is unset the header is silently # dropped — no warning. Confirm both vars are present in your machine environment. responseHeaders: X-ERPC-Region: \${REGION} X-ERPC-Machine: \${MACHINE_ID} metrics: enabled: true port: 4001 # compact is the default; confirm it explicitly so a future config merge can't flip it. errorLabelMode: compact customizations: # Drop user + composite fleet-wide to keep Prometheus series bounded. # erpc_upstream_request_duration_seconds × user × composite = O(users × upstreams) # which blows up TSDB at multi-tenant scale. Re-add selectively below. - subject: "*" labels: - subject: user action: drop - subject: composite action: drop # Re-add user only on the network histogram where per-user latency analysis matters. - subject: network_request_duration_seconds labels: - subject: user action: keep ``` **TypeScript — `erpc.ts`:** ```typescript server: { maxTimeout: "150s", // LB drain window — most load balancers and k8s ingresses need 20-30s to drain an endpoint. waitBeforeShutdown: "30s", // Keep the process alive after shutdown so proxies can close open connections. waitAfterShutdown: "30s", // CRITICAL for external-facing deployments — upstream errors routinely embed API keys. includeErrorDetails: false, // RFC-1918 covers most private meshes and cloud VPCs; tighten if your LB // uses a narrower range. trustedIPForwarders: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], // some platforms inject the real client IP in their own header (e.g. Fly-Client-IP, CF-Connecting-IP); prefer it over X-Forwarded-For // which can be spoofed by the caller. trustedIPHeaders: ["CF-Connecting-IP"], // Env vars are expanded once at startup; if REGION is unset the header is silently // dropped — no warning. Confirm both vars are present in your machine environment. responseHeaders: { "X-ERPC-Region": "\${REGION}", "X-ERPC-Machine": "\${MACHINE_ID}", }, }, metrics: { enabled: true, port: 4001, // compact is the default; confirm it explicitly so a future config merge can't flip it. errorLabelMode: "compact", customizations: [ { // Drop user + composite fleet-wide to keep Prometheus series bounded. subject: "*", labels: [ { subject: "user", action: "drop" }, { subject: "composite", action: "drop" }, ], }, { // Re-add user only on the network histogram where per-user latency analysis matters. subject: "network_request_duration_seconds", labels: [{ subject: "user", action: "keep" }], }, ], } ``` **2. Internal indexing deployment (no public exposure).** An internal indexing fleet on Kubernetes with gRPC enabled for cache connectors. `includeErrorDetails` is omitted (left at default `true`) because callers are internal services that need the full upstream error for debugging. `logLevel: error` cuts log volume drastically for high-QPS indexers where `warn` produces too much noise: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml logLevel: error server: # Same 30s drain waits as edge — service-mesh networking also needs the full window. waitBeforeShutdown: 30s waitAfterShutdown: 30s # gRPC enabled for cache connectors; shares port 4000 with HTTP by default. # If you separate the ports add an explicit Docker -p flag — only 4000/4001/6060 are EXPOSED. grpcEnabled: true metrics: enabled: true port: 4001 errorLabelMode: compact # Fine-grained histogram buckets tuned for fast internal RPC (10ms–30s range). # Default buckets miss the 10–100ms region where most indexer calls land. histogramBuckets: "0.010,0.030,0.050,0.100,0.250,0.500,1,3,5,10,30" ``` **TypeScript — `erpc.ts`:** ```typescript logLevel: "error", server: { // Same 30s drain waits as edge — service-mesh networking also needs the full window. waitBeforeShutdown: "30s", waitAfterShutdown: "30s", // gRPC enabled for cache connectors; shares port 4000 with HTTP by default. // If you separate the ports add an explicit Docker -p flag — only 4000/4001/6060 are EXPOSED. grpcEnabled: true, }, metrics: { enabled: true, port: 4001, errorLabelMode: "compact", // Fine-grained histogram buckets tuned for fast internal RPC (10ms–30s range). histogramBuckets: "0.010,0.030,0.050,0.100,0.250,0.500,1,3,5,10,30", } ``` **3. Docker Compose / local staging — minimal hardening.** Smaller memory budget; drain waits shortened to 5s because no Kubernetes LB lifecycle is involved. `includeErrorDetails: false` should still be set even in staging so configs don't accidentally mirror prod with it enabled: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: maxTimeout: 60s waitBeforeShutdown: 5s waitAfterShutdown: 5s includeErrorDetails: false metrics: enabled: true port: 4001 errorLabelMode: compact ``` **TypeScript — `erpc.ts`:** ```typescript server: { maxTimeout: "60s", waitBeforeShutdown: "5s", waitAfterShutdown: "5s", includeErrorDetails: false, }, metrics: { enabled: true, port: 4001, errorLabelMode: "compact", } ``` **4. Multi-tenant high-cardinality deployment with selective label carve-outs.** When serving many users across many upstreams, `erpc_upstream_request_duration_seconds` with `user` and `agent_name` labels creates O(users × upstreams) Prometheus series. The production pattern drops both fleet-wide and re-adds `user` only on the network-level histogram where per-user latency SLO reporting is needed: **Config path:** `metrics` **YAML — `erpc.yaml`:** ```yaml metrics: errorLabelMode: compact customizations: # Drop high-cardinality labels fleet-wide first. # erpc_upstream_request_duration_seconds × 50 users × 20 upstreams = 1000 series minimum. - subject: "*" labels: - subject: user action: drop - subject: agent_name action: drop # Then selectively restore user on the one histogram that feeds per-user latency dashboards. # Precedence is by specificity, so this carve-out wins over the "*" entry above. - subject: network_request_duration_seconds labels: - subject: user action: keep ``` **TypeScript — `erpc.ts`:** ```typescript metrics: { errorLabelMode: "compact", customizations: [ { // Drop high-cardinality labels fleet-wide first. subject: "*", labels: [ { subject: "user", action: "drop" }, { subject: "agent_name", action: "drop" }, ], }, { // Then selectively restore user on the one histogram that feeds per-user latency dashboards. subject: "network_request_duration_seconds", labels: [{ subject: "user", action: "keep" }], }, ], } ``` ### Request/response behavior - On `SIGTERM`, healthcheck returns HTTP 503 plain-text `"shutting down"` immediately, before any drain wait. [[`erpc/http_server.go:L78-83`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L78-L83)] - `waitBeforeShutdown` elapses before `http.Server.Shutdown` starts; `waitAfterShutdown` elapses after `appCtx` is done, before `os.Exit`. [[`erpc/http_server.go:L209-221`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L209-L221), [`erpc/init.go:L223-225`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L223-L225)] - A `maxTimeout` hit returns JSON-RPC `-32603` `"http request handling timeout"` with HTTP 200 for POST, 504 for non-POST — not a Go deadline cancellation. [[`erpc/http_timeout.go:L107-122`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L107-L122)] - `server.responseHeaders` env expansion runs once at `NewHttpServer` construction time, not per-request. Empty-after-expansion values are silently dropped. [[`erpc/http_server.go:L135-148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148)] - The metrics server binds `0.0.0.0:` — `metrics.hostV4` / `hostV6` are defined but unused. Restrict scrape access via firewall or network policy. [[`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189)] - `metrics.errorLabelMode: compact` is applied at `erpc.Init`; any series created before `Init` carry `verbose` labels until they expire. [[`erpc/init.go:L178-180`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L178-L180)] - Idle-series sweep evicts stale `upstream_request_duration_seconds` and `rate_limits_total` Prometheus series every ~5 minutes with a 30-minute idle window. [[`health/tracker.go:L557-563`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L557-L563), [`health/tracker.go:L598-631`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L598-L631)] ### Best practices - Set `GOMEMLIMIT` to 90 % of your container memory limit. The bundled kube/erpc.yml omits it entirely — Go's default GC will let the heap grow to the container ceiling, causing OOM kills rather than soft GC passes. - Both `waitBeforeShutdown` and `waitAfterShutdown` default to `10s` — raise both to `30s` for Kubernetes + Envoy/Cilium environments where LB drain windows are typically 20–30 s. - `terminationGracePeriodSeconds` must exceed `waitBeforeShutdown + waitAfterShutdown + expected drain time`. With both waits at 30 s, use `terminationGracePeriodSeconds: 90` minimum. - Always set `includeErrorDetails: false` before exposing eRPC externally — the default is `true` and upstream error messages routinely contain embedded API keys. - Set `evm.chainId` explicitly on every network and upstream to avoid an `eth_chainId` call burst on every pod restart or scale-out event. - For high-traffic multi-tenant deployments, drop `user` and `agent_name` with a `subject: "*"` entry in `metrics.customizations` — `erpc_upstream_request_duration_seconds` with those labels can produce thousands of Prometheus series; add an exact-subject `keep` to selectively re-add them on the specific families where per-user analysis is needed. - Alert on `erpc_unexpected_panic_total` at any non-zero rate — recovered panics mean a request goroutine crashed; they are surfaced as `-32603` errors to the caller rather than crashing the process, so they can go undetected without an alert. ### Edge cases & gotchas 1. **`maxTimeout: 0` (or bare `0`) fails validation** — `"server.maxTimeout is required"`. Integer YAML values are milliseconds: `maxTimeout: 150` = 150 ms. Always use string form `"150s"`. Source: [`common/validation.go:L90-92`](https://github.com/erpc/erpc/blob/main/common/validation.go#L90-L92), [`common/duration.go:L8-32`](https://github.com/erpc/erpc/blob/main/common/duration.go#L8-L32) 2. **`GOMEMLIMIT` is absent from all bundled manifests.** With a 3 Gi kube limit and default GC, heap can approach the limit before GC fires. Set `GOMEMLIMIT=2700MiB` as a container env var. Source: [`kube/erpc.yml:L33-36`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L33-L36) 3. **`terminationGracePeriodSeconds` must exceed `waitBeforeShutdown + waitAfterShutdown + drain time`.** With both set to 30 s, use `terminationGracePeriodSeconds: 90` minimum. Kubernetes SIGKILL fires when this expires, cutting in-flight requests. 4. **`metrics.hostV4: 127.0.0.1` does not restrict the metrics port.** The bind address is always `0.0.0.0:`. Restrict via firewall, network policy, or run the metrics server inside a VPC. Source: [`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189) 5. **`server.responseHeaders` with an env var that is unset at startup silently omits the header.** No warning is emitted. If `X-ERPC-Region: ${REGION}` is configured and that env var is absent in a new region, the header disappears with no observable error. Source: [`erpc/http_server.go:L135-148`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L135-L148) 6. **`metrics.errorLabelMode: verbose` can create unbounded Prometheus cardinality.** Full error messages include block numbers and IP addresses. Existing `compact` series and new `verbose` series co-exist until the verbose ones expire. Source: [`common/errors.go:L17-66`](https://github.com/erpc/erpc/blob/main/common/errors.go#L17-L66) 7. **The monitoring container (Prometheus + Grafana combined) is not production-suitable.** It runs both processes under `tail -f /dev/null`; if either crashes neither restarts. Use separate Prometheus and Grafana deployments in production. Source: `monitoring/Dockerfile` 8. **Alert rules reference stale metric names.** `HighRateLimiting` and `NetworkRateLimiting` use `erpc_upstream_request_self_rate_limited_total` / `erpc_network_request_self_rate_limited_total`. The current metric is `erpc_rate_limits_total`. Source: `monitoring/prometheus/alert.rules` 9. **`kube/postgres.yml` pins `postgres:latest`.** No digest. Pin a specific PostgreSQL version before deploying the bundled manifest. Source: `kube/postgres.yml` 10. **`docker compose down` (without `--volumes`) preserves monitoring data; `make down` passes `--volumes` and destroys `prometheus_data` and `grafana_data`.** Source: [`Makefile:L114`](https://github.com/erpc/erpc/blob/main/Makefile#L114) 11. **`trustedIPHeaders: []` (the default) means all requests appear to originate from the load-balancer IP.** IP-based rate limits and `network` auth strategies become effectively global rather than per-client. Source: [`common/defaults.go:L730-733`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L730-L733) 12. **`includeErrorDetails: true` in production exposes upstream endpoint URLs and potentially embedded API keys** in JSON-RPC `error.data`. Source: [`erpc/http_server.go:L1424-1433`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1424-L1433) 13. **gRPC traffic on the shared port bypasses `maxTimeout` and the gzip handler.** By default `server.grpcPortV4 = server.httpPortV4 = 4000`. When `grpcEnabled: true`, gRPC and HTTP share port 4000 via in-handler mux. If you separate the ports (e.g. gRPC on 4002), add the explicit Docker `-p 4002:4002` flag — only ports 4000, 4001, and 6060 are `EXPOSE`d in the Dockerfile. Source: [`erpc/http_server.go:L158-177`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L158-L177), [`Dockerfile:L84`](https://github.com/erpc/erpc/blob/main/Dockerfile#L84) 14. **The distroless/nonroot image has no shell, no package manager, and no debug tools.** The final container runs as a nonroot user with the minimal distroless base. Exec-ing into the container, mounting files dynamically, or attaching profilers requires a privileged sidecar. The default `CMD` is `/erpc-server`, not a shell wrapper. Source: `Dockerfile` 15. **TypeScript config files (`erpc.ts`) require Node.js, which is NOT in the distroless image.** The compiled TypeScript SDK and `node_modules` are present, and eRPC invokes a bundled Node execution path for `.ts` config loading. If `node_modules` is stripped from a custom image layer, TypeScript config loading fails silently and the process may not find a valid config file. 16. **`erpc-server-pprof` is present in every image but is never the default CMD.** The pprof binary is always built into the image at `/erpc-server-pprof` but the default `CMD` is `/erpc-server`. Operators must override the container command to use pprof — it is not activated by any env var or config flag. Source: `Dockerfile:L84`, `Makefile` (`run-pprof` target) 17. **The `prometheus.yaml` at the repo root is NOT the monitoring container's config.** It is the production Prometheus Operator config (with `remote_write` to Mimir, in-cluster job discovery). The monitoring container at `monitoring/prometheus/prometheus.yml` is a separate file with different scrape targets. Loading the wrong one into the monitoring container will produce empty or incorrect dashboards. Source: `prometheus.yaml`, `monitoring/prometheus/prometheus.yml` ### WebSocket subscriptions If you serve [`eth_subscribe`](/operation/websocket.llms.txt) traffic, a few additional notes: - **Upstream load does not grow with clients** — `newHeads` is one upstream subscription per subscription source while any client needs every block (`onDemand`), or from network init (`always`); `logs` makes no upstream subscription: each instance fetches `eth_getBlockReceipts` once per block that may match a filter, whatever the number of clients. Budget about 2.5 receipts calls/s per instance on a 0.4s chain, and send them to upstreams that gzip. - **No queue or indexer settings** — subscriptions read the chain feed with no per-subscription buffer and no `indexer` block. Strict config decoding rejects `server.webSocket.subscriptionBufferSize` and `indexer`; the tracker's only settings are [`evm.chainTracker`](/config/projects/networks.llms.txt). - **Instance-local subscriptions** — a client WS connection lives on one eRPC instance; its subscriptions end when that connection closes, so clients must re-subscribe after reconnecting. - **Slow-client policy** — a subscription whose next block has waited more than `chainTracker.reorgWindow` × the block time: `newHeads` restarts after the head (a jump in numbers), `logs` closes the connection with `1013`. Watch `erpc_tap_end_total{reason="lagging"}`. - **Shutdown** — new WS work is refused as soon as shutdown begins (upgrades get `503`); active connections send `1001` after in-flight requests finish or `waitBeforeShutdown` expires, so clients reconnect to another instance while the load balancer drains this one. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_errors_total` | counter | project, vendor, network, upstream, category, error, severity | upstream attempt errored; used by `HighErrorRate` alert | | `erpc_upstream_request_duration_seconds` | LabeledHistogram | project, vendor, network, upstream, category | upstream attempt duration | | `erpc_upstream_request_duration_seconds_budget` | LabeledHistogram | project, vendor, network, upstream, category | upstream attempt duration (budget variant); used by `SlowRequests` alert (p95 `histogram_quantile`) | | `erpc_upstream_request_total` | counter | project, vendor, network, upstream, category | each upstream attempt; used by `HighRequestRate` / `LowRequestRate` alerts | | `erpc_rate_limits_total` | counter | project, network, vendor, upstream, category, budget, scope, origin | rate-limit event (local or remote upstream 429); replaces stale `self_rate_limited_total` alert metrics | | `erpc_unexpected_panic_total` | counter | scope, extra, error | recovered panic by location; alert on any non-zero rate | | `erpc_upstream_cordoned` | gauge | project, vendor, network, upstream, category, reason | 1 when upstream is cordoned; 0 on uncordon | **Bundled alert rules** (`monitoring/prometheus/alert.rules`): | Alert | Condition | Severity | |---|---|---| | `HighErrorRate` | upstream error rate > 5% for 5 min | warning | | `SlowRequests` | upstream p95 latency > 1 s for 5 min | warning | | `HighRateLimiting` | upstream self-rate-limited > 10% for 5 min (stale metric — use `erpc_rate_limits_total`) | warning | | `NetworkRateLimiting` | network self-rate-limited > 10 req/s for 5 min (stale metric) | warning | | `HighRequestRate` | upstream request rate > 1000 req/s for 5 min | warning | | `LowRequestRate` | upstream request rate < 1 req/s for 15 min | warning | ### Source code entry points - [`erpc/http_server.go:L78-L83`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L78-L83) — drain flag set on SIGTERM; healthcheck returns 503 - [`erpc/http_server.go:L209-L221`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L209-L221) — `waitBeforeShutdown` sleep + `Shutdown` call with 30 s budget - [`erpc/init.go:L172-L177`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L172-L177) — `waitAfterShutdown` sleep before process exit - [`erpc/http_timeout.go:L36-L143`](https://github.com/erpc/erpc/blob/main/erpc/http_timeout.go#L36-L143) — custom `TimeoutHandler` (timeout/cancel bodies, buffered response, panic propagation) - [`erpc/init.go`](https://github.com/erpc/erpc/blob/main/erpc/init.go) — metrics HTTP server construction; the Prometheus handler over `telemetry.Gatherer` on `:%d`; 5 s shutdown - [`common/defaults.go:L694-L733`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L694-L733) — `ServerConfig.SetDefaults`: maxTimeout, readTimeout, writeTimeout, waitBeforeShutdown, waitAfterShutdown, includeErrorDetails, executionHeaders, trustedIPForwarders, trustedIPHeaders - [`common/defaults.go:L749-L767`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L749-L767) — `MetricsConfig.SetDefaults`: enabled, port, errorLabelMode - [`kube/erpc.yml:L33-L36`](https://github.com/erpc/erpc/blob/main/kube/erpc.yml#L33-L36) — reference kube resource spec (3 Gi / 2 CPU; no GOMEMLIMIT) - [`monitoring/prometheus/alert.rules`](https://github.com/erpc/erpc/blob/main/monitoring/prometheus/alert.rules) — 6 bundled alerting rules - [`cmd/erpc/main.go:L279-L294`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L279-L294) — config file discovery: 12-path ordered search - [`cmd/erpc/main.go:L354-L363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) — `LOG_LEVEL` env var override - [`cmd/erpc/main.go:L53-L57`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L53-L57) — `LOG_WRITER=console` zerolog console writer - [`cmd/erpc/main.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go) — `validate` and `dump` CLI subcommands ### Related pages - [Deployment](/deployment.llms.txt) — Docker, Kubernetes, and Compose setup instructions. - [Rate limiters](/config/rate-limiters.llms.txt) — per-IP and per-user budget configuration that depends on correct `trustedIPHeaders`. - [Auth](/config/auth.llms.txt) — the `network` auth strategy uses the resolved client IP. - [Observability](/operation/monitoring.llms.txt) — full metrics and alerting reference. - [Fail-safe: timeout](/config/failsafe/timeout.llms.txt) — per-request upstream deadline distinct from `server.maxTimeout`. --- --- # Tracing & logging > Source: https://docs.erpc.cloud/operation/tracing > Every request, cache lookup, and upstream call becomes a searchable span — shipped to any OTel backend. Secrets never leave the process. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Tracing & logging eRPC instruments every layer of the request pipeline — inbound HTTP, routing, cache lookups, upstream calls — and exports those spans over OTLP to any OpenTelemetry-compatible backend. Structured JSON logs run at five verbosity levels, secrets are redacted before any line is written, and a force-trace override lets you capture full detail for a single network or method without touching global sampling. **What you get** - End-to-end distributed traces from caller through every upstream hop - Two span tiers: always-on for data-plane ops, detailed for high-cardinality debug info - Force-trace by request header, query param, or config pattern — even at `sampleRate: 0` - Automatic secret redaction for all API keys and passwords in logs and config dumps - W3C TraceContext propagation: eRPC becomes a child of your caller's trace ## Quick taste Illustrative, not a tuned production config — 10 % sampling, gRPC export: **Config path:** `tracing` **YAML — `erpc.yaml`:** ```yaml tracing: enabled: true # OTLP gRPC collector — eRPC always overrides OTEL_EXPORTER_OTLP_ENDPOINT endpoint: localhost:4317 protocol: grpc # 10 % ambient sampling — sampleRate: 0 is rewritten to 1.0 by SetDefaults, use enabled: false to disable sampleRate: 0.1 serviceName: erpc-prod ``` **TypeScript — `erpc.ts`:** ```typescript tracing: { enabled: true, // OTLP gRPC collector — eRPC always overrides OTEL_EXPORTER_OTLP_ENDPOINT endpoint: "localhost:4317", protocol: "grpc", // 10 % ambient sampling — sampleRate: 0 is rewritten to 1.0 by SetDefaults, use enabled: false to disable sampleRate: 0.1, serviceName: "erpc-prod", } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: wire eRPC traces to my OTel collector** ```text Set up distributed tracing in my eRPC instance so every request, cache lookup, and upstream call produces spans exported to my OpenTelemetry collector. Work with my existing eRPC config. and my collector is at otel-collector:4317. Choose a sensible production sample rate and explain the sampleRate: 0 footgun. Read the full reference first: https://docs.erpc.cloud/operation/tracing.llms.txt ``` **Prompt Example #2: force full traces on debug methods only** ```text I want eRPC to sample at 5% normally but always capture 100% traces for debug_* and trace_* methods so I can triage slow calls without raising global sample rate. Update my eRPC config with the right forceTraceMatchers config. Reference: https://docs.erpc.cloud/operation/tracing.llms.txt ``` **Prompt Example #3: send traces to Grafana Cloud with auth** ```text Configure eRPC's OTLP exporter in my eRPC config to send traces to my Grafana Cloud OTLP HTTP endpoint with bearer-token auth headers and TLS enabled. Include the sample rate and serviceName settings appropriate for production. Reference: https://docs.erpc.cloud/operation/tracing.llms.txt ``` **Prompt Example #4: debug missing or noisy spans** ```text My tracing backend shows either no spans from eRPC or too many after a config change. Diagnose the issue in my eRPC config — check sampleRate zero-rewrite, OTEL env var overrides, and detailed mode cost — and fix the config so I get the spans I expect. Reference: https://docs.erpc.cloud/operation/tracing.llms.txt ``` --- ### Tracing & logging — full agent reference ### How it works **Tracing initialization.** On startup, `NewERPC` calls `common.InitializeTracing` exactly once (guarded by `sync.Once`). When enabled, it builds an OTLP exporter (gRPC via `otlptracegrpc` or HTTP via `otlptracehttp`), constructs a `TracerProvider` with a batcher and a custom sampler, wires W3C TraceContext + Baggage propagation, and stores any `forceTraceMatchers` for per-request evaluation. Two package-level booleans — `IsTracingEnabled` and `IsTracingDetailed` — are set once and consulted on every hot-path span call with zero allocation when tracing is off. [[`common/tracing_core.go:L53-148`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L53-L148)] **Two span tiers.** All instrumented call sites use one of two helpers: - `StartSpan` — fires whenever `IsTracingEnabled`; covers major external interactions: cache, upstreams, connectors, rate limiters, consensus. - `StartDetailSpan` — fires only when both `IsTracingEnabled` and `IsTracingDetailed`; covers eRPC-internal operations and spans carrying high-cardinality attributes such as request params, block numbers, lock contention, and hook execution. Enabling `detailed: true` roughly doubles span count. When tracing is disabled, both helpers return the caller's unchanged context and a singleton `noopSpan` — no allocation on the hot path. [[`common/tracing_util.go:L1-234`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L1-L234)] **Span hierarchy for a single HTTP request (normal mode):** ``` Http.ReceivedRequest (SpanKindServer) └─ Request.Handle (SpanKindInternal) └─ Network.Forward └─ Network.forwardAttempt ├─ Cache.Get └─ Upstream.Forward └─ HttpJsonRpcClient.sendSingleRequest ``` With `detailed: true`, additional spans appear inside the HTTP layer (`Http.ReadBody`, `Http.ParseRequests`, `HttpServer.WriteResponse`), between Forward and forwardAttempt (`Project.Forward`, `Network.TryForward`, `Network.UpstreamLoop`), and inside upstream execution (`RateLimiter.TryAcquirePermit`, `Upstream.tryForward.PreRequest`, `Upstream.tryForward.SendRequest`), cache lookup, lock/parse ops, and method-specific hooks. **Sampler logic.** `createTracingSampler` builds the base sampler from `sampleRate`: - `<= 0` → `NeverSample()` - `>= 1.0` → `AlwaysSample()` - otherwise → `ParentBased(TraceIDRatioBased(rate))` with all four parent-sampling options configured for consistency (no orphan spans) The `forceTraceSampler` always wraps the base sampler regardless of rate. [[`common/tracing_core.go:L229-268`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L229-L268)] **Force-trace mechanism.** Three paths can force a span to be recorded regardless of `sampleRate`: 1. HTTP header `X-ERPC-Force-Trace: true` (or `1`, `yes`) — checked at request entry. 2. Query parameter `?force-trace=true` — same check. 3. Config-driven `forceTraceMatchers` — evaluated after the URL is parsed and the network is known. Each matcher can specify `network` (in `architecture:chainId` form, e.g. `evm:1`) and/or `method` (JSON-RPC method pattern). Pipe (`|`) = OR; wildcards supported. Both fields present on one matcher = AND semantics. In all cases, the force-trace decision is communicated to the OTel sampler by setting the span attribute `erpc.force_trace = true` at creation time. The custom `forceTraceSampler` wraps the base sampler and returns `RecordAndSample` unconditionally when it sees this attribute — even when `sampleRate: 0`. [[`common/tracing_core.go:L257-268`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L257-L268)] **Context propagation.** Incoming HTTP requests have `traceparent`/`tracestate` extracted via W3C `TraceContext{}` carrier, making eRPC spans children of the caller's trace. After the response is written, `InjectHTTPResponseTraceContext` injects the active span context back into response headers so downstream callers can correlate their traces. gRPC requests have no OTel trace extraction — they start with a fresh root span. [[`common/tracing_util.go:L58-74`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L58-L74)] **Logging system.** zerolog is the structured JSON logger used throughout eRPC. Default output is newline-delimited JSON with Unix-millisecond timestamps: ```json {"level":"info","time":1718000000123,"message":"...","key":"value"} ``` Set `LOG_WRITER=console` to switch to a human-readable format for local development: ``` 04:05.000ms INF message key=value ``` Five levels are available: `trace`, `debug`, `info`, `warn`, `error` (plus `fatal`, `panic`, `disabled`). `LOG_LEVEL` environment variable overrides `logLevel` config at startup and again when the config is loaded, so it always wins. `ERPC_NOLOGS=1` silences all output at the binary level. When the resolved level is `info` or lower, eRPC serializes the entire loaded config as a JSON field in a startup log line. All secrets are redacted before this serialization. **Secret redaction.** Two layers: 1. `MarshalJSON`/`MarshalYAML` overrides on config types — called whenever config is serialized — replace secret fields with `"REDACTED"` or apply `util.RedactEndpoint`: | Config type | Field | Replacement | |---|---|---| | `RedisConnectorConfig` | `password` | `"REDACTED"` | | `RedisConnectorConfig` | `uri` | `util.RedactEndpoint(uri)` | | `PostgreSQLConnectorConfig` | `connectionUri` | `util.RedactEndpoint(connectionUri)` | | `AwsAuthConfig` | `secretAccessKey` | `"REDACTED"` | | `ProviderConfig` | `settings` | `"REDACTED"` | | `UpstreamConfig` | `endpoint` | `util.RedactEndpoint(endpoint)` | | `SecretStrategyConfig` | `value` | `"REDACTED"` | [[`common/config.go:L397-503`](https://github.com/erpc/erpc/blob/main/common/config.go#L397-L503)] 2. `util.RedactEndpoint` — computes a SHA-256 of the full original URL, takes the first 5 hex chars as a stable identifier, then strips path and credentials according to scheme: - Native-protocol endpoints (`alchemyv2://`, `erigon://`, etc.): `scheme://host#redacted=` - Envio-suffix schemes: `scheme://host` (no hash needed — no secrets in path) - Repository-suffix schemes: `scheme://host#redacted=` - Standard `http`/`https` RPC endpoints: `scheme#redacted=` — **hostname is also dropped** - Unparseable URL: `"redacted="` Two endpoints with the same scheme but different paths (API keys) produce different hashes, enabling correlation without exposing secrets. [[`util/redact.go:L10-36`](https://github.com/erpc/erpc/blob/main/util/redact.go#L10-L36)] **OTel resource attributes.** The `TracerProvider` is built with a resource that includes `service.name` (from `tracing.serviceName`), `service.version` (the compiled-in `ErpcVersion` constant), `commit.sha` (the compiled-in `ErpcCommitSha` constant), and any key/value pairs from `tracing.resourceAttributes`. Environment variables in `resourceAttributes` values are expanded via `os.ExpandEnv` at config load; empty values after expansion are silently skipped. [[`common/tracing_core.go:L93-102`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L93-L102)] The OTel instrumentation name registered by eRPC is `"github.com/erpc/erpc"`. [[`common/tracing_core.go:L26`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L26)] **Error recording.** `SetTraceSpanError` checks `span.IsRecording()` before acting. For `StandardError` types it sets an `error.code` span attribute (the full error-code chain) and records the error as a span event; for plain `error` values it calls `span.RecordError` and sets the span status to `codes.Error`. [[`common/tracing_core.go:L163-183`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L163-L183)] **Force-flush.** `common.ForceFlushTraces(ctx)` calls `tracerProvider.ForceFlush(ctx)`, flushing all batched but not-yet-exported spans to the collector immediately. It is called automatically on graceful shutdown and exposed for callers that need guaranteed delivery of critical traces. [[`common/tracing_core.go:L237-245`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L237-L245)] **Graceful shutdown.** A goroutine watches `appCtx.Done` and flushes buffered spans with a 5-second grace period before the process exits. [[`erpc/erpc.go:L92-99`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go#L92-L99)] ### Config schema #### Top-level `logLevel` | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `logLevel` | string | `"INFO"` ([`common/defaults.go:L50-51`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L50-L51)) | Controls log verbosity for all eRPC subsystems. Valid: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`, `disabled` (case-insensitive). Invalid value → warning + fallback to `debug` ([`erpc/init.go:L27-32`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L27-L32)). Overridden by `LOG_LEVEL` env var at config-load time ([`cmd/erpc/main.go:L354-363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363)). | #### `tracing.*` Full struct: [`common/config.go:L218-235`](https://github.com/erpc/erpc/blob/main/common/config.go#L218-L235). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `tracing.enabled` | bool | `false` (Go zero value) | Master switch. When `false`, sets `IsTracingEnabled = false` globally; all span calls are no-ops ([`common/tracing_core.go:L53-58`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L53-L58)). | | `tracing.endpoint` | string | `"localhost:4317"` (gRPC) or `"http://localhost:4318"` (HTTP) — derived from `protocol` in `SetDefaults` ([`common/defaults.go:L622-628`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L622-L628)) | OTLP collector endpoint. gRPC: `host:port` with no scheme. HTTP: `http(s)://host:port[/path]` or `host:port`; the URL scheme decides TLS (`http://` with `tls.enabled` is an init error), and a URL without a path exports to `/v1/traces`. **Footgun:** `OTEL_EXPORTER_OTLP_ENDPOINT` is always overridden by this field even when it holds the default value. | | `tracing.protocol` | TracingProtocol | `"grpc"` ([`common/defaults.go:L619-621`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L619-L621)) | `"grpc"` uses `otlptracegrpc`; `"http"` uses `otlptracehttp`. Any other value → error at init ([`common/tracing_core.go:L71-78`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L71-L78)). | | `tracing.sampleRate` | float64 | `1.0` ([`common/defaults.go:L629-631`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L629-L631)) | `<= 0` → `NeverSample()`, `>= 1.0` → `AlwaysSample()`, otherwise → `ParentBased(TraceIDRatioBased(rate))`. **Footgun:** `SetDefaults` replaces `0` with `1.0`, so `sampleRate: 0` in YAML means "always sample", not "never sample". To keep tracing on but silent, use a very small positive value like `0.0000001`. | | `tracing.detailed` | bool | `false` (Go zero value) | When `true`, sets `IsTracingDetailed = true`, enabling `StartDetailSpan` calls. Roughly 2× span count. Includes request params, block numbers, lock spans, hook execution spans. | | `tracing.serviceName` | string | `"erpc"` ([`common/defaults.go:L632-634`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L632-L634)) | OTel `service.name` resource attribute. | | `tracing.headers` | map[string]string | nil | Additional metadata headers sent with every OTLP export batch. Used for auth to managed collectors (Grafana Cloud, Honeycomb, Datadog). When set, takes precedence over `OTEL_EXPORTER_OTLP_HEADERS`. | | `tracing.tls.enabled` | bool | `false` (Go zero value) | Master switch for TLS on the OTLP exporter. When `false`, exporters are created with `WithInsecure()` ([`common/tracing_core.go:L187`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L187)). | | `tracing.tls.certFile` | string | `""` | Path to PEM client certificate for mTLS. Both `certFile` and `keyFile` must be non-empty; supplying one without the other silently skips mutual TLS. | | `tracing.tls.keyFile` | string | `""` | Path to PEM private key corresponding to `certFile`. Required alongside `certFile` for mTLS. | | `tracing.tls.caFile` | string | `""` | Path to PEM CA certificate. When set, the collector's server cert is validated against this CA instead of the system pool. | | `tracing.tls.insecureSkipVerify` | bool | `false` | When `true`, disables verification of the OTLP collector's server cert. Does not affect client-cert loading. Only for development or trusted private networks. | | `tracing.resourceAttributes` | map[string]string | nil | Custom OTel resource attributes. Values are `os.ExpandEnv`-expanded at config load. Empty values after expansion are silently skipped ([`common/tracing_core.go:L93-97`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L93-L97)). | | `tracing.forceTraceMatchers` | []*ForceTraceMatcher | nil | Matchers that bypass `sampleRate` and force `RecordAndSample`. | | `tracing.forceTraceMatchers[].network` | string | — | Network pattern in `architecture:chainId` form, e.g. `"evm:1"`, `"evm:1\|evm:42161"`, `"evm:*"`. Pipe = OR; wildcards via `WildcardMatch`. | | `tracing.forceTraceMatchers[].method` | string | — | JSON-RPC method pattern, e.g. `"eth_call"`, `"debug_*\|trace_*"`. Pipe = OR; wildcards supported. | **ForceTraceMatcher AND/OR semantics:** when both `network` and `method` are specified on one matcher, both must match (AND). If only one field is set, only that field is checked. An empty matcher (neither field) never matches ([`common/tracing_core.go:L306-330`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L306-L330)). #### Standard `OTEL_*` environment variables | Env var | Interaction with eRPC config | |---|---| | `OTEL_EXPORTER_OTLP_ENDPOINT` | **Overridden.** eRPC always passes `WithEndpoint(cfg.Endpoint)`; this env var is silently ignored. | | `OTEL_EXPORTER_OTLP_HEADERS` | **Partially overridden.** Only takes effect when `tracing.headers` is nil/empty in config. | | `OTEL_SERVICE_NAME` | **Not explicitly overridden, but eRPC always sets `service.name`.** eRPC builds its resource with `semconv.ServiceNameKey.String(cfg.ServiceName)`. If the OTel SDK's default detectors also read `OTEL_SERVICE_NAME`, last-writer-wins resource merge semantics apply; eRPC's explicit value is always present. | | `OTEL_TRACES_SAMPLER` | **Ignored.** eRPC supplies its own sampler via explicit SDK option. | | `OTEL_PROPAGATORS` | **Ignored.** eRPC explicitly sets TraceContext + Baggage propagators. | | `OTEL_SDK_DISABLED` | **Honored.** Disables all OTel SDK operations globally before `InitializeTracing` runs. | ### Worked examples **1. Production setup: 10 % sampling with force-trace on debug methods.** Low ambient cost; debug-namespace calls always produce a full trace for triage: **Config path:** `tracing` **YAML — `erpc.yaml`:** ```yaml tracing: enabled: true endpoint: otel-collector:4317 protocol: grpc sampleRate: 0.1 serviceName: erpc-prod forceTraceMatchers: - method: "debug_*|trace_*" ``` **TypeScript — `erpc.ts`:** ```typescript tracing: { enabled: true, endpoint: "otel-collector:4317", protocol: "grpc", sampleRate: 0.1, serviceName: "erpc-prod", forceTraceMatchers: [{ method: "debug_*|trace_*" }], } ``` **2. Detailed mode for a staging environment.** Capture every span including request params, block numbers, and lock contention to understand slow calls — not recommended in production due to 2× span volume: **Config path:** `tracing` **YAML — `erpc.yaml`:** ```yaml tracing: enabled: true endpoint: tempo:4317 sampleRate: 1.0 detailed: true serviceName: erpc-staging ``` **TypeScript — `erpc.ts`:** ```typescript tracing: { enabled: true, endpoint: "tempo:4317", sampleRate: 1.0, detailed: true, serviceName: "erpc-staging", } ``` **3. Managed collector with auth headers and TLS.** For Grafana Cloud or Honeycomb where the OTLP endpoint requires a bearer token: **Config path:** `tracing` **YAML — `erpc.yaml`:** ```yaml tracing: enabled: true endpoint: "https://otlp-gateway.grafana.net/otlp" protocol: http sampleRate: 0.05 headers: Authorization: "Basic " ``` **TypeScript — `erpc.ts`:** ```typescript tracing: { enabled: true, endpoint: "https://otlp-gateway.grafana.net/otlp", protocol: "http", sampleRate: 0.05, headers: { Authorization: "Basic " }, } ``` **4. Silent tracing for force-trace-only capture.** Keep tracing on but produce no ambient spans — only requests that carry `X-ERPC-Force-Trace: true` or match a configured matcher are recorded. Use `sampleRate: 0.0000001` because `sampleRate: 0` is rewritten to `1.0` by `SetDefaults`: **Config path:** `tracing` **YAML — `erpc.yaml`:** ```yaml tracing: enabled: true endpoint: localhost:4317 sampleRate: 0.0000001 forceTraceMatchers: - network: "evm:1" method: "eth_call" ``` **TypeScript — `erpc.ts`:** ```typescript tracing: { enabled: true, endpoint: "localhost:4317", sampleRate: 0.0000001, forceTraceMatchers: [{ network: "evm:1", method: "eth_call" }], } ``` ### Request/response behavior - Incoming HTTP requests with `traceparent`/`tracestate` headers become children of the caller's trace. eRPC spans are nested under the caller's root span. - After the response is written, the active span's W3C context is injected back into HTTP response headers unconditionally — including error responses. Trace IDs are observable to callers. [[`erpc/http_server.go:L701`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L701)] - For batch HTTP requests, each item gets its own `Request.Handle` child span under a single `Http.ReceivedRequest` parent. All child spans may be in-flight simultaneously. [[`erpc/http_server.go:L465`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L465)] - gRPC requests start a fresh root span — no trace context extraction is implemented for the gRPC server path. [[`erpc/grpc_server.go`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go)] - OTLP export failures are logged at `trace` level only and never propagate to callers. [[`common/tracing_core.go:L125-127`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L125-L127)] - `Request.Handle` is started via `tracer.Start` directly (not `StartSpan`), so it fires whenever `IsTracingEnabled`, regardless of `IsTracingDetailed`. This is the correct attach point for distributed callers. [[`common/tracing_util.go:L165`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L165)] **Span attributes on `Request.Handle`** (set by `StartRequestSpan`/`EndRequestSpan`): | Attribute | Mode | Value | |---|---|---| | `request.method` | always | JSON-RPC method name | | `erpc.force_trace` | always, when forced | `true` (bool, internal — used by sampler to force `RecordAndSample`; not a user-visible exported attribute) | | `erpc.forced_trace_reason` | when forced | `"header_or_query"` or `"network:,method:"` etc. | | `request.id` | detailed only | JSON-RPC request ID as string | | `request.jsonrpc.params` | detailed only | JSON-serialized params array | | `network.id` | detailed only, on response | Network ID string | | `user.id` | detailed only, on response | Auth user ID | | `request.finality` | detailed only, on response | Finality label (e.g. `"realtime"`, `"finalized"`) | | `response.finality` | detailed only, on response | Response finality | | `execution.attempts` | detailed only, on response | Total attempts | | `execution.retries` | detailed only, on response | Number of retries | | `execution.hedges` | detailed only, on response | Number of hedges | | `response.result_size` | detailed only, on response | Length of JSON-RPC result field | | `upstream.id` | always (if non-nil), on response | Upstream identifier | | `cache.hit` | always (if non-nil), on response | bool: whether response was served from cache | **Span attributes on `Http.ReceivedRequest`** (set by `StartHTTPServerSpan`/`EnrichHTTPServerSpan`): | Attribute | Phase | Value | |---|---|---| | `http.method` | on request | HTTP method (semconv) | | `http.url` | on request | Full request URL | | `http.scheme` | on request | URL scheme | | `http.user_agent` | on request | User-Agent header value | | `erpc.force_trace` | on request, when forced | `true` (if forced via header/query) | | `erpc.forced_trace_reason` | on request, when forced | `"header_or_query"` | | `http.status_code` | on response | HTTP response status code (semconv) | [[`common/tracing_util.go:L80-138`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L80-L138)] ### Best practices - Set `sampleRate: 0.05`–`0.2` in production — `AlwaysSample()` at scale sends enormous span volume to your collector. - Use `forceTraceMatchers` with `method: "debug_*|trace_*"` to guarantee full traces on expensive diagnostic methods regardless of sample rate — this costs nothing extra for normal traffic. - Never set `sampleRate: 0` thinking it means "disabled" — `SetDefaults` rewrites it to `1.0`. Use `enabled: false` to disable tracing entirely. - Enable `detailed: true` only in staging or on-demand: 2× span count and high-cardinality attributes (params, block numbers) can saturate a collector or inflate storage costs. - Always set `tracing.endpoint` explicitly — do not rely on `OTEL_EXPORTER_OTLP_ENDPOINT` to route spans to a remote collector; eRPC overrides it unconditionally. - Enable `tracing.tls.enabled: true` for any span export that leaves a trusted network; the default is `WithInsecure()`. - Force-trace via the `X-ERPC-Force-Trace: true` request header during integration testing to capture full detail without raising global sample rate. ### Edge cases & gotchas 1. **`initOnce.Do` means tracing config cannot change after first `NewERPC`.** Tests or multi-tenant code creating multiple ERPC instances will silently use only the first instance's tracing config. Source: [`common/tracing_core.go:L53`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L53) 2. **`sampleRate: 0` in YAML means "always sample", not "never sample".** `SetDefaults` replaces `0` with `1.0`. To keep tracing enabled but silent, set `0.0000001` or a very small positive value. Source: [`common/defaults.go:L629-631`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L629-L631) 3. **Force-trace network matching requires URL parsing to have succeeded.** `forceTraceMatchers` with `network` patterns never match admin or healthcheck requests. Source: [`erpc/http_server.go:L285-288`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L285-L288) 4. **W3C traceparent injection into HTTP responses is unconditional** when tracing is enabled — including error responses. Trace IDs are observable to callers. Source: [`erpc/http_server.go:L701`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L701) 5. **gRPC server has no OTel trace extraction.** gRPC-originated requests start with a fresh root span, not as children of the caller's trace. Source: `erpc/grpc_server.go` 6. **TLS on the OTLP exporter is off by default.** Both gRPC and HTTP exporters use `WithInsecure()` unless `tracing.tls.enabled: true`. Production deployments sending spans over the internet should enable TLS. Source: [`common/tracing_core.go:L187`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L187) 7. **`OTEL_EXPORTER_OTLP_ENDPOINT` is silently overridden.** eRPC always calls `WithEndpoint(cfg.Endpoint)`, so this env var has no effect. Set `tracing.endpoint` in config explicitly. Source: [`common/tracing_core.go:L197`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L197) 8. **`OTEL_TRACES_SAMPLER` and `OTEL_PROPAGATORS` have no effect.** eRPC supplies its own sampler and propagator via explicit SDK options. Source: [`common/tracing_core.go:L109`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L109) 9. **`OTEL_EXPORTER_OTLP_HEADERS` only takes effect when `tracing.headers` is nil/empty in config.** Source: [`common/tracing_core.go:L200-202`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L200-L202) 10. **`util.RedactEndpoint` drops the entire hostname for standard http/https URLs.** An endpoint like `https://eth-mainnet.alchemyapi.io/v2/SECRET` becomes `https#redacted=ab3c4`. Only native-protocol and repository-type endpoints keep `scheme://host`. Source: [`util/redact.go:L32-34`](https://github.com/erpc/erpc/blob/main/util/redact.go#L32-L34) 11. **`LOG_LEVEL` env var is applied twice** — once globally before config load, and again when `getConfig` overrides `cfg.LogLevel`. The second application persists into the running instance and always wins over the YAML `logLevel`. Source: [`cmd/erpc/main.go:L354-363`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L354-L363) 12. **OTel debug logging (zerologr bridge) is wired only at tracing init time.** If zerolog level is not `<= Debug` when `InitializeTracing` runs, OTel SDK internals are never logged, even if you lower the level later via the admin API. Source: [`common/tracing_core.go:L119-122`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L119-L122) 13. **`console.error` in TypeScript config scripts throws `TypeError`.** Only `debug`, `info`, `log`, `trace`, and `warn` are registered in the Sobek runtime. Source: [`common/console.go:L15-21`](https://github.com/erpc/erpc/blob/main/common/console.go#L15-L21) ### Observability There are no Prometheus metrics emitted by the tracing or logging subsystem. The tracing pipeline is a pure OTel concern; OTLP export errors are logged at `trace` level only and do not increment any counter. **Notable log messages:** | Level | Message | When | |---|---|---| | info | `"OpenTelemetry tracing is disabled"` | `tracing.enabled = false` | | info | `"initializing OpenTelemetry tracing"` + endpoint/protocol/sampleRate/detailed | Before exporter creation | | info | `"OpenTelemetry debug logging enabled"` | Only if zerolog level ≤ debug at init time | | info | `"OpenTelemetry tracing initialized successfully"` | After successful init | | info | `"force-trace matcher configured"` + index/network/method | Once per configured matcher | | trace | `"open telemetry export error"` | OTLP export failure | | error | `"failed to create span exporter"` | Exporter init failure | | error | `"failed to create resource"` | OTel resource build failure | | error | `"failed to initialize tracing"` | From `NewERPC` when `InitializeTracing` errors | | error | `"failed to shutdown tracer provider"` | On process shutdown | | warn | `"invalid log level '%s', defaulting to 'debug'"` | Unrecognized `logLevel` value | | info | (empty message, `config` JSON field) | Startup when level ≤ info: full redacted config dump | **OTel span name inventory.** "normal" = emitted when `tracing.enabled`; "detail" = emitted only when `tracing.enabled && tracing.detailed`; "direct" = calls `tracer.Start` directly (same threshold as normal). OTel instrumentation name: `"github.com/erpc/erpc"`. All 126 span names (expand) | Span name | Mode | Call site | |---|---|---| | `Cache.FindGetPolicies` | detail | `architecture/evm/json_rpc_cache.go:L173` | | `Cache.Get` | normal | `architecture/evm/json_rpc_cache.go:L153` | | `Cache.GetForPolicy` | detail | `architecture/evm/json_rpc_cache.go:L241` | | `Cache.Set` | normal | `architecture/evm/json_rpc_cache.go:L572` | | `ChainTracker.Fetch` | detail | `architecture/evm/chain_fetch.go:L452` | | `ConnectorFailsafe.Delete` | detail | `data/failsafe.go:L286` | | `ConnectorFailsafe.Get` | detail | `data/failsafe.go:L224` | | `ConnectorFailsafe.Set` | detail | `data/failsafe.go:L253` | | `Consensus.CollectResponses` | detail | `consensus/executor.go:L189` | | `Consensus.Run` | normal | `consensus/executor.go:L1282` | | `CounterInt64.TryUpdate` | normal | `data/shared_state_variable.go:L365` | | `CounterInt64.TryUpdateIfStale` | normal | `data/shared_state_variable.go:L391` | | `CounterInt64.TryUpdateIfStale.AcquireMutex` | normal | `data/shared_state_variable.go:L405` | | `CounterInt64.TryUpdateIfStale.ExecuteRefresh` | normal | `data/shared_state_variable.go:L430` | | `DynamoDBConnector.Delete` | normal | `data/dynamodb.go:L833` | | `DynamoDBConnector.Get` | normal | `data/dynamodb.go:L414` | | `DynamoDBConnector.List` | normal | `data/dynamodb.go:L874` | | `DynamoDBConnector.Lock` | normal | `data/dynamodb.go:L579` | | `DynamoDBConnector.Set` | normal | `data/dynamodb.go:L355` | | `DynamoDBConnector.Unlock` | normal | `data/dynamodb.go:L691` | | `DynamoDBConnector.getSimpleValue` | detail | `data/dynamodb.go:L766` | | `Evm.ExtractBlockReferenceFromRequest` | detail | `architecture/evm/block_ref.go:L19` | | `Evm.ExtractBlockReferenceFromResponse` | detail | `architecture/evm/block_ref.go:L118` | | `Evm.ExtractBlockTimestampFromResponse` | detail | `architecture/evm/block_ref.go:L191` | | `Evm.extractRefFromJsonRpcRequest` | detail | `architecture/evm/block_ref.go:L240` | | `Evm.extractRefFromJsonRpcResponse` | detail | `architecture/evm/block_ref.go:L314` | | `EvmStatePoller.Ask` | detail | `architecture/evm/evm_state_poller.go:L640` | | `EvmStatePoller.PollFinalizedBlockNumber` | detail | `architecture/evm/evm_state_poller.go:L1532` | | `GrpcBdsClient.GetBlockByHash` | detail | `clients/grpc_bds_client.go:L365` | | `GrpcBdsClient.GetBlockByNumber` | detail | `clients/grpc_bds_client.go:L422` | | `GrpcBdsClient.GetLogs` | detail | `clients/grpc_bds_client.go:L632` | | `GrpcBdsClient.QueryBlocks` | detail | `clients/grpc_bds_client.go:L1097` | | `GrpcBdsClient.QueryLogs` | detail | `clients/grpc_bds_client.go:L1173` | | `GrpcBdsClient.QueryTraces` | detail | `clients/grpc_bds_client.go:L1209` | | `GrpcBdsClient.QueryTransactions` | detail | `clients/grpc_bds_client.go:L1138` | | `GrpcBdsClient.QueryTransfers` | detail | `clients/grpc_bds_client.go:L1245` | | `GrpcBdsClient.SendRequest` | normal | `clients/grpc_bds_client.go:L194` | | `Http.ParseRequests` | detail | `erpc/http_server.go:L397` | | `Http.ReadBody` | detail | `erpc/http_server.go:L373` | | `Http.ReceivedRequest` | normal | `common/tracing_util.go:L96` | | `HttpJsonRpcClient.sendSingleRequest` | normal | `clients/http_json_rpc_client.go:L675` | | `HttpServer.WriteResponse` | detail | `erpc/http_server.go:L680` | | `JsonRpcRequest.Lock` | detail | `common/json_rpc.go:L1229` | | `JsonRpcRequest.RLock` | detail | `common/json_rpc.go:L1235` | | `JsonRpcResponse.IsResultEmptyish` | detail | `common/json_rpc.go:L799` | | `JsonRpcResponse.ParseFromStream` | detail | `common/json_rpc.go:L288` | | `JsonRpcResponse.PeekBytesByPath` | detail | `common/json_rpc.go:L486` | | `JsonRpcResponse.PeekStringByPath` | detail | `common/json_rpc.go:L464` | | `Multiplexer.Close` | detail | `erpc/multiplexer.go:L37` | | `Network.EnrichStatePoller` | detail | `erpc/networks.go:L2146` | | `Network.Forward` | normal | `erpc/networks.go:L943` | | `Network.GetFinality` | detail | `erpc/networks.go:L1646` | | `Network.NormalizeResponse` | detail | `erpc/networks.go:L2235` | | `Network.PostForward.eth_blockNumber` | detail | `architecture/evm/eth_blockNumber.go:L69` | | `Network.PostForward.eth_getBlockByNumber` | detail | `architecture/evm/eth_getBlockByNumber.go:L44` | | `Network.PostForward.eth_sendRawTransaction` | detail | `architecture/evm/eth_sendRawTransaction.go:L280` | | `Network.PostForwardHook` | detail | `architecture/evm/hooks.go:L64` | | `Network.PreForwardHook` | detail | `architecture/evm/hooks.go:L41` | | `Network.PreForwardHook.eth_chainId` | detail | `architecture/evm/eth_chainId.go:L79` | | `Network.TryForward` | detail | `erpc/networks.go:L1137` | | `Network.UpstreamLoop` | detail | `erpc/networks.go:L1227` | | `Network.WaitForMultiplexResult` | normal | `erpc/networks.go:L2058` | | `Network.forwardAttempt` | normal | `erpc/networks.go:L1188` | | `PolicyEngine.GetOrdered` | detail | `erpc/networks.go:L1023` | | `PostgreSQLConnector.Delete` | normal | `data/postgresql.go:L1130` | | `PostgreSQLConnector.Get` | normal | `data/postgresql.go:L466` | | `PostgreSQLConnector.List` | normal | `data/postgresql.go:L1165` | | `PostgreSQLConnector.Lock` | normal | `data/postgresql.go:L526` | | `PostgreSQLConnector.PublishCounterInt64` | normal | `data/postgresql.go:L683` | | `PostgreSQLConnector.Set` | normal | `data/postgresql.go:L409` | | `PostgreSQLConnector.Unlock` | normal | `data/postgresql.go:L589` | | `PostgreSQLConnector.getCurrentValue` | detail | `data/postgresql.go:L974` | | `PostgreSQLConnector.getWithWildcard` | detail | `data/postgresql.go:L1006` | | `Project.Forward` | detail | `erpc/projects.go:L103` | | `Project.PreForwardHook` | detail | `architecture/evm/hooks.go:L14` | | `Project.PreForwardHook.eth_chainId` | detail | `architecture/evm/eth_chainId.go:L30` | | `Project.executeShadowRequest` | detail | `erpc/shadow.go:L82` | | `Query.Execute` | detail | `erpc/query_executor.go:L45` | | `Query.ForwardSubrequest` | detail | `erpc/query_shim.go:L427` | | `Query.ResolveQueryBounds` | detail | `erpc/query_executor.go:L277` | | `Query.ShimBlocks` | detail | `erpc/query_shim.go:L18` | | `Query.ShimLogs` | detail | `erpc/query_shim.go:L112` | | `Query.ShimTraces` | detail | `erpc/query_shim.go:L187` | | `Query.ShimTransactions` | detail | `erpc/query_shim.go:L55` | | `QueryStream.Handle` | normal | `erpc/request_processor.go:L76` | | `RateLimiter.DoLimit` | normal | `upstream/ratelimiter_budget.go:L279` | | `RateLimiter.TryAcquirePermit` | detail | `upstream/ratelimiter_budget.go:L161` | | `RedisConnector.Delete` | normal | `data/redis.go:L636` | | `RedisConnector.Get` | normal | `data/redis.go:L341` | | `RedisConnector.List` | normal | `data/redis.go:L682` | | `RedisConnector.Lock` | normal | `data/redis.go:L435` | | `RedisConnector.PublishCounterInt64` | normal | `data/redis.go:L558` | | `RedisConnector.Set` | normal | `data/redis.go:L281` | | `RedisConnector.Unlock` | normal | `data/redis.go:L612` | | `Request.GenerateCacheHash` | detail | `common/json_rpc.go:L1387` | | `Request.Handle` | direct | `common/tracing_util.go:L165` | | `Request.Lock` | detail | `common/request.go:L925` | | `Request.RLock` | detail | `common/request.go:L931` | | `Request.ResolveJsonRpc` | detail | `common/request.go:L939` | | `Response.IsObjectNull` | detail | `common/response.go:L420` | | `Response.Lock` | detail | `common/response.go:L84` | | `Response.RLock` | detail | `common/response.go:L90` | | `Response.ResolveJsonRpc` | detail | `common/response.go:L293` | | `Tap.Read` | detail | `indexer/taps.go:L107` | | `Upstream.Forward` | normal | `upstream/upstream.go:L416` | | `Upstream.PostForwardHook` | detail | `architecture/evm/hooks.go:L110` | | `Upstream.PostForwardHook.eth_getBlockByNumber` | detail | `architecture/evm/eth_getBlockByNumber.go:L435` | | `Upstream.PostForwardHook.eth_getBlockReceipts` | detail | `architecture/evm/eth_getBlockReceipts.go:L31` | | `Upstream.PostForwardHook.eth_getLogs` | detail | `architecture/evm/eth_getLogs.go:L350` | | `Upstream.PostForwardHook.eth_sendRawTransaction` | detail | `architecture/evm/eth_sendRawTransaction.go:L59` | | `Upstream.PostForwardHook.trace_filter` | detail | `architecture/evm/trace_filter.go:L362` | | `Upstream.PreForwardHook` | detail | `architecture/evm/hooks.go:L87` | | `Upstream.PreForwardHook.eth_chainId` | detail | `architecture/evm/eth_chainId.go:L124` | | `Upstream.PreForwardHook.eth_getLogs` | detail | `architecture/evm/eth_getLogs.go:L289` | | `Upstream.PreForwardHook.trace_filter` | detail | `architecture/evm/trace_filter.go:L298` | | `Upstream.tryForward.PreRequest` | detail | `upstream/upstream.go:L572` | | `Upstream.tryForward.SendRequest` | detail | `upstream/upstream.go:L630` | | `UpstreamsRegistry.GetNetworkUpstreams` | detail | `upstream/registry.go:L349` | | `UpstreamsRegistry.GetSortedUpstreams` | detail | `upstream/registry.go:L387` | | `UpstreamsRegistry.buildProviderBootstrapTask` | detail | `upstream/registry.go:L485` | | `UpstreamsRegistry.buildUpstreamBootstrapTask` | detail | `upstream/registry.go:L431` | | `createSyntheticSuccessResponse` | detail | `architecture/evm/eth_sendRawTransaction.go:L179` | | `extractTxHashFromSendRawTransaction` | detail | `architecture/evm/eth_sendRawTransaction.go:L136` | | `verifyAndHandleNonceTooLow` | detail | `architecture/evm/eth_sendRawTransaction.go:L206` | ### Source code entry points - [`common/tracing_core.go:L53-L170`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L53-L170) — `InitializeTracing`: exporter creation, sampler construction, propagator setup, `forceTraceSampler`, `IsTracingEnabled`/`IsTracingDetailed` globals - [`common/tracing_util.go:L1-L234`](https://github.com/erpc/erpc/blob/main/common/tracing_util.go#L1-L234) — `noopSpan` singleton, `StartSpan`/`StartDetailSpan` helpers, `StartHTTPServerSpan`, `StartRequestSpan`/`EndRequestSpan`, `InjectHTTPResponseTraceContext` - [`common/defaults.go:L618-L637`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L618-L637) — `TracingConfig.SetDefaults`: protocol, endpoint, sampleRate, serviceName - [`common/config.go:L218-L235`](https://github.com/erpc/erpc/blob/main/common/config.go#L218-L235) — `TracingConfig` struct definition - [`common/config.go:L397-L503`](https://github.com/erpc/erpc/blob/main/common/config.go#L397-L503) — `MarshalJSON`/`MarshalYAML` redaction overrides for secret-bearing config types - [`util/redact.go:L10-L36`](https://github.com/erpc/erpc/blob/main/util/redact.go#L10-L36) — `RedactEndpoint`: SHA-256-based URL sanitization with scheme-aware rules - [`cmd/erpc/main.go:L48-L66`](https://github.com/erpc/erpc/blob/main/cmd/erpc/main.go#L48-L66) — zerolog global setup: `TimeFieldFormat`, `ErrorMarshalFunc`, `LOG_WRITER` console mode, `LOG_LEVEL` env override - [`erpc/erpc.go:L31-L99`](https://github.com/erpc/erpc/blob/main/erpc/erpc.go#L31-L99) — calls `InitializeTracing` on startup, registers shutdown goroutine with 5-second grace period - [`erpc/http_server.go:L285-L288`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L285-L288) — network context for force-trace matcher evaluation - [`erpc/http_server.go:L701`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L701) — W3C traceparent injection into HTTP response headers - [`erpc/init.go:L27-L42`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L27-L42) — parses `cfg.LogLevel` into zerolog level; logs full redacted config at info level - [`common/console.go:L15-L29`](https://github.com/erpc/erpc/blob/main/common/console.go#L15-L29) — JS/TS `console.{debug,info,log,trace,warn}` → zerolog bridge (note: `console.error` is absent) - [`common/runtime.go:L39`](https://github.com/erpc/erpc/blob/main/common/runtime.go#L39) — installs `console` object into every Sobek runtime - [`cmd/erpc/initflags.go`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go) — `ERPC_NOLOGS=1` → zerolog.Disabled + io.Discard writer (build-tagged, non-test only) ### Related pages - [Metrics & Prometheus](/operation/metrics.llms.txt) — the Prometheus side of observability; no overlap with OTel spans. - [Admin API](/operation/admin.llms.txt) — runtime log-level changes via the admin endpoint. - [Health checks](/operation/health-check.llms.txt) — healthcheck requests bypass force-trace network matchers. - [Deployment](/deployment/docker.llms.txt) — how to wire an OTel collector sidecar alongside eRPC. --- --- # URL structure > Source: https://docs.erpc.cloud/operation/url > One URL pattern routes every chain — domain and network aliases let you publish clean, memorable endpoints without touching your app code. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # URL structure Every request reaches eRPC at `///`. Two aliasing layers let you shorten or domain-bind that path without touching your app: **domain aliasing** maps a wildcard `Host` header to any combination of project, network, and chain; **network aliasing** lets a name like `"arbitrum"` stand in for `evm/42161` anywhere in the path. Unknown projects or networks return clean JSON-RPC error envelopes, never silent failures. ## Quick taste Illustrative, not a tuned production config — map a dedicated domain to a single chain: **Config path:** `server.aliasing.rules` **YAML — `erpc.yaml`:** ```yaml server: aliasing: rules: # map a dedicated domain → single chain, no path segments needed - matchDomain: "eth.myservice.com" serveProject: "main" serveArchitecture: "evm" serveChain: "1" ``` **TypeScript — `erpc.ts`:** ```typescript server: { aliasing: { rules: [{ // map a dedicated domain → single chain, no path segments needed matchDomain: "eth.myservice.com", serveProject: "main", serveArchitecture: "evm", serveChain: "1", }], }, } ``` ## WebSocket You can also connect via WebSocket using the same URL path with a `ws://` or `wss://` scheme: ``` ws://localhost:4000/main/evm/1 ``` WebSocket connections support all JSON-RPC methods, batch requests, and real-time subscriptions (`eth_subscribe`). Read more in the [WebSocket](/operation/websocket.llms.txt) page. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up clean per-chain domains** ```text I want each of my EVM chains to have its own dedicated subdomain (e.g. eth.myservice.com, arb.myservice.com) so clients never need to include chain IDs in the URL path. Configure eRPC domain aliasing rules in my eRPC config. Read the full reference first: https://docs.erpc.cloud/operation/url.llms.txt ``` **Prompt Example #2: add human-readable network aliases** ```text Replace the raw evm/42161 and evm/8453 path segments in my eRPC setup with friendly aliases like "arbitrum" and "base" so my app can POST to /main/arbitrum instead of /main/evm/42161. Update my eRPC config and tell me how alias collisions are handled. Reference: https://docs.erpc.cloud/operation/url.llms.txt ``` **Prompt Example #3: debug a 400 on my healthcheck probe** ```text My load-balancer health probe is hitting GET /main/evm/1/healthcheck and getting HTTP 400 instead of 200. Explain why eRPC returns 400 for this URL shape and show me the correct probe path given my config in my eRPC config. Reference: https://docs.erpc.cloud/operation/url.llms.txt ``` **Prompt Example #4: route multi-chain SDK calls without URL changes** ```text My SDK sends all requests to the same endpoint but includes the target chain in the JSON-RPC body as "networkId":"evm:42161". Confirm my eRPC config is set up to accept project-level POST /main requests where the network comes from the body, and flag any footguns in the current alias config. Reference: https://docs.erpc.cloud/operation/url.llms.txt ``` --- ### URL structure — full agent reference ### How it works Routing happens in two phases. First, the server evaluates `server.aliasing.rules` against the stripped `Host` header (port removed). The first matching rule wins and pre-populates up to all three of `(projectId, architecture, chainId)`. Then `parseUrlPath` reads the remaining URL path segments and fills in any fields not yet set by domain aliasing. After path parsing, `common.IsValidArchitecture` validates the architecture string. `"evm"` and `"svm"` are both valid; any other value — including an empty string when chainId is present — returns HTTP 400. If `projectId` is still empty after all resolution, the request is also rejected with 400. **The third segment is not always a numeric chain id.** It is a generic identifier slot whose meaning depends on the architecture: for EVM it is the numeric chain id (`/main/evm/42161`), and for SVM it is the cluster — `/main/svm/mainnet-beta` for Solana, or `:` for a fork, e.g. `/main/svm/fogo:mainnet`. The colon inside a fork's identifier is carried intact in that one segment and reassembled as `svm:fogo:mainnet`. For POST requests where `architecture` and `chainId` are still unknown after the path, the server inspects the JSON-RPC body for a top-level `"networkId"` field — `"evm:42161"`, `"svm:mainnet-beta"`, or `"svm:fogo:mainnet"`. The split is `SplitN(networkId, ":", 2)`, so a fork's `chain:cluster` tail stays intact as the chainId component. This allows project-level requests (`POST /main`) to self-describe their network inline without a URL change. Any request whose HTTP method is neither POST nor OPTIONS has `isHealthCheck` forced to `true` after path parsing — meaning `GET /main/evm/1` silently becomes a network-scoped healthcheck rather than an error. Architecture validation still runs first; a GET to an invalid architecture path returns 400, not 200. **Domain alias wildcard matching.** `matchDomain` is evaluated with `common.WildcardMatch`, which uses Go `filepath.Match` semantics supporting `*` and `?`. The `Host` header has its port stripped before matching. Only the first matching rule applies; remaining rules are ignored. [Source: [`erpc/http_server.go:L234-256`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L234-L256)] **Network alias resolution.** Inside path parsing, whenever a single unresolved segment is being interpreted as architecture or chainId, the parser calls `project.networksRegistry.ResolveAlias(segment)`. If it matches, the stored `(architecture, chainId)` override the raw segment — enabling `POST /main/arbitrum` instead of `POST /main/evm/42161`. Aliases are registered eagerly at startup from all statically configured networks, and lazily when a network is first bootstrapped. [Source: [`erpc/http_server.go:L860-866`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L860-L866)] **Global `NetworkAlias` resolver.** A process-global atomic function pointer (`common.networkAliasResolver`) is installed at startup via `common.SetNetworkAliasResolver(f)`. `common.NetworkAlias(networkId)` calls the installed resolver and returns the alias if found, or the raw `networkId` unchanged. Components without project context (e.g., the gRPC cache connector) use this for consistent metric label emission. This is distinct from the per-project URL routing alias maps. [Source: [`common/network_alias.go:L10-34`](https://github.com/erpc/erpc/blob/main/common/network_alias.go#L10-L34)] **Full set of accepted proxy URL shapes after alias resolution:** | URL shape | Pre-populated by alias | Segments needed | |---|---|---| | `POST ///` | none | 3 — canonical form | | `POST //` | project | 2 | | `POST /` | project + arch | 1 | | `POST /` | project + arch + chain | 0 — single-chain dedicated domain | | `POST //` | none | 2 — alias resolved to arch+chain | | `POST /` | project | 1 — alias resolved | | `POST /` | none | 1 — arch+chain from body `networkId` | | `POST //` | none | 2 — chainId from body `networkId` | **Path parsing state machine.** `parseUrlPath` has six distinct cases keyed by which fields were pre-populated by domain aliasing. Before the case switch, the path is cleaned with `path.Clean` (collapsing double slashes, resolving `..` segments) and split on `/`. A trailing segment `"healthcheck"` or an empty root GET is always a healthcheck regardless of case. | Case | Pre-selected | Segment handling | |---|---|---| | 1 | none | 0→healthcheck; 1→projectId; 2→project+(alias or arch); 3→project+arch+chain; 4+→400 | | 2 | project | 0→healthcheck; 1→alias or arch; 2→arch+chain; 3→full override; 4+→400 | | 3 | project + arch | 0→healthcheck; 1→alias override or chainId; 2→400; 3→full override; 4+→400 | | 4 | all three | 0 or 1 (healthcheck suffix)→pass; anything else→400 | | 5 | arch + chain | 0→healthcheck; 1→projectId; 2→400; 3→full override; 4+→400 | | 6 | arch only | 0→healthcheck; 1→projectId; 2→project+chainId; 3→full override; 4+→400 | | default | project + chain, no arch | always 400 — impossible combination | Source: [[`erpc/http_server.go:L852-991`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L852-L991)] **Invalid and impossible path combinations** (after the case switch, post-switch checks at L993-L999 apply): | Condition | HTTP status | Error message | |---|---|---| | `projectId` still empty (not healthcheck) | 400 | `"project is required either in path or via domain aliasing"` | | Architecture fails `IsValidArchitecture` | 400 | `"architecture is not valid (must be 'evm')"` | | `projectId` + `chainId` pre-selected but no `architecture` (default case) | 400 | `"it is not possible to alias for project and chain WITHOUT architecture"` | | 4+ segments with no pre-selection | 400 | `"must only provide ///"` | **Healthcheck URL shapes.** The following GET (or any non-POST/non-OPTIONS) URL patterns reach healthcheck handlers — alias resolution and architecture validation still apply to the path segments: | URL shape | Scope | |---|---| | `GET /` | Global (all projects) | | `GET /healthcheck` | Global (all projects) | | `GET //healthcheck` | Per-project | | `GET ////healthcheck` | Per-network (explicit) | | `GET ///healthcheck` | Per-network (alias resolved) | | Aliased domain `GET /healthcheck` | Scope matches what alias pre-selects | | Aliased domain `GET /` | Same as above | Note: `GET /main/foo/healthcheck` where `foo` is neither a valid alias nor `"evm"` returns HTTP 400, not 200, because architecture validation runs before healthcheck dispatch. ### Config schema **Domain aliasing** — `server.aliasing.rules[]` (struct: [`common/config.go:L253-262`](https://github.com/erpc/erpc/blob/main/common/config.go#L253-L262)): | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `matchDomain` | `string` | required | Wildcard pattern matched against `Host` header after port strip. Supports `*` and `?` (Go `filepath.Match`). First matching rule wins; no merging. **Footgun:** a `"*"` wildcard before specific rules captures everything. Source: [`common/config.go:L258`](https://github.com/erpc/erpc/blob/main/common/config.go#L258) | | `serveProject` | `string` | `""` | Project ID pre-populated when rule matches. If empty, projectId must appear in path. Source: [`common/config.go:L259`](https://github.com/erpc/erpc/blob/main/common/config.go#L259) | | `serveArchitecture` | `string` | `""` | Architecture pre-populated (e.g. `"evm"`). If empty, must appear in path or be resolved from a network alias. Source: [`common/config.go:L260`](https://github.com/erpc/erpc/blob/main/common/config.go#L260) | | `serveChain` | `string` | `""` | Chain ID string pre-populated (e.g. `"1"`, `"42161"`). If empty, must appear in path. **Footgun:** setting `serveChain` without `serveArchitecture` is an impossible combination and always returns 400. Source: [`common/config.go:L261`](https://github.com/erpc/erpc/blob/main/common/config.go#L261) | **Network (path) aliasing** — `projects[].networks[].alias` (struct: [`common/config.go:L1995-2006`](https://github.com/erpc/erpc/blob/main/common/config.go#L1995-L2006)): | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `projects[].networks[].alias` | `string` | `""` (no alias) | Human-readable path alias for this network (e.g. `"arbitrum"`). Used in URL instead of raw `/`. Per-project; two projects can have the same alias string without conflict. **Footgun:** alias collision within a project drops the second registration silently with a WARN log — first registration wins. Also propagated to the process-global `NetworkAlias` resolver for metric-label consistency. Source: [`common/config.go:L2002`](https://github.com/erpc/erpc/blob/main/common/config.go#L2002), [`erpc/networks_registry.go:L67-79`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L67-L79) | Total config fields in scope: **5** ### Worked examples **1. Single-chain dedicated domain.** A product endpoint where every call is Ethereum mainnet — clients POST to `https://eth.myservice.com/` with no path beyond the root: **Config path:** `server.aliasing.rules` **YAML — `erpc.yaml`:** ```yaml server: aliasing: rules: - matchDomain: "eth.myservice.com" serveProject: "main" serveArchitecture: "evm" serveChain: "1" ``` **TypeScript — `erpc.ts`:** ```typescript server: { aliasing: { rules: [{ matchDomain: "eth.myservice.com", serveProject: "main", serveArchitecture: "evm", serveChain: "1", }], }, } ``` **2. Multi-chain domain with architecture pre-selected.** Pre-select only `serveArchitecture: "evm"` so clients can hit `POST /main/42161` or `POST /main/1` without the `evm` segment. Useful when all traffic is EVM but chains vary per request: **Config path:** `server.aliasing.rules` **YAML — `erpc.yaml`:** ```yaml server: aliasing: rules: - matchDomain: "rpc.myservice.com" serveProject: "main" serveArchitecture: "evm" ``` **TypeScript — `erpc.ts`:** ```typescript server: { aliasing: { rules: [{ matchDomain: "rpc.myservice.com", serveProject: "main", serveArchitecture: "evm", }], }, } ``` **3. Human-readable network alias in path.** Configure `alias: "arbitrum"` on the Arbitrum network so clients can POST to `/main/arbitrum` instead of `/main/evm/42161`. When two projects both define `alias: "mainnet"` they resolve independently — no cross-project conflict: **Config path:** `projects[].networks[].alias` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 42161 alias: arbitrum ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 42161 }, alias: "arbitrum", }], }] ``` **4. Body-level network routing (no network in URL).** For services that dynamically pick chains per call, send `POST /main` with `"networkId": "evm:42161"` in the JSON-RPC body. No URL change needed across chains — useful for SDK integrations where the network travels in the request payload: ```json POST /main Content-Type: application/json {"jsonrpc":"2.0","method":"eth_blockNumber","networkId":"evm:42161","id":1} ``` ### Request/response behavior - All proxy responses use a JSON-RPC envelope regardless of HTTP status code; 404s are never plain-text. - HTTP status codes are derived by `httpStatusCode(err)`: | HTTP status | Error codes | Condition | |---|---|---| | 400 | `ErrCodeInvalidUrlPath`, `ErrCodeJsonRpcRequestUnmarshal`, `ErrCodeInvalidRequest` | Invalid URL path, bad JSON, invalid architecture, impossible alias combination, corrupt gzip body | | 401 | `ErrCodeAuthUnauthorized`, `ErrCodeEndpointUnauthorized` | Auth failure at project or upstream level | | 404 | `ErrCodeProjectNotFound`, `ErrCodeNetworkNotFound`, `ErrCodeNetworkNotSupported` | Unknown `projectId`, unknown `networkId`, or unsupported network | | 429 | `ErrCodeAuthRateLimitRuleExceeded`, `ErrCodeProjectRateLimitRuleExceeded`, `ErrCodeNetworkRateLimitRuleExceeded`, `ErrCodeEndpointCapacityExceeded` | Rate limiter exceeded at any level | | 200 | (all other) | All other outcomes — including upstream errors, which return HTTP 200 with a JSON-RPC error body | [Source: [`erpc/http_server.go:L1285-1317`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1285-L1317)] - Non-POST/non-OPTIONS methods: `isHealthCheck` is forced `true` after path parsing; the client receives a healthcheck response with no indication the substitution occurred. [[`erpc/http_server.go:L1001-1003`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1001-L1003)] - Unknown project (`ErrProjectNotFound`): `s.erpc.GetProject(projectId)` returns HTTP 404 with a JSON-RPC envelope and message `"project is not configured"`. [Source: [`erpc/projects_registry.go:L118`](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go#L118)] - Networks are lazily initialized: `ErrNetworkNotFound` (HTTP 404) is returned only when the networkId format is valid but resolution definitively fails. A network that has never been requested may succeed on first call for provider-based projects. [Source: [`erpc/networks_registry.go:L221-232`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L221-L232)] - The request envelope is parsed once per request. `method`, `id`, `params`, and the body's `networkId` hint all come from that single parse, so the method erpc authenticates and rate-limits on is the method it sends upstream. [[`common/request.go:L887-921`](https://github.com/erpc/erpc/blob/main/common/request.go#L887-L921)] - `networkId` is routing input only and is never relayed: the upstream body is rebuilt from `jsonrpc`, `method`, `params`, and `id`. [[`clients/http_json_rpc_client.go:L702-707`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L702-L707)] - Batch detection fires on `body[0] == '['` — no Content-Type gate, no pre-parse. A body like `[invalid json` is detected as batch then fails unmarshalling with a 400. [[`erpc/http_server.go:L405-409`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L405-L409)] - Request gzip decompression is unconditional: `Content-Encoding: gzip` always triggers decompression regardless of the `server.enableGzip` setting (which controls response compression only). Corrupt gzip → 400 `ErrInvalidRequest` immediately. [[`erpc/http_server.go:L349-370`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L349-L370)] - `MaxHeaderBytes` is `1 MiB` on both IPv4 and IPv6 servers; requests with oversized headers are rejected at the Go net/http layer with HTTP 431 before any eRPC handler runs. Body size has no configured cap. [[`erpc/http_server.go:L186`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L186)] - gRPC dispatch (`Content-Type: application/grpc` + HTTP/2) happens before URL parsing — only when `grpcSharesHttpV4` is enabled; IPv6 never gets gRPC sharing. [[`erpc/http_server.go:L162-175`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L162-L175)] - Cleartext HTTP/2 (h2c) prior-knowledge connections are served on every non-TLS listener (IPv4 and IPv6) regardless of whether gRPC sharing is enabled: both servers set `http.Server.Protocols` to HTTP/1.1 + unencrypted HTTP/2. HTTP/1.1 `Upgrade: h2c` is not honored (the request is served over HTTP/1.1). With TLS, HTTP/2 is negotiated via ALPN instead. [[`erpc/http_server.go:L179-192`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L179-L192)] - The admin endpoint is exactly `POST /admin` or `OPTIONS /admin`; `GET /admin` is a healthcheck; `/admin/foo` fails with a URL parse error. [[`erpc/http_server.go:L836-838`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L836-L838)] ### Best practices - **Use `serveArchitecture: "evm"` without `serveChain`** on a project-scoped domain to drop `evm` from every URL (`POST /main/1` instead of `POST /main/evm/1`), saving clients a segment while preserving multi-chain flexibility. - **Order domain alias rules most-specific first.** The first matching rule wins and remaining rules are not evaluated. A catch-all `matchDomain: "*"` placed before specific rules silently captures every request — include it last only if intentional. - **Never set `serveChain` without `serveArchitecture`.** This combination is explicitly detected as impossible and returns 400. If you want to pre-select a chain, always pair it with `serveArchitecture: "evm"`. - **Assign unique aliases within a project.** Alias collision silently drops the second registration (only a WARN log is emitted). Verify at startup that each project's `alias` values are distinct. - **Apply body-size limits at the reverse proxy.** The 1 MiB limit is headers only; bodies are read into memory without a cap. Nginx/Envoy `client_max_body_size` prevents memory exhaustion from oversized requests. - **Test healthcheck paths with your alias setup.** `parseUrlPath` runs alias and architecture validation even on healthcheck requests — a `GET /main/foo/healthcheck` where `foo` is neither a valid alias nor `"evm"` returns 400, not 200, which can break load-balancer probes. ### Edge cases & gotchas 1. **Domain aliasing matches the `Host` header after port stripping.** If an ingress forwards `Host: api.example.com:443`, the colon and port are stripped before matching. A rule `matchDomain: "api.example.com"` works regardless of the port in the `Host` header. Source: [`erpc/http_server.go:L234-237`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L234-L237) 2. **`GET /main/evm/1` is a healthcheck, not a proxy request.** Any non-POST/non-OPTIONS method forces `isHealthCheck=true` after path parsing. The response gives no indication this substitution occurred. This is intentional for load-balancer probes. Source: [`erpc/http_server.go:L1001-1003`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1001-L1003) 3. **`serveProject` + `serveChain` without `serveArchitecture` always errors.** The combination is detected as an impossible alias and returns 400 immediately. Source: [`erpc/http_server.go:L985-988`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L985-L988) 4. **First domain alias rule wins; no merging.** Order rules from most-specific to least-specific. A `matchDomain: "*"` before specific rules captures everything. Source: [`erpc/http_server.go:L244-256`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L244-L256) 5. **Network aliases are per-project, not global.** The alias map is stored per `NetworksRegistry` per `PreparedProject`. Source: [`erpc/networks_registry.go:L31`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L31) 6. **Alias collision: first-registration wins, silently for callers.** If a provider dynamically creates a network whose alias matches a statically configured one, the static alias wins. The dynamic registration is dropped with a WARN log but no error is returned. Source: [`erpc/networks_registry.go:L340-344`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L340-L344) 7. **Alias resolution only in specific path positions.** In a fully-explicit 3-segment path (`/project/evm/42161`), no alias resolution is attempted — an alias named `"evm"` would NOT intercept the architecture position. Source: [`erpc/http_server.go:L860-866`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L860-L866) 8. **Body `networkId` requires valid JSON.** If the body is not valid JSON when `architecture` is still empty, a JSON-RPC parse error is returned. This only applies to proxy requests; healthcheck does not read the body. Source: [`erpc/http_server.go:L617-622`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L617-L622) 9. **Healthcheck paths pass through architecture validation.** `GET /main/foo/healthcheck` where `foo` is not a known alias and not `"evm"` returns HTTP 400, not 200. Source: [`erpc/http_server.go:L997-999`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L997-L999) 10. **`path.Clean` normalizes unusual paths.** `/main//evm/1` becomes `/main/evm/1`; `/main/../other/evm/1` resolves to `/other/evm/1`. Source: [`erpc/http_server.go:L821`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L821) 11. **Batch detection has no Content-Type gate.** A body starting with `[` is treated as batch even if `Content-Type: text/plain` or omitted entirely. A malformed batch like `[invalid json` is detected as batch and then fails unmarshal with a 400. Source: [`erpc/http_server.go:L405-414`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L405-L414) 12. **`server.enableGzip` controls response compression only.** Request decompression is unconditional. Operators cannot disable inbound gzip decompression via config. Source: [`erpc/http_server.go:L349-370`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L349-L370) 13. **Body size has no configured cap.** The 1 MiB limit is headers only. Arbitrarily large bodies are read into memory. Apply body-size limits at the reverse-proxy layer. Source: [`erpc/http_server.go:L186`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L186), [`erpc/http_server.go:L374`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L374) 14. **Unknown network may succeed on first call for provider-based projects.** Networks are lazily initialized. `ErrNetworkNotFound` (HTTP 404) is returned only when resolution definitively fails. Source: [`erpc/networks_registry.go:L221-232`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L221-L232) 15. **`serveArchitecture: "evm"` with no `serveChain` lets callers omit `evm` from the path.** With a domain alias pre-selecting architecture, the URL becomes `POST //` — no need to include `evm` in every call. Source: [`erpc/http_server.go:L963-983`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L963-L983) 16. **gRPC sharing is IPv4-only.** The `Content-Type: application/grpc` + HTTP/2 dispatch happens before URL parsing only on IPv4. IPv6 never gets a shared gRPC handler. Source: [`erpc/http_server.go:L162-175`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L162-L175) 17. **Cleartext HTTP/2 (h2c) is prior-knowledge only.** Without TLS, both the IPv4 and IPv6 listeners accept HTTP/2 prior-knowledge connections natively, independent of gRPC. An HTTP/1.1 `Upgrade: h2c` request is answered over HTTP/1.1, so clients that rely on the upgrade dance stay on HTTP/1.1. Source: [`erpc/http_server.go:L179-192`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L179-L192) 18. **A request object that states `method` more than once is rejected.** JSON decoders do not agree on which occurrence wins, so erpc reads none of them and returns 400 `ErrCodeInvalidRequest` (JSON-RPC `-32700`, the same shape as any unparseable body) before auth, rate limiting, and routing. This covers a repeated key, an escaped spelling (`"\u006dethod"`), and a case variant (`"Method"`) that Go's case-insensitive field matching folds onto the same field. A `"method"` key nested inside `params` or any other member is untouched. Source: [`common/json_rpc.go:L1253-1284`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1253-L1284) 19. **An `id` that is not a string, a number, or `null` is an Invalid Request.** JSON-RPC 2.0 §4 allows only those id types (or no `id` member: a notification). A `true`/`false`, object, or array `id` is answered with JSON-RPC `-32600` and `"id": null` before routing, so no upstream is asked and no retry or hedge runs. The rule is the same for every architecture and for HTTP, WebSocket, and gRPC, since all of them run `NormalizedRequest.Validate`. HTTP status follows `ErrInvalidRequest`: 400, or 200 on SVM networks. In a batch only the offending item gets the error; the other items are served. Every number form accepted before is still accepted. Source: [`common/json_rpc.go:L1482-1496`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1482-L1496), [`common/request.go:L1293-1309`](https://github.com/erpc/erpc/blob/main/common/request.go#L1293-L1309) 20. **A numeric `id` must be an integer in the int64 or u64 range.** An integer above the int64 maximum, up to `18446744073709551615`, is accepted: the upstream sees a random int64 id and the client gets its own id bytes back. A fraction, an exponent form, or an integer outside both ranges fails the parse (`-32700`, 400). Source: [`common/json_rpc.go:L1503-1525`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1503-L1525) 21. **On an SVM network a negative integer `id` is answered locally.** A Solana node reads an id as `null`, a u64, or a string, so it answers a negative id with `-32700` "Parse error" and `"id": null` whatever the method. eRPC gives that same reply (HTTP 200) in the project pre-forward hook, so no upstream is asked and no retry or hedge runs. A Solana node parses a batch as one value, so a batch with one such id gets that single reply (not an array) and none of its elements runs. An empty batch `[]` gets HTTP 200 with an empty body. EVM networks still forward negative ids and answer each batch element, and `[]` with `[]`, since EVM nodes do. Source: [`architecture/svm/hooks.go:L140-190`](https://github.com/erpc/erpc/blob/main/architecture/svm/hooks.go#L140-L190) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cors_requests_total` | counter | project, origin | Every request carrying an `Origin` header | | `erpc_cors_preflight_requests_total` | counter | project, origin | OPTIONS preflight from an allowed origin | | `erpc_cors_disallowed_origin_total` | counter | project, origin | Request from an origin not in the allowlist | **Tracing.** All requests share an `Http.ReceivedRequest` OTel span with `http.method`, `http.url`, `http.scheme`, `http.user_agent` attributes. After routing, `common.SetForceTraceNetwork(ctx, architecture+":"+chainId)` injects the network into the span context. [Source: [`erpc/http_server.go:L285-288`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L285-L288)] **Log messages.** - `"received http request"` — INFO with `body` JSON field for non-empty bodies - `"received http request with empty body"` — INFO for empty-body requests - `"failed to match aliasing rule"` — ERROR if `WildcardMatch` returns an error for a domain alias rule - `"registered network alias"` — DEBUG on alias registration - `"skipping duplicate alias registration with different target"` — WARN on alias collision ### Source code entry points - [`erpc/http_server.go:L226-L292`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L226-L292) — domain alias evaluation in `handleRequest`; `Host` header stripping; routing dispatch - [`erpc/http_server.go:L810-L1006`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L810-L1006) — `parseUrlPath`: full path parsing state machine (all 6 cases), alias resolution, healthcheck/admin detection, validation - [`erpc/http_server.go:L671-L689`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L671-L689) — `networkId` fallback from request body - [`common/request.go:L887-L921`](https://github.com/erpc/erpc/blob/main/common/request.go#L887-L921) — `resolveJsonRpc`: the one body parse every consumer reads - [`common/json_rpc.go:L1245-L1266`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1245-L1266) — `uniqueString`: rejects a member stated more than once - [`erpc/http_server.go:L1285-L1317`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1285-L1317) — `httpStatusCode(err)`: full HTTP status code mapping (400/401/404/429/200) - [`erpc/networks_registry.go:L22-L81`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L22-L81) — `NetworksRegistry` struct + `NewNetworksRegistry` (eager alias registration from static config) - [`erpc/networks_registry.go:L247-L255`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L247-L255) — `ResolveAlias`: alias lookup under read lock - [`erpc/networks_registry.go:L322-L348`](https://github.com/erpc/erpc/blob/main/erpc/networks_registry.go#L322-L348) — `registerAlias`: lazy registration + collision guard - [`common/config.go:L253-L262`](https://github.com/erpc/erpc/blob/main/common/config.go#L253-L262) — `AliasingConfig`, `AliasingRuleConfig` fields - [`common/config.go:L1995-L2006`](https://github.com/erpc/erpc/blob/main/common/config.go#L1995-L2006) — `NetworkConfig.Alias` field - [`common/network_alias.go:L10-L34`](https://github.com/erpc/erpc/blob/main/common/network_alias.go#L10-L34) — process-global `NetworkAlias` resolver (cross-component metric-label consistency) - [`common/network.go:L35-L37`](https://github.com/erpc/erpc/blob/main/common/network.go#L35-L37) — `IsValidArchitecture` (currently only `"evm"`) - [`erpc/http_server_test.go:L3378-L3709`](https://github.com/erpc/erpc/blob/main/erpc/http_server_test.go#L3378-L3709) — `TestHttpServer_ParseUrlPath`: 30+ cases covering all alias combinations, network alias resolution, invalid architectures, healthcheck suffix placement - [`erpc/projects_registry.go:L118`](https://github.com/erpc/erpc/blob/main/erpc/projects_registry.go#L118) — `ErrProjectNotFound` returned by `GetProject` on unknown projectId ### Related pages - [Auth](/config/auth.llms.txt) — auth failure produces the 401 this page's error table maps. - [Rate limiters](/config/rate-limiters.llms.txt) — rate limit exceeded produces the 429 this page's error table maps. - [Projects](/config/projects.llms.txt) — where `networks[].alias` is configured. - [Deployment](/deployment.llms.txt) — reverse-proxy body-size limits recommended in best practices. --- --- # WebSocket > Source: https://docs.erpc.cloud/operation/websocket > WebSocket support in eRPC for persistent connections and real-time subscriptions > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # 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:///// ``` ```javascript // 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" } }; ``` > **INFO** > 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: ```javascript // 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: ```javascript 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 ```javascript 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. ```javascript ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_subscribe", params: [ "logs", { address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC topics: [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" // Transfer ] } ] })); ``` ### eth_unsubscribe ```javascript 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](#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`](/config/projects/networks.llms.txt#failover) 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. ```javascript 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](/config/failsafe/integrity.llms.txt) 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: | Transport | On a reorg | |---|---| | ws `newHeads` | each head of the new branch, oldest first | | ws `logs` | the sent logs of the dropped blocks with `"removed": true`, newest first; then the logs of the new branch | | gRPC `StreamBlocks` | resends 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.** | Transport | Slow or stalled | Out of range | |---|---|---| | ws `newHeads` | next block waited more than `reorgWindow` × block time: restart after the confirmed head | restart after the confirmed head | | ws `logs` | next block waited more than `reorgWindow` × block time, a reorg that reverts more than `reorgWindow` sent blocks, or 60s on one block's receipts: close `1013` | close `1013`; closes from one event spread over 60s | | ws `newPendingTransactions` | skips to the newest | — | | gRPC `StreamBlocks` | 60s of stalled read, or one `Send` over 10s: `UNAVAILABLE` | `OUT_OF_RANGE` | Every out-of-range or lagging end counts in `erpc_tap_end_total{reason,detail}`. **Failure model.** | Failure | Recovery | Bound | |---|---|---| | wss socket drops | reconnect with jittered 1–30s backoff; other voters carry; the tracker links the missed blocks | 30s | | wss socket alive, `newHeads` silent | its vote ages out; the socket reconnects | 30s past the last push | | upstream lags | benched after `max(30s, 3 × cadence)` | 90s | | one upstream ahead, peers stalled | subscribers wait until the peers are benched, then get the held blocks in batches | 90s | | upstream on a minority fork | loses its vote, goes last in routing | about 60s | | voters disagree | the branch with the most votes; a tie asks non-voting upstreams to settle | 1 settle | | one block's receipts not served | other upstreams, then `eth_getLogs`; then `logs` connections close `1013` | 60s | | chain makes no blocks | nothing reconnects or resubscribes | — | ## gRPC StreamBlocks With [`server.grpcEnabled`](/config/server.llms.txt), the `StreamService.StreamBlocks` RPC ([`evm/stream.proto`](https://github.com/blockchain-data-standards/manifesto)) 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. | Request | Stream starts | |---|---| | neither set | after the confirmed head | | both set, cursor on the canonical chain | at `fromBlock + 1`, replaying every block up to the confirmed head | | both set, cursor on a dropped branch | at the fork point + 1 | | both set, cursor older than `chainTracker.maxBackfill` or a hash no upstream serves | ends with `OUT_OF_RANGE` | | only one set | `INVALID_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.** | Code | Cause | Client action | |---|---|---| | `UNAVAILABLE` | 60s with no block while the confirmed head stands above the cursor, or one `Send` blocked for 10s | reconnect with the last applied cursor | | `OUT_OF_RANGE` | the cursor left the window, or no upstream serves it | backfill with unary calls, then reopen | | `INVALID_ARGUMENT` | only one of `fromBlock`, `fromHash`, or a `fromHash` not 32 bytes | fix 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: **yaml:** ```yaml filename="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 ``` **typescript:** ```ts filename="erpc.ts" export default createConfig({ projects: [ { id: "main", upstreams: [ // Regular HTTP upstream { 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" }, }, }, ], }, ], }); ``` > **INFO** > 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. ```yaml filename="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 (`///`, or a path that [domain aliasing](/operation/url.llms.txt) 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](/operation/directives.llms.txt) (`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: `, `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](/reference/evm/block-tracking.llms.txt). 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](/operation/directives.llms.txt) 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: ```javascript // 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. --- # Examples > Source: https://docs.erpc.cloud/presets > Drop-in eRPC config presets for specific scenarios (DVN, indexer, frontend, etc.). > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Examples Drop-in eRPC config examples for specific scenarios. Each example is a minimal, self-hosted starting point you can adapt to your chains and providers. - [DVN (LayerZero)](/presets/dvn-ready.llms.txt) — multi-provider consensus profile for DVN operators and any verifier service that can't trust a single RPC stack. ## Agent reference **Prompt Example #1: start from a preset and adapt it to my stack** ```text I want to start my eRPC setup from one of the official presets and adapt it to my chains and providers. List the available presets, pick the closest one for my use case, and walk me through customizing it into my eRPC config. Reference: https://docs.erpc.cloud/presets.llms.txt ``` --- # DVN-ready preset (LayerZero) > Source: https://docs.erpc.cloud/presets/dvn-ready > A drop-in eRPC config for DVN operators — unanimous consensus on the four source-chain verification methods closes the forged-log attack vector that hit KelpDAO. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # DVN-ready preset (LayerZero) Running a Decentralized Verifier Network means trusting on-chain state to validate cross-chain messages. A single compromised RPC provider can forge log responses — the KelpDAO attack vector. This preset closes that door: unanimous consensus across three independent providers, misbehavior logging to disk, and hedged retries for everything else. Drop this config in, swap the three endpoint env-vars, and you're protected. **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml logLevel: warn projects: - id: dvn networks: - architecture: evm evm: chainId: 1 # Ethereum mainnet — repeat this block per chain you verify failsafe: # 1. Unanimous consensus on the four methods DVN verification depends on. - matchMethod: "eth_getLogs|eth_getBlockByNumber|eth_getTransactionReceipt|eth_getBlockReceipts" timeout: duration: 10s retry: maxAttempts: 3 consensus: maxParticipants: 3 agreementThreshold: 3 # Unanimous — security over availability. disputeBehavior: returnError # Never accept a disputed read. lowParticipantsBehavior: returnError preferNonEmpty: true # Reject [] if any peer returned real data. preferLargerResponses: true # Reject truncated logs if a larger valid set exists. ignoreFields: eth_getLogs: - "*.blockTimestamp" eth_getTransactionReceipt: - "blockTimestamp" - "logs.*.blockTimestamp" - "l1Fee" - "l1GasPrice" - "l1GasUsed" eth_getBlockByNumber: - "transactions.*.gasPrice" - "transactions.*.l1Fee" - "transactions.*.yParity" punishMisbehavior: disputeThreshold: 3 disputeWindow: 10m sitOutPenalty: 30m misbehaviorsDestination: type: file path: /var/log/erpc/dvn-misbehaviors filePattern: "{dateByDay}-{networkId}-{method}" # 2. Default policy for everything else: hedged reads with retries. - matchMethod: "*" timeout: duration: 10s retry: maxAttempts: 3 hedge: delay: 500ms maxCount: 1 upstreams: # Three independent providers minimum. Add more for stronger guarantees. - id: provider-a endpoint: \${PROVIDER_A_ENDPOINT} - id: provider-b endpoint: \${PROVIDER_B_ENDPOINT} - id: provider-c endpoint: \${PROVIDER_C_ENDPOINT} # - id: self-hosted # endpoint: http://your-eth-node:8545 ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ logLevel: "warn", projects: [{ id: "dvn", networks: [ { architecture: "evm", evm: { chainId: 1 }, // Ethereum mainnet — repeat per chain you verify failsafe: [ { // 1. Unanimous consensus on the four methods DVN verification depends on. matchMethod: "eth_getLogs|eth_getBlockByNumber|eth_getTransactionReceipt|eth_getBlockReceipts", timeout: { duration: "10s" }, retry: { maxAttempts: 3 }, consensus: { maxParticipants: 3, agreementThreshold: 3, // Unanimous — security over availability. disputeBehavior: "returnError", // Never accept a disputed read. lowParticipantsBehavior: "returnError", preferNonEmpty: true, // Reject [] if any peer returned real data. preferLargerResponses: true, // Reject truncated logs. ignoreFields: { eth_getLogs: ["*.blockTimestamp"], eth_getTransactionReceipt: [ "blockTimestamp", "logs.*.blockTimestamp", "l1Fee", "l1GasPrice", "l1GasUsed", ], eth_getBlockByNumber: [ "transactions.*.gasPrice", "transactions.*.l1Fee", "transactions.*.yParity", ], }, punishMisbehavior: { disputeThreshold: 3, disputeWindow: "10m", sitOutPenalty: "30m", }, misbehaviorsDestination: { type: "file", path: "/var/log/erpc/dvn-misbehaviors", filePattern: "{dateByDay}-{networkId}-{method}", }, }, }, { // 2. Default policy for everything else. matchMethod: "*", timeout: { duration: "10s" }, retry: { maxAttempts: 3 }, hedge: { delay: "500ms", maxCount: 1 }, }, ], }, ], upstreams: [ // Three independent providers minimum. { id: "provider-a", endpoint: process.env.PROVIDER_A_ENDPOINT! }, { id: "provider-b", endpoint: process.env.PROVIDER_B_ENDPOINT! }, { id: "provider-c", endpoint: process.env.PROVIDER_C_ENDPOINT! }, // { id: "self-hosted", endpoint: "http://your-eth-node:8545" }, ], }], }); ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: deploy the DVN-ready preset for my LayerZero verifier** ```text I run a LayerZero DVN and need eRPC configured with unanimous consensus on the four source-chain verification methods (eth_getLogs, eth_getBlockByNumber, eth_getTransactionReceipt, eth_getBlockReceipts) to close the forged-log attack vector. Drop the DVN-ready preset into my eRPC config, swap in my three provider endpoint env-vars, and explain why agreementThreshold must equal maxParticipants. Read the reference first: https://docs.erpc.cloud/presets/dvn-ready.llms.txt ``` **Prompt Example #2: extend the preset to cover multiple chains** ```text I need the DVN-ready consensus policy applied to Ethereum mainnet, Arbitrum One, and Base in a single eRPC config. Show me how to use YAML anchors to avoid repeating the failsafe block, and what ignoreFields entries I need to add for L2-specific fields on Arbitrum and Base to avoid benign disputes. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/presets/dvn-ready.llms.txt ``` **Prompt Example #3: configure S3 misbehavior export for a multi-instance deployment** ```text I'm running multiple eRPC DVN instances and need all consensus dispute records centralized in S3 so I have a single audit trail. Configure misbehaviorsDestination with type: s3, show the correct filePattern to avoid object overwrites across concurrent instances, and explain the IAM minimum permissions needed. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/presets/dvn-ready.llms.txt ``` **Prompt Example #4: alert on provider misbehavior and audit my dispute settings** ```text I want to set up alerting when a provider starts diverging from consensus on my DVN verification path, and audit whether my punishMisbehavior thresholds are appropriate for production traffic. Check my eRPC config for missing required fields (disputeThreshold, disputeWindow) and tell me which Prometheus metric to alert on and what spike patterns to watch for. Reference: https://docs.erpc.cloud/presets/dvn-ready.llms.txt ``` --- ### DVN-ready preset — full agent reference ### How it works DVN operators (LayerZero and comparable off-chain verifiers) read source-chain state to prove a cross-chain message was genuinely emitted. The four critical methods are: - **`eth_getLogs`** — retrieves `PacketSent` (or equivalent) events proving a message was emitted. The KelpDAO attack forged this exact response. **This is the kill shot — get consensus right here above all.** - **`eth_getBlockByNumber`** — confirms block finality and confirmation depth before accepting a message. - **`eth_getTransactionReceipt`** — confirms the originating transaction was actually included in a block. - **`eth_getBlockReceipts`** — used for batch verification of message inclusion. State-read methods like `eth_call` and `eth_getBalance` are not part of typical DVN verification paths and are left under the default (hedged) policy to keep latency reasonable. **Why `agreementThreshold: 3` (unanimous).** A 2-of-3 quorum can still be poisoned if two providers share infrastructure or are both compromised via a common dependency (same cloud region, same indexing stack). Unanimity means an attacker must corrupt every provider simultaneously. Per KB14: `lowParticipantsBehavior` fires when `validParticipants < agreementThreshold` (not enough upstreams responded); `disputeBehavior` fires when enough upstreams responded but disagree (no group meets threshold). Setting both to `returnError` means any degraded state surfaces immediately rather than silently picking a winner. Consensus sits in `networkExecutor.Run` — when `ConsensusPolicyConfig` is present and `SkipConsensus` is false, the executor calls `consensus.Run(ctx, req, slotInner)` where `slotInner` is `retry(hedge(tryOneUpstream))`. [[`erpc/network_executor.go:L183-188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L183-L188)] ### Config schema Fields used in this preset. For the complete consensus schema see [Consensus](/config/failsafe/consensus.llms.txt). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `consensus.maxParticipants` | int | `5` | Number of upstreams to fan out to. This preset sets `3`. Must be `<= len(upstreams)` or `lowParticipantsBehavior` fires on every request. Source: [`common/defaults.go:L2390-2392`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2390-L2392) | | `consensus.agreementThreshold` | int | `2` | Minimum agreeing participants. Set to `maxParticipants` for unanimity. Source: [`common/defaults.go:L2393-2395`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2393-L2395) | | `consensus.disputeBehavior` | string | `"returnError"` | Action when participants disagree above threshold. Values: `returnError`, `acceptMostCommonValidResult`, `preferBlockHeadLeader`, `onlyBlockHeadLeader`. Source: [`common/defaults.go:L2396-2398`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2396-L2398) | | `consensus.lowParticipantsBehavior` | string | `"acceptMostCommonValidResult"` | Action when fewer upstreams respond than `agreementThreshold`. Source: [`common/defaults.go:L2399-2401`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2399-L2401) | | `consensus.preferNonEmpty` | \*bool | `true` | Prefer non-empty over empty/error winner even when empty group meets threshold. Source: [`common/defaults.go:L2420-2422`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2420-L2422) | | `consensus.preferLargerResponses` | \*bool | `true` | Prefer larger response body. **Disables all short-circuit** — every request waits for all participants. Source: [`common/defaults.go:L2423-2425`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2423-L2425) | | `consensus.ignoreFields` | map\[string\]\[\]string | Built-in per-method defaults | **Set replacement, not merge.** Adding any entry removes the entire default map. Source: [`common/defaults.go:L2405-2419`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2405-L2419) | | `consensus.punishMisbehavior.disputeThreshold` | uint | **Required** | Disputes allowed per window before punishment. Must be `> 0`; omitting is a startup error. Source: [`common/validation.go:L1172-1173`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1172-L1173) | | `consensus.punishMisbehavior.disputeWindow` | Duration | **Required** | Token-bucket window. Must be `> 0`. Source: [`common/validation.go:L1175-1176`](https://github.com/erpc/erpc/blob/main/common/validation.go#L1175-L1176) | | `consensus.punishMisbehavior.sitOutPenalty` | Duration | — | How long to cordon a misbehaving upstream. | | `misbehaviorsDestination.type` | string | `"file"` | `"file"` or `"s3"`. Source: [`common/defaults.go:L2460-2462`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2460-L2462) | | `misbehaviorsDestination.path` | string | — | Absolute directory path (file) or `s3://bucket/prefix/` (S3). Relative path is a startup error for file type. | | `misbehaviorsDestination.filePattern` | string | `"{timestampMs}-{instanceId}-{method}-{networkId}"` | Supports `{dateByHour}`, `{dateByDay}`, `{method}`, `{networkId}`, `{instanceId}`, `{timestampMs}`. `.jsonl` appended automatically. Source: [`common/defaults.go:L3184-3188`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L3184-L3188) | | `misbehaviorsDestination.s3.credentials.accessKeyID` | string | — | **YAML key is `accessKeyID` (capital D).** Using `accessKeyId` silently falls back to the SDK default chain. Source: [`common/config.go:L483`](https://github.com/erpc/erpc/blob/main/common/config.go#L483) | ### Worked examples **1. Multi-chain DVN (Ethereum + Arbitrum + Base).** Repeat the `networks[]` entry for every chain you verify — only `chainId` changes. Use a YAML anchor to avoid duplication: ```yaml networks: - architecture: evm evm: { chainId: 1 } # Ethereum mainnet failsafe: &dvn-failsafe # YAML anchor for reuse - matchMethod: "eth_getLogs|eth_getBlockByNumber|eth_getTransactionReceipt|eth_getBlockReceipts" # ... (full consensus block as above) - matchMethod: "*" # ... (default hedge block) - architecture: evm evm: { chainId: 42161 } # Arbitrum One failsafe: *dvn-failsafe # reuse the same policy - architecture: evm evm: { chainId: 8453 } # Base failsafe: *dvn-failsafe ``` For L2s, extend `ignoreFields` with chain-specific extras (deposit receipt fields, L2 fee fields) — and include all the base defaults, since `ignoreFields` is set-replacement not merge. **2. Centralized audit with S3 export.** For multi-instance deployments where you need a single audit trail, switch `misbehaviorsDestination` to S3. Use `{instanceId}` in the pattern so concurrent instances don't overwrite each other: ```yaml misbehaviorsDestination: type: s3 path: s3://my-bucket/erpc-dvn-disputes filePattern: "{dateByHour}/{networkId}/{method}-{instanceId}" s3: region: us-east-1 maxRecords: 100 maxSize: 1048576 # 1 MiB flushInterval: 60s credentials: mode: env # reads AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY ``` IAM minimum: `s3:PutObject` on the target prefix. The S3 exporter validates bucket access at startup via `HeadBucket`; if unreachable, export is disabled and consensus continues — check startup logs. Source: [`consensus/policy.go:L155-168`](https://github.com/erpc/erpc/blob/main/consensus/policy.go#L155-L168) **3. Relaxed punish settings for DeFi correctness checks (non-DVN).** The preset uses DVN-grade values. For DeFi apps that want correctness without the strict availability penalty, soften the punishment window and increase the threshold: ```yaml punishMisbehavior: disputeThreshold: 10 disputeWindow: 10m sitOutPenalty: 15m ``` **4. Mixing provider types for independence.** The three upstreams should come from different infrastructure stacks. Use the shorthand provider form (KB09) or explicit HTTPS URLs: ```yaml upstreams: - id: alchemy-eth endpoint: ${ALCHEMY_ETH_ENDPOINT} # managed, broad chain support - id: drpc-eth endpoint: ${DRPC_ETH_ENDPOINT} # different infrastructure stack - id: self-hosted endpoint: http://your-eth-node:8545 # you control it; strongest trust guarantee ``` Each upstream applies to all networks in the project — no separate entries per chain are needed. ### Request/response behavior - A consensus dispute on a verification method returns `ErrConsensusDispute` (JSON-RPC code `-32603`, HTTP `200`). The caller receives a structured error; it does NOT silently accept a forged response. [[`common/errors.go:L2559-2588`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2559-L2588)] - `lowParticipantsBehavior: returnError` produces `ErrConsensusLowParticipants` (JSON-RPC `-32603`, HTTP `200`). This fires when fewer upstreams responded than `agreementThreshold` — not the same as a dispute. [[`common/errors.go:L2593-2626`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2593-L2626)] - `preferLargerResponses: true` disables all short-circuit — every consensus request waits for all `maxParticipants` responses (or `maxWaitOnResult`/`maxWaitOnEmpty` caps). This increases latency but prevents a fast truncated-log response from winning. [[`consensus/rules.go:L913-915`](https://github.com/erpc/erpc/blob/main/consensus/rules.go#L913-L915)] - Any request can bypass consensus via `X-ERPC-Skip-Consensus: true` header, `?skip-consensus=true` query param, or `directiveDefaults.skipConsensus: true` in config. Only the literal string `"true"` activates bypass. [[`common/request.go:L746-747`](https://github.com/erpc/erpc/blob/main/common/request.go#L746-L747)] - `ignoreFields` comparison uses `CanonicalHashWithIgnoredFields` — dot-path wildcard segments (`*`) match any key at that depth. [[`consensus/analysis.go:L442-453`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L442-L453)] - `punishMisbehavior` requires a clear majority (`consensusGroup.Count > validParticipants / 2`) before cordoning. [[`consensus/executor.go:L1196`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L1196)] ### Best practices - **Mix provider infrastructure categories.** Use at least one managed RPC provider (Alchemy, Infura, QuickNode, dRPC) and one alternative from a different stack (Ankr, Chainstack, PublicNode). A self-hosted full node provides the strongest trust guarantee if you can maintain it. - **Never pick three providers from the same cloud region.** A zonal incident causes all three to agree on stale state or all go down simultaneously, triggering `lowParticipantsBehavior: returnError` on every request. Geo-distribute or mix cloud providers. - **Always include the base `ignoreFields` defaults when extending.** `ignoreFields` is set-replacement — adding `eth_getBlockByNumber` entries without copying `eth_getLogs`, `eth_getTransactionReceipt`, `eth_getBlockReceipts` silently removes timestamp-ignore for those methods, causing constant spurious disputes. Source: [`common/defaults.go:L2405-2419`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2405-L2419) - **Extend `ignoreFields` for L2s.** Running the Ethereum `ignoreFields` set on Arbitrum or Base without adding chain-specific extras (deposit receipt fields, Arbitrum-specific fields, Optimism extras) causes constant benign disputes. - **Do not apply `disputeBehavior: returnError` to the default (`matchMethod: "*"`) policy.** Methods like `eth_gasPrice` or `eth_estimateGas` legitimately differ between nodes — surfacing those as errors would break non-DVN callers. - **Alert on `erpc_consensus_misbehavior_detected_total`.** A sudden spike means a provider is diverging from consensus on a live verification path. This is your primary DVN health signal. - **Both `punishMisbehavior.disputeThreshold` and `disputeWindow` are required.** Omitting either when the `punishMisbehavior` block is present is a startup validation error, not a silent default. ### Edge cases & gotchas 1. **`ignoreFields` is set-replacement.** Setting any entry removes the built-in defaults for `eth_getLogs`, `eth_getTransactionReceipt`, `eth_getBlockReceipts`. Always include all entries you want to keep. Source: [`common/defaults.go:L2405-2419`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2405-L2419). 2. **`maxParticipants` must not exceed available healthy upstreams.** If `maxParticipants: 3` but only 2 upstreams are healthy, every request triggers `lowParticipantsBehavior: returnError`. Always ensure `len(upstreams) >= maxParticipants`. 3. **`preferLargerResponses: true` increases latency for all consensus requests.** It disables short-circuit so every request waits for all `maxParticipants` responses (or `maxWaitOnResult`/`maxWaitOnEmpty` caps). Consider disabling in low-latency scenarios. 4. **`disputeBehavior: returnError` must not be applied to the default (`matchMethod: "*"`) policy** unless you want disputes on `eth_gasPrice` or `eth_estimateGas` to surface as errors to callers. Keep it only on the verification methods. 5. **Three providers in the same cloud region fail together.** A zonal incident causes all three to agree on stale state or all three to go down simultaneously. Geo-distribute and mix cloud providers. 6. **`punishMisbehavior.disputeThreshold` and `disputeWindow` are both required.** Omitting either when the `punishMisbehavior` block is present is a startup validation error, not a silent default. 7. **S3 content is overwritten on flush**, not appended. The `PutObject` call replaces the object at `prefix/`. Use `{timestampMs}` or `{instanceId}` in `filePattern` to create new objects per flush; `{dateByHour}` causes the same-hour flush to overwrite the previous object. 8. **`recheckInterval` in vendor settings cannot be set from YAML.** The Go type assertion `.(time.Duration)` fails silently when set from YAML. The vendor default (1h for repository/quicknode/chainstack, 24h for alchemy/drpc/superchain/tenderly) always applies in YAML configs. Only programmatic Go configs can override this. 9. **Not extending `ignoreFields` for L2s causes benign disputes.** Running the Ethereum `ignoreFields` set on Arbitrum or Base without adding chain-specific extras will cause constant disputes. Add per-chain extras and include all defaults. 10. **S3 `accessKeyID` YAML casing.** The YAML key is `accessKeyID` (capital D). The common typo `accessKeyId` is silently ignored; the AWS SDK falls back to its default credential chain. ### Observability Every consensus dispute increments `erpc_consensus_misbehavior_detected_total`. Wire your alerting to this metric: a sudden spike means a provider is diverging from consensus on a live verification path. | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_consensus_total` | counter | project, network, category, outcome, finality | Every `Run` completion. `outcome`: `success`, `consensus_on_error`, `dispute`, `low_participants`, `generic_error`, `caller_abandoned`. | | `erpc_consensus_misbehavior_detected_total` | counter | project, network, upstream, category, finality, response_type, larger_than_consensus | Per misbehaving upstream per round. Primary alert metric for DVN operators. | | `erpc_consensus_upstream_punished_total` | counter | project, network, upstream | When an upstream is cordoned. | | `erpc_consensus_upstream_errors_total` | counter | project, network, upstream, category, finality, response_type, error_code | Per upstream per round when upstream has an error disagreeing with consensus group. | | `erpc_consensus_responses_collected` | histogram | project, network, category, vendors, short_circuited, finality | After all responses collected; records count. `short_circuited=false` expected when `preferLargerResponses: true`. | | `erpc_consensus_short_circuit_total` | counter | project, network, category, reason, finality | When short-circuit fires (`preferLargerResponses: true` disables this). | See [Monitoring](/operation/monitoring.llms.txt) for the full Prometheus metric set. ### Source code entry points - [`consensus/executor.go:L183-L291`](https://github.com/erpc/erpc/blob/main/consensus/executor.go#L183-L291) — `executeConsensus`: fan-out, wait caps, short-circuit, analyzer loop - [`consensus/rules.go:L24-L840`](https://github.com/erpc/erpc/blob/main/consensus/rules.go#L24-L840) — `consensusRules`: all 24 priority-ordered decision rules including `preferNonEmpty`, `preferLargerResponses`, `returnError` semantics - [`consensus/export.go:L1-L120`](https://github.com/erpc/erpc/blob/main/consensus/export.go#L1-L120) — `fileMisbehaviorExporter`: JSONL record structs and file write logic - [`consensus/export_s3.go:L1-L200`](https://github.com/erpc/erpc/blob/main/consensus/export_s3.go#L1-L200) — `s3MisbehaviorExporter`: buffered per-key S3 uploads with background flush - [`common/defaults.go:L2389-L2487`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2389-L2487) — `ConsensusPolicyConfig.SetDefaults`: all default values including `ignoreFields` map - [`erpc/network_executor.go:L174-L188`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L174-L188) — integration point: routes to `consensus.Run` when policy present and `SkipConsensus` is false - [`consensus/analysis.go:L442-L453`](https://github.com/erpc/erpc/blob/main/consensus/analysis.go#L442-L453) — `CanonicalHashWithIgnoredFields`: dot-path wildcard hashing - [`consensus/quota.go:L27-L79`](https://github.com/erpc/erpc/blob/main/consensus/quota.go#L27-L79) — `reorderForParticipantQuota`: tag-aware participant front-loading ### Related pages - [Consensus](/config/failsafe/consensus.llms.txt) — full reference for every consensus config field and rule. - [Retry](/config/failsafe/retry.llms.txt) — wraps the consensus slot; each retry attempt is a fresh upstream call. - [Hedge](/config/failsafe/hedge.llms.txt) — used by the default (`matchMethod: "*"`) policy in this preset. - [Rate limiters](/config/rate-limiters.llms.txt) — cap request volume per upstream to stay within provider budgets. - [Providers & vendors](/config/projects/providers.llms.txt) — shorthand endpoint forms (`alchemy://KEY`, etc.) supported in `upstreams[].endpoint`. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the broader resilience pattern this preset builds on. --- --- # Error taxonomy > Source: https://docs.erpc.cloud/reference/errors > Every error eRPC can emit — typed, categorized, with retryability flags, wire HTTP status, and JSON-RPC codes — so you can interpret metrics, write alerts, and debug routing decisions confidently. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Error taxonomy A catalog of all ~73 typed errors eRPC can emit, organized by category. Each entry shows whether the error retries on the same upstream, retries on a different upstream, what HTTP status and JSON-RPC code it produces on the wire, and whether it is live or dead code. Every vendor's idiosyncratic message is normalized into one of these types before retry logic or metrics ever see it. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: debug why requests are exhausting all upstreams** ```text My eRPC instance frequently returns ErrUpstreamsExhausted to clients and I don't know which upstream error type is dominating. Read the error taxonomy, then inspect my my eRPC config config and tell me which metrics and log fields to check, and how to adjust retry or circuit-breaker settings based on the dominant child error. Reference: https://docs.erpc.cloud/reference/errors.llms.txt ``` **Prompt Example #2: set up production alerting on error severity** ```text I want Prometheus alerts that fire on critical errors only and ignore expected noise like hedge discards and client disconnects. Using the severity classification in the eRPC error taxonomy, write PromQL alert expressions for my eRPC config deployment and explain which error codes map to each severity level. Reference: https://docs.erpc.cloud/reference/errors.llms.txt ``` **Prompt Example #3: trace a -32003 response on eth_sendRawTransaction** ```text Some of my eth_sendRawTransaction calls return JSON-RPC code -32003 even though the transactions go through. Explain which normalizer rules apply to sendRawTransaction, why eRPC may have retried, and how to distinguish already_known from nonce_too_low using the error details fields. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/reference/errors.llms.txt ``` --- ### Error taxonomy — full agent reference ### How it works **Two-layer taxonomy.** Go errors are `BaseError`-rooted structs with a string `ErrorCode` constant. Upstream-attributed errors additionally carry an `UpstreamAwareError` accessor. `ErrJsonRpcExceptionExternal` is deliberately NOT a `StandardError` — it is the raw vendor JSON-RPC object used as input to normalizers only; it never propagates beyond the client layer. **Normalization pipeline.** Architecture-specific extractors are composed, and each no-ops on upstreams of the other type. EVM HTTP responses go through `ExtractJsonRpcError` (`architecture/evm/error_normalizer.go`), which runs a vendor-specific hook first, then evaluates 22 ordered rules (first match wins). SVM HTTP responses go through `architecture/svm/error_normalizer.go`, which classifies from the native Solana code and **preserves that code and `error.data` on the wire** — see [SVM (Solana) error contract](#svm-solana-error-contract). gRPC/BDS responses go through `ExtractGrpcErrorFromGrpcStatus` (`common/grpc_errors.go`), which checks BDS error codes first, then standard gRPC codes. All paths produce a typed internal error wrapping `ErrJsonRpcExceptionInternal` that carries both the original vendor code and the normalized eRPC code. **Retryability is dual-axis.** `IsRetryableTowardsUpstream` returns `false` if any of 10 specific codes appear anywhere in the cause chain (including joined multi-errors). `IsRetryableTowardNetwork` defaults to `true` and returns `false` only when: (a) `ErrUpstreamsExhausted` has a nil cause, (b) a multi-error cause has ALL non-retryable children, or (c) a linear cause chain carries `Details["retryableTowardNetwork"]=false`. The flag walk stops at multi-error wrappers to avoid order-dependent bugs. **Wire translation.** `TranslateToJsonRpcException` converts internal errors to a JSON-RPC numeric code. For `ErrUpstreamsExhausted`, it selects the "dominant" child error (highest occurrence count, skipping `ErrCodeUpstreamRequestSkipped` and `ErrCodeEndpointUnsupported`) over a **deterministically ordered** cause slice — retryable-toward-network causes first, then by upstream id — so an identical multiset of upstream failures always yields the same wire code, and a retryable cause outranks a terminal one. HTTP status is determined by two identical switch functions in `erpc/http_server.go` — not by per-type `ErrorStatusCode()` methods, which are dead code. **Error label for metrics.** Both error metrics use `common.ErrorFingerprint(err)` as the `error` label value. `ErrorFingerprint` calls `ErrorSummary` then redacts hashes/addresses/IPs/numbers and caps at 256 characters. The mode of `ErrorSummary` is controlled by `metrics.errorLabelMode`, defaulting to `compact` (code-only labels, preventing high cardinality). `verbose` mode is human-readable but creates unbounded time series — use only in development. **Severity classification.** `ClassifySeverity(err)` categorizes errors for the `severity` Prometheus label: `info` for nil/client errors/execution exceptions; `warning` for non-retryable-toward-upstream errors, `ErrEndpointRequestCanceled`, `context.Canceled`; `critical` for everything else. **`ErrUpstreamsExhausted` aggregation.** This is a multi-error aggregator: its `Cause` is an `errors.Join` of all per-upstream errors. `SummarizeCauses()` buckets children into 19 categories and appends a human-readable suffix to the message: `"(2 upstream timeout, 1 upstream rateLimit)"`. When `buildErrorResponseBody` sees a single-child `ErrUpstreamsExhausted`, it unwraps it — clients see the real upstream error, not the wrapper. **Error class hierarchy:** ``` StandardError interface └── BaseError (embedded in all domain errors) ├── UpstreamAwareError (embedded in upstream-attributed errors) │ ├── Server / request lifecycle │ ├── ErrInvalidRequest, ErrInvalidUrlPath, ErrInvalidConfig │ ├── ErrRequestTimeout, ErrInternalServerError, ErrNotImplemented │ ├── Auth │ ├── ErrAuthUnauthorized, ErrAuthRateLimitRuleExceeded │ ├── Project / Network │ ├── ErrProjectNotFound, ErrProjectAlreadyExists │ ├── ErrNetworkNotFound, ErrNetworkNotSupported, ErrNetworkInitializing │ ├── ErrNetworkNoUpstreamsAvailable │ ├── ErrUnknownNetworkID, ErrUnknownNetworkArchitecture │ ├── ErrInvalidEvmChainId, ErrFinalizedBlockUnavailable, ErrNetworkRequestTimeout │ ├── Upstream lifecycle │ ├── ErrUpstreamClientInitialization, ErrUpstreamInitialization │ ├── ErrNoUpstreamsLeftToSelect, ErrNoUpstreamsDefined, ErrNoUpstreamsFound │ ├── Upstream request routing │ ├── ErrUpstreamRequest (wrapper), ErrUpstreamRequestSkipped │ ├── ErrUpstreamBlockUnavailable, ErrUpstreamMethodIgnored │ ├── ErrUpstreamSyncing, ErrUpstreamShadowing, ErrUpstreamNotAllowed │ ├── ErrUpstreamHedgeCancelled, ErrUpstreamMalformedResponse │ ├── ErrUpstreamsExhausted (multi-error aggregator) │ ├── Rate limiting │ ├── ErrRateLimitBudgetNotFound, ErrProjectRateLimitRuleExceeded │ ├── ErrNetworkRateLimitRuleExceeded, ErrUpstreamRateLimitRuleExceeded │ ├── Endpoint (upstream HTTP/gRPC responses) │ ├── ErrEndpointUnauthorized, ErrEndpointUnsupported │ ├── ErrEndpointClientSideException, ErrEndpointExecutionException │ ├── ErrEndpointTransportFailure, ErrEndpointServerSideException │ ├── ErrEndpointRequestTimeout, ErrEndpointRequestCanceled │ ├── ErrEndpointCapacityExceeded, ErrEndpointBillingIssue │ ├── ErrEndpointMissingData, ErrEndpointRequestTooLarge │ ├── ErrEndpointContentValidation, ErrEndpointNonceException │ ├── Failsafe policies │ ├── ErrFailsafeConfiguration, ErrFailsafeTimeoutExceeded │ ├── ErrFailsafeRetryExceeded, ErrFailsafeCircuitBreakerOpen │ ├── Consensus │ ├── ErrConsensusDispute, ErrConsensusLowParticipants │ ├── getLogs / client range errors │ ├── ErrGetLogsExceededMaxAllowedRange │ ├── ErrGetLogsExceededMaxAllowedAddresses, ErrGetLogsExceededMaxAllowedTopics │ ├── JSON-RPC (carriers) │ ├── ErrJsonRpcRequestUnmarshal, ErrJsonRpcRequestUnresolvableMethod │ ├── ErrJsonRpcRequestPreparation │ └── ErrJsonRpcExceptionInternal (normalized carrier) │ └── Store / cache ├── ErrInvalidConnectorDriver, ErrRecordNotFound, ErrRecordExpired Not StandardError (standalone types): ├── ErrJsonRpcExceptionExternal — raw upstream JSON-RPC error; normalizer input only ├── TaskFatalError — initializer stop signal; IsTaskFatal()=true └── ErrDynamicTimeoutExceeded — sentinel for context.WithTimeoutCause ``` ### Config schema | YAML path | Type | Default | Behavior / footguns | |---|---|---|---| | `metrics.errorLabelMode` | `string` | `"compact"` ([`common/defaults.go:L762-L764`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L762-L764)) | Controls `ErrorSummary` output format. `"compact"`: code-only labels (low cardinality). `"verbose"`: `CodeChain: cleanedDeepestMessage` (high cardinality; development only). Only `"compact"` and `"verbose"` are accepted ([`common/validation.go:L147-L148`](https://github.com/erpc/erpc/blob/main/common/validation.go#L147-L148)). Applied globally via `common.SetErrorLabelMode`. Source: [`common/config.go:L2536-2550`](https://github.com/erpc/erpc/blob/main/common/config.go#L2536-L2550) | No other error-specific config fields. Vendor normalization is unconditional for any upstream with a matching `Vendor()`. ### Complete error-code table Legend: - **U** = `IsRetryableTowardsUpstream` result - **N** = `IsRetryableTowardNetwork` result - **Wire HTTP** = actual wire status from `determineResponseStatusCode`/`handleErrorResponse` ([`erpc/http_server.go:L1280-1317`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1280-L1317), [`erpc/http_server.go:L1457-1491`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1457-L1491)) - **JSON-RPC** = wire numeric code after `TranslateToJsonRpcException` | # | Error code | U | N | Wire HTTP | JSON-RPC | Notes | |---|---|---|---|---|---|---| | 1 | `ErrInvalidRequest` | yes | yes | 400 | −32602 | invalid body/headers | | 2 | `ErrInvalidUrlPath` | yes | yes | 400 | −32602 | malformed URL path | | 3 | `ErrInvalidConfig` | yes | yes | 200 | −32603 | startup-only | | 4 | `ErrRequestTimeout` | yes | yes | 200 | −32603 | pre-upstream timeout | | 5 | `ErrInternalServerError` | yes | yes | 200 | −32603 | internal | | 6 | `ErrAuthUnauthorized` | yes | yes | 401 | −32016 | auth strategy rejected | | 7 | `ErrAuthRateLimitRuleExceeded` | no (capacity) | yes | 429 | −32005 | auth-level budget | | 8 | `ErrProjectNotFound` | yes | yes | 404 | −32603 | project not configured | | 9 | `ErrProjectAlreadyExists` | n/a | n/a | — | — | startup duplicate | | 10 | `ErrNetworkNotFound` | yes | yes | 404 | −32603 | network not configured | | 11 | `ErrUnknownNetworkID` | yes | yes | 200 | −32603 | — | | 12 | `ErrUnknownNetworkArchitecture` | yes | yes | 200 | −32603 | — | | 13 | `ErrNotImplemented` | yes | yes | 200 | −32601 | stateful method under a multi-upstream pool or served by no targeted upstream, `eth_accounts`/`eth_sign`, or subscription over HTTP → method not supported | | 14 | `ErrInvalidEvmChainId` | yes | yes | 200 | −32603 | — | | 15 | `ErrFinalizedBlockUnavailable` | yes | yes | 200 | −32603 | finality check | | 16 | `ErrUpstreamClientInitialization` | yes | yes | — | — | not fatal unless wrapped in `TaskFatalError` | | 17 | `ErrUpstreamRequest` | inherited | inherited | — | inherited | wrapper; carries durationMs/attempts/retries/hedges | | 18 | `ErrUpstreamMalformedResponse` | yes | yes | 200 | −32603 | — | | 19 | `ErrUpstreamsExhausted` | recursive | recursive | 200 | from dominant child | multi-error aggregator | | 20 | `ErrNoUpstreamsLeftToSelect` | yes | yes | 200 | −32603 | per-upstream states in details | | 21 | `ErrNoUpstreamsDefined` | yes | yes | 200 | −32603 | **Dead code** — zero production call sites | | 22 | `ErrNoUpstreamsFound` | yes | yes | 200 | −32603 | — | | 23 | `ErrNetworkInitializing` | yes | yes | 200 | −32603 | retry shortly; becomes `ErrNetworkNoUpstreamsAvailable` past the threshold | | 23b | `ErrNetworkNoUpstreamsAvailable` | yes | yes | 404 | −32603 | network stuck initializing with zero upstreams for `upstream.NoUpstreamsAvailableAfter` (5m) | | 24 | `ErrNetworkNotSupported` | yes | yes | 404 | −32603 | no provider covers network | | 25 | `ErrUpstreamNetworkNotDetected` | yes | yes | — | — | **Dead code** — zero production call sites | | 26 | `ErrUpstreamInitialization` | yes | yes | — | — | — | | 27 | `ErrUpstreamRequestSkipped` | no | yes | 200 | −32603 | permanent skip | | 28 | `ErrUpstreamBlockUnavailable` | yes | yes | 200 | −32603 | transient lag | | 29 | `ErrUpstreamMethodIgnored` | no | yes | 200 | −32601 | `ignoreMethods` config | | 30 | `ErrUpstreamSyncing` | yes | yes | 200 | −32603 | node still syncing | | 31 | `ErrUpstreamShadowing` | yes | yes | — | — | shadow mode | | 32 | `ErrUpstreamNotAllowed` | yes | yes | — | — | use-upstream directive | | 33 | `ErrUpstreamHedgeCancelled` | yes | yes | — | — | hedge discard | | 34 | `ErrResponseWriteLock` | yes | yes | — | — | **Dead code** — superseded by `ErrUpstreamHedgeCancelled` | | 35 | `ErrJsonRpcRequestUnmarshal` | no | no | 400 | −32700 | retryableTowardNetwork=false always | | 36 | `ErrJsonRpcRequestUnresolvableMethod` | yes | no | 200 | −32603 | retryableTowardNetwork=false; note: gets −32603, not −32700 | | 37 | `ErrJsonRpcRequestPreparation` | yes | no | 200 | −32603 | **Dead code** — N=false default is caller-overridable (unique in taxonomy) | | 38 | `ErrFailsafeConfiguration` | n/a | n/a | — | — | startup | | 39 | `ErrFailsafeTimeoutExceeded` | yes | yes | 200 | −32603 | scope in message | | 40 | `ErrFailsafeRetryExceeded` | inherited | inherited | — | inherited | scope in message | | 41 | `ErrFailsafeCircuitBreakerOpen` | no | yes | 200 | −32603 | — | | 42 | `ErrRateLimitBudgetNotFound` | n/a | n/a | — | — | config | | 43 | `ErrRateLimitRuleNotFound` | n/a | n/a | — | — | **Dead code** — zero production call sites | | 44 | `ErrProjectRateLimitRuleExceeded` | no (capacity) | yes | 429 | −32005 | — | | 45 | `ErrNetworkRateLimitRuleExceeded` | no (capacity) | yes | 429 | −32005 | — | | 46 | `ErrNetworkRequestTimeout` | yes | yes | 200 | −32603 | network-scope timeout | | 47 | `ErrUpstreamRateLimitRuleExceeded` | no (capacity) | yes | 200 | −32005 | NOT in wire 429 list despite method returning 429 | | 48 | `ErrUpstreamExcludedByPolicy` | yes | yes | — | — | **Dead code** — zero production call sites; exclusion is structural | | 49 | `ErrEndpointUnauthorized` | no | yes | 401 | −32016 | provider 401/403 | | 50 | `ErrEndpointUnsupported` | no | yes | 200 | −32601 | — | | 51 | `ErrEndpointClientSideException` | yes | yes (default) | 200 | from cause | N:no set by some normalizer branches (rules 17, 18d) | | 52 | `ErrEndpointExecutionException` | no | no | 200 | 3 or −32003 | N:yes overridden for `eth_sendRawTransaction` reverts | | 53 | `ErrEndpointTransportFailure` | yes | yes | — | −32603 | URL stripped from cause msg (credential hygiene) | | 54 | `ErrEndpointServerSideException` | yes | yes | 200 | from cause | `originalStatusCode` stored in details | | 55 | `ErrEndpointRequestTimeout` | yes | yes | 200 | −32015 | — | | 56 | `ErrEndpointRequestCanceled` | yes | yes | — | — | severity=warning | | 57 | `ErrEndpointCapacityExceeded` | no (capacity) | yes | 429 | −32005 | — | | 58 | `ErrEndpointBillingIssue` | no | yes | 200 | −32005 | — | | 59 | `ErrEndpointMissingData` | yes | yes | 200 | −32014 | details: latestBlock/finalizedBlock/maxAvailableRecentBlocks | | 60 | `ErrUpstreamNodeTypeMismatch` | yes | yes | — | −32603 | archive vs full node | | 61 | `ErrEndpointRequestTooLarge` | no | yes | 200 | −32012 | complaint: `evm_block_range` or `evm_addresses` | | 62 | `ErrJsonRpcExceptionInternal` | wrapper | wrapper | — | `normalizedCode` field | internal carrier for normalized codes | | 63 | `ErrJsonRpcExceptionExternal` | n/a | n/a | — | — | raw upstream JSON-RPC; normalizer input only | | 64 | `ErrInvalidConnectorDriver` | n/a | n/a | — | — | config | | 65 | `ErrRecordNotFound` | yes | yes | — | — | cache miss | | 66 | `ErrRecordExpired` | yes | yes | — | — | cache TTL exceeded | | 67 | `ErrConsensusDispute` | multi | multi | 200 | −32603 | retryable if ANY child is retryable | | 68 | `ErrConsensusLowParticipants` | multi | multi | 200 | −32603 | same any-child rule | | 69 | `ErrGetLogsExceededMaxAllowedRange` | yes | yes | 200 | −32012 | eRPC cap, not upstream | | 70 | `ErrGetLogsExceededMaxAllowedAddresses` | yes | yes | 200 | −32012 | — | | 71 | `ErrGetLogsExceededMaxAllowedTopics` | yes | yes | 200 | −32012 | — | | 72 | `ErrEndpointContentValidation` | no | yes | 200 | −32603 | try different upstream | | 73 | `ErrEndpointNonceException` | yes | no | 200 | −32003 | reason: `already_known` or `nonce_too_low`; idempotency | Non-`StandardError` types: `ErrJsonRpcExceptionExternal` (normalizer input), `TaskFatalError` (initializer stop signal), `ErrDynamicTimeoutExceeded` (sentinel distinguishing failsafe-policy timeout from HTTP server deadline). ### JSON-RPC numeric codes All defined at [`common/errors.go:L2151-L2174`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2151-L2174). | Constant | Value | Category | |---|---|---| | `JsonRpcErrorUnknown` | −99999 | eRPC internal — unclassified fallback | | `JsonRpcErrorCallException` | −32000 | standard — generic call exception | | `JsonRpcErrorTransactionRejected` | −32003 | standard — transaction rejected; also nonce exceptions | | `JsonRpcErrorClientSideException` | −32600 | standard — invalid request | | `JsonRpcErrorUnsupportedException` | −32601 | standard — method not found/unsupported | | `JsonRpcErrorInvalidArgument` | −32602 | standard — invalid params | | `JsonRpcErrorServerSideException` | −32603 | standard — internal error; eRPC default for unmapped errors | | `JsonRpcErrorParseException` | −32700 | standard — JSON parse error | | `JsonRpcErrorEvmReverted` | 3 | de-facto — EVM execution reverted (positive code) | | `JsonRpcErrorCapacityExceeded` | −32005 | eRPC-normalized — maps all rate-limit / capacity types | | `JsonRpcErrorEvmLargeRange` | −32012 | eRPC-normalized — request range too large | | `JsonRpcErrorMissingData` | −32014 | eRPC-normalized — data not on this node | | `JsonRpcErrorNodeTimeout` | −32015 | eRPC-normalized — node-level timeout | | `JsonRpcErrorUnauthorized` | −32016 | eRPC-normalized — unauthorized/forbidden | ### Wire HTTP status mapping | Wire HTTP | Triggered by (`HasErrorCode` anywhere in chain) | |---|---| | 400 | `ErrInvalidUrlPath`, `ErrJsonRpcRequestUnmarshal`, `ErrInvalidRequest` | | 401 | `ErrAuthUnauthorized`, `ErrEndpointUnauthorized` | | 404 | `ErrProjectNotFound`, `ErrNetworkNotFound`, `ErrNetworkNotSupported`, `ErrNetworkNoUpstreamsAvailable` | | 429 | `ErrAuthRateLimitRuleExceeded`, `ErrProjectRateLimitRuleExceeded`, `ErrNetworkRateLimitRuleExceeded`, `ErrEndpointCapacityExceeded` | | 200 | everything else | **`ErrUpstreamRateLimitRuleExceeded` returns 200 on the wire** despite its `ErrorStatusCode()` method returning 429. It is not in the wire 429 switch. ### HTTP/JSON-RPC vendor normalization rules Entry point: [`architecture/evm/error_normalizer.go:L20`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L20). Triggered when `jr.Error != nil` OR HTTP status > 299. Rules evaluated in order — **first match wins**. `originalCode` (vendor numeric) is preserved; `normalizedCode` is set to the eRPC value. | # | Trigger | Normalized error | JSON-RPC | U | N | |---|---|---|---|---|---| | 0 | Vendor hook returns non-nil | vendor-defined | vendor-defined | — | — | | 1 | Block-range-too-large strings ("Try with this block range", "max block range", "range too large", "too many results", "try paginating", etc.) | `ErrEndpointRequestTooLarge` (`evm_block_range`) | −32012 | no | yes | | 2 | Address-count strings ("specify less number of address", "addresses or topics per search position", "filters"+"current limit is") | `ErrEndpointRequestTooLarge` (`evm_addresses`) | −32012 | no | yes | | 3 | "sender is over rate limit" (OP sequencer) | `ErrEndpointCapacityExceeded` | −32005 | no | **no** (all providers hit same sequencer) | | 4 | status 402, "reached the free tier", "Monthly capacity limit", "/billing" | `ErrEndpointBillingIssue` | −32005 | no | yes | | 5 | status 429, "Too many requests", "rate limit", "has exceeded", "limit exceeded", etc. | `ErrEndpointCapacityExceeded` | −32005 | no | yes | | 6 | Block-tag unsupported ("pending block is not available", "safe block not found", "finalized is not a supported", etc.) | `ErrEndpointClientSideException` | −32600 | yes | yes (deliberately retryable) | | 7 | Missing-data patterns ("missing trie node", "unknown block", "header not found", "transaction not found", "no historical rpc", etc.) | `ErrEndpointMissingData` | −32014 | yes | yes | | 7b | "gas exhausted during precompiled contract execution" (HyperEVM node without HyperCore state for the requested block), any method except `eth_sendRawTransaction` — **must precede rule 14** | `ErrEndpointMissingData` | −32014 | yes | yes | | 8 | "execution timeout" | `ErrEndpointServerSideException` | −32015 | yes | yes | | 9 | Reverts: "reverted", "VM execution error", "VM Exception", "intrinsic gas too high", reth `RevertError { output: Some(0x…) \| None }` (−32603, no `data`; the `0x…` bytes become `data`) | `ErrEndpointExecutionException` | 3 | no | no (yes for `eth_sendRawTransaction`) | | 10 | "EVM error: InvalidJump" (Berachain) | `ErrEndpointExecutionException` | 3 | no | no (yes for `eth_sendRawTransaction`) | | 11 | Duplicate-tx: "already known", "tx already in mempool", "transaction already exists", etc. — **must precede rule 14** | `ErrEndpointNonceException` (`already_known`) | −32003 | yes | no | | 12 | Nonce conflict: "nonce too low", "nonce has already been used" | `ErrEndpointNonceException` (`nonce_too_low`) | −32003 | yes | no | | 12b | Mempool policy rejections: "existing transaction had higher priority", "newer transaction had higher priority", "transaction fee too low", whole-message "rejected" (Monad `EthTxPoolDropReason`, surfaced as −32603 with no `data`); "underpriced" (geth-family "transaction underpriced", "replacement transaction underpriced") | `ErrEndpointExecutionException` | −32003 | no | no (yes for `eth_sendRawTransaction` — pool contents are node-local) | | 13 | "insufficient funds", "insufficient balance" | `ErrEndpointExecutionException` | −32003 | no | yes (`trace_*`/`debug_*`/`eth_trace*` only — state-reconstruction artifact; non-retried for writes & live simulations) | | 14 | code == −32003, "out of gas", "gas too low", "gas required exceeds allowance" (`eth_estimateGas` out of gas at its cap; go-ethereum estimator, seen on Arbitrum nitro), "IntrinsicGas" | `ErrEndpointExecutionException` | −32003 | no | no (yes for `eth_sendRawTransaction`) | | 14b | "invalid chain id" (the transaction's chainId does not match the network) | `ErrEndpointExecutionException` | −32003 | no | **no**, including `eth_sendRawTransaction` | | 14c | "exceeds block gas limit" (the transaction's gas limit is above the block gas limit) | `ErrEndpointExecutionException` | −32003 | no | **no**, including `eth_sendRawTransaction` | | 15a | "not found"/"not available" AND ("Method"\|"module") | `ErrEndpointUnsupported` | −32601 | no | yes | | 15b | same outer AND ("header"\|"block"\|"transaction"\|"state") | `ErrEndpointMissingData` | −32014 | yes | yes | | 15c | same outer, neither 15a nor 15b | `ErrEndpointClientSideException` | −32600 | yes | yes | | 16 | status 415/405, code −32601/−32004/−32001, "Unsupported method", "not supported", "method is not whitelisted" — **must follow "not found" rules** | `ErrEndpointUnsupported` | −32601 | no | yes | | 17 | Malformed tx: "rlp: expected input list", "typed transaction too short", "invalid transaction" | `ErrEndpointClientSideException` | −32602 | yes | **no** | | 18a | "tx of type", Envio type errors | `ErrEndpointClientSideException` | −32601 | yes | yes | | 18b | code == −32600 AND data contains "validation errors in batch" | `ErrEndpointClientSideException` | −32000 | yes | yes | | 18c | code == −32602 or −32600 (generic) | `ErrEndpointClientSideException` | −32602 | yes | yes | | 18d | "param is required", "Invalid Request", "invalid argument", "invalid params" | `ErrEndpointClientSideException` | −32602 | yes | **no** | | 19 | status 401/403, "invalid api key", "key is inactive", "unauthorized" | `ErrEndpointUnauthorized` | −32016 | no | yes | | 20 | Fallback (everything else) | `ErrEndpointServerSideException` | passthrough vendor code | yes | yes | | 21 | 200-OK result begins with `0x08c379a0` at `dt[1:11]` (index 0 is JSON quote) | `ErrEndpointExecutionException` | 3 | no | no | | 22 | `trace_*`/`debug_*`/`eth_trace*` AND raw body contains "execution timeout" (string scan, not JSON) | `ErrEndpointServerSideException` | −32015 | yes | yes | ### gRPC/BDS normalization rules Entry point: [`common/grpc_errors.go:L12`](https://github.com/erpc/erpc/blob/main/common/grpc_errors.go#L12). BDS error codes checked first, then gRPC codes. | Trigger | Normalized error | JSON-RPC | U | N | |---|---|---|---|---| | BDS `UNSUPPORTED_BLOCK_TAG`, `UNSUPPORTED_METHOD` | `ErrEndpointUnsupported` | −32601 | no | yes | | BDS `RANGE_OUTSIDE_AVAILABLE` | `ErrEndpointMissingData` | −32014 | yes | yes | | BDS `INVALID_PARAMETER`, `INVALID_REQUEST` | `ErrEndpointClientSideException` | −32602 | yes | **no** | | BDS `RATE_LIMITED` | `ErrEndpointCapacityExceeded` | −32005 | no | yes | | BDS `TIMEOUT_ERROR` | `ErrEndpointRequestTimeout` | −32015 | yes | yes | | BDS `RANGE_TOO_LARGE` | `ErrEndpointRequestTooLarge` (`evm_block_range`) | −32012 | no | yes | | BDS `INTERNAL_ERROR` | `ErrEndpointServerSideException` | −32603 | yes | yes | | gRPC `Canceled` | `ErrEndpointRequestCanceled` | — | yes | yes | | gRPC `Unimplemented` | `ErrEndpointUnsupported` | −32601 | no | yes | | gRPC `InvalidArgument` | `ErrEndpointClientSideException` | −32602 | yes | **no** | | gRPC `ResourceExhausted` | `ErrEndpointCapacityExceeded` | −32005 | no | yes | | gRPC `DeadlineExceeded` | `ErrEndpointRequestTimeout` | −32015 | yes | yes | | gRPC `Unauthenticated`, `PermissionDenied` | `ErrEndpointUnauthorized` | −32016 | no | yes | | gRPC `NotFound`, `OutOfRange` | `ErrEndpointMissingData` | −32014 | yes | yes | | gRPC `Internal`, `Unknown`, `Unavailable`, default | `ErrEndpointServerSideException` | −32603 | yes | yes | ### SVM (Solana) error contract Entry point: [`architecture/svm/error_normalizer.go:L68-73`](https://github.com/erpc/erpc/blob/main/architecture/svm/error_normalizer.go#L68-L73). The SVM extractor no-ops on non-SVM upstreams, so a mixed EVM/SVM project shares one composite extractor. **Native codes reach the client unchanged.** This is the central guarantee and it is the opposite of the EVM path's normalize-the-number behavior. Solana clients dispatch on the exact number — `@solana/kit` maps `-32002`/`-32005`/`-32016`/… to named error classes — so rewriting the code to an eRPC constant silently breaks them. eRPC's routing verdict lives entirely in the **outer `StandardError` class** (retryable / capacity / client-vs-server), never in the wire number. **`error.data` is carried through verbatim.** Solana packs the actionable half of an error there. Dropping it is what broke `@solana/web3.js` `SendTransactionError` (which reads `data.logs`) and `@solana/kit`. Unlike EVM there is no prefix-stripping to do — SVM payloads are structured objects, not revert strings. An empty-string `data` is treated as `ParseError`'s "no data" placeholder and omitted rather than forwarded. In particular: - **`-32002 SendTransactionPreflightFailure` carries an `RpcSimulateTransactionResult`** — `err`, `logs`, `unitsConsumed`, `accounts`. Both the code and that object survive to the client, which is precisely why `@solana/web3.js` can raise `SendTransactionError` with populated `.logs`. - **`-32005 NodeUnhealthy` carries `numSlotsBehind`.** **The eRPC/Solana code collision.** `common.JsonRpcErrorNumber` reuses `-32005` for `CapacityExceeded` and `-32016` for `Unauthorized`, while Solana assigns those to `NodeUnhealthy` and `MinContextSlotNotReached`. The invariant that keeps them apart: **on an SVM path eRPC never synthesizes either number.** A `-32005` or `-32016` in an SVM error body always came from the upstream and always means the agave semantic. eRPC's own verdicts are conveyed by the outer class and the HTTP status, and every fallback picks a collision-free code: | eRPC verdict on an SVM path | Wire code when the upstream sent none | Why not the eRPC constant | |---|---|---| | Unauthorized (HTTP 401/403) | `-32600` | `-32016` would be decoded as `MinContextSlotNotReached`, so a client would retry against a fresher node forever instead of fixing its key | | Capacity exceeded (HTTP 429, no body) | `-32000` | `-32005` would be decoded as `NodeUnhealthy` | | Unknown / codeless error object | `-32603` | — | #### SVM code map "Retry another upstream?" is `IsRetryableTowardNetwork`. Every row keeps the upstream's own numeric code on the wire. | Code | agave name | eRPC class | Retry another upstream? | What it tells a client | |---|---|---|---|---| | `-32601` | MethodNotFound | `ErrEndpointUnsupported` | yes | This provider does not implement the method; another may. | | `-32001` | BlockCleanedUp | `ErrEndpointMissingData` | yes | Pruned from **this node's** local ledger — a bigtable-backed provider still has it. | | `-32004` | BlockNotAvailable | `ErrEndpointMissingData` | yes | The block exists but has not reached this node yet (tip propagation). **Transient — retry.** | | `-32008` | NoSnapshot | `ErrEndpointMissingData` | yes | This node currently holds no snapshot. | | `-32010` | KeyExcludedFromSecondaryIndex | `ErrEndpointMissingData` | yes | Index coverage is per-provider (`--account-index`), so an indexed provider serves it. A deliberate divergence from routers that mark this terminal. | | `-32011` | TransactionHistoryNotAvailable | `ErrEndpointMissingData` | yes | This node has no transaction history (no bigtable); others do. | | `-32014` | BlockStatusNotAvailableYet | `ErrEndpointMissingData` | yes | Block status not computed yet on this node. **Transient — retry.** | | `-32007` | SlotSkipped | `ErrEndpointMissingData`, **permanent** | yes, once per provider | Ambiguous by design: *skipped*, or *lost to a ledger jump*. The ledger-jump half is node-local so the sweep tries every provider — but a skipped slot never materializes, so once all providers have answered there is no time-delayed re-sweep. **Do not poll for it.** | | `-32009` | LongTermStorageSlotSkipped | `ErrEndpointMissingData`, **permanent** | yes, once per provider | The node consulted its own long-term storage and did not find the slot. Archive completeness differs per provider, so one provider's gap does not answer for the cluster: eRPC asks every provider once, like `-32007`, then stops. **Do not poll for it.** | | `-32005` | NodeUnhealthy | `ErrEndpointServerSideException` | yes | This node is behind; `data.numSlotsBehind` says how far. A fresher upstream serves it. | | `-32012` | ScanError | `ErrEndpointServerSideException` | yes | Scan aborted by rooted-slot movement — transient; another node or a plain retry succeeds. | | `-32016` | MinContextSlotNotReached | `ErrEndpointServerSideException` | yes | This node has not caught up to the request's `minContextSlot`. Selection also pre-filters on this, so seeing it means no upstream had fresh enough tracked state. Back off; do not treat as a hard failure. | | `-32019` | LongTermStorageUnreachable | `ErrEndpointServerSideException` | yes | This node's bigtable backend is down — distinct from `-32009`, which is a verdict about the data. | | `-32020` on `getSignaturesForAddress` | vendor: signature not found | `ErrEndpointMissingData`, **permanent** | yes, once per provider | Not an agave code. Some vendor proxies send it when the `before`/`until` cursor is unknown to them, where agave answers an empty page. eRPC asks every other provider once and serves what they answer; it never asks the same provider again in that request. On any other method `-32020` takes the unknown-code default. | | `null` from `getBlockTime` | vendor: no time for a rooted slot | `ErrEndpointMissingData` `-32009`, **permanent** | yes, once per provider | Not an agave answer for a slot at or below the provider's finalized slot that the cluster records a time for: agave answers `-32007` or `-32009` there. Some vendors answer `null` for a skipped slot. eRPC asks every other provider once; when none has the time, the client receives an error (`-32007` or `-32009`), never `null`. A `null` for a slot before the cluster recorded block times is agave's answer and is served. | | `-32002` | SendTransactionPreflightFailure | `ErrEndpointClientSideException` | **no** | The transaction itself is the problem. `data` is an `RpcSimulateTransactionResult`; read `data.logs`. | | `-32003` | TransactionSignatureVerificationFailure | `ErrEndpointClientSideException` | **no** | Fix the signature. | | `-32006` | TransactionPrecompileVerificationFailure | `ErrEndpointClientSideException` | **no** | Fix the instruction. | | `-32013` | TransactionSignatureLenMismatch | `ErrEndpointClientSideException` | **no** | Fix the payload. | | `-32015` | UnsupportedTransactionVersion | `ErrEndpointClientSideException` | **no** | Set `maxSupportedTransactionVersion`. A versioned transaction is present whichever node answers. | | `-32018` | SlotNotEpochBoundary | `ErrEndpointClientSideException` | **no** | The caller-supplied slot is invalid for this query. | | `-32600` / `-32602` / `-32700` | InvalidRequest / InvalidParams / ParseError | `ErrEndpointClientSideException` | **no** | Passed through rather than collapsed to `-32600`, preserving the distinction every JSON-RPC client already understands. | | `-32017` | EpochRewardsPeriodActive | `ErrEndpointExecutionException` | **no** | Epoch-rewards distribution is in progress for the queried epoch; the whole cluster reports the same until it completes. Not the caller's fault, but retrying will not change it. | | `-32603` | InternalError | `ErrEndpointServerSideException` | yes | Try another upstream. | | `-32000` | generic server-error bucket | see below | see below | Disambiguated by message text. | | anything else | newer agave codes | `ErrEndpointServerSideException` | yes | agave appends codes over time; the default is deliberately safe rather than surprising. The raw code is kept. | **`WithRetryableTowardNetwork(false)` on the client-side rows scopes the opt-out to SVM only** — EVM's `ClientSideException` still retries, which is its default. #### The `-32000` bucket Some vendors put everything in `-32000`. eRPC disambiguates by message text, and **every branch keeps `-32000` on the wire** — a heuristic on vendor wording is far too weak a basis for rewriting the number a client dispatches on. Only the routing verdict changes: | Message contains | eRPC class | Retry another upstream? | |---|---|---| | a rate-limit phrase | `ErrEndpointCapacityExceeded` | yes | | `"missing in long-term storage"` | `ErrEndpointMissingData`, permanent (codeless `-32009` variant) | yes, once per provider | | `"ledger jump"` | `ErrEndpointMissingData`, permanent (codeless `-32007` variant) | yes, once per provider | | `"preflight"`, `"transaction simulation failed"`, `"blockhash not found"` | `ErrEndpointClientSideException` | **no** | | `"invalid"` plus one of `"signature"`/`"transaction"`/`"instruction"` | `ErrEndpointClientSideException` | **no** | | anything else | `ErrEndpointServerSideException` | yes | #### HTTP-only failures (no JSON-RPC body) | Status | eRPC class | Wire code | Note | |---|---|---|---| | 401 / 403 | `ErrEndpointUnauthorized` | upstream's code, else `-32600` | **Outranks the JSON-RPC body.** Helius and QuickNode return 401/403 *with* an error object; reading that body first sent an expired API key down whichever generic path its code happened to map to. The upstream's message and `data` still ride along. | | 429 | `ErrEndpointCapacityExceeded` | `-32000` | | | 5xx | `ErrEndpointServerSideException` | `-32603` | Retryable. | | other 4xx | `ErrEndpointClientSideException` | `-32602` | Non-retryable toward network — typically an auth/config issue. | #### Deterministic codes when upstreams disagree When every upstream fails, the per-upstream errors are bundled into `ErrUpstreamsExhausted` and one representative is chosen for the client-visible code. That choice is **deterministic for a given multiset of causes**, and a **retryable cause outranks a terminal one**. `sync.Map.Range` yields Go-map order, which varies run to run, so `orderCauses` imposes a total order before anything downstream picks a representative: 1. **Retryable-toward-network causes before terminal ones.** When upstreams disagree about the same datum — one says "not available yet", another says "gone forever" — the retryable verdict is the safe representative. Reporting "gone forever" can make a consumer permanently skip data that does exist, which is unrecoverable; reporting "not yet" merely costs a retry. 2. **Then by upstream id**, so equally-retryable causes still have exactly one canonical order. A tie on both falls back to the error text. `TranslateToJsonRpcException` then tallies the dominant error code over that ordered slice and takes the **first** cause in the winning bucket — so with, say, one upstream reporting `-32004 BlockNotAvailable` and another reporting `-32007 SlotSkipped` for the same slot, the client deterministically sees the retryable `-32004`. Both ranks are architecture-neutral: rank 1 reads the very same flag the retry path consults, so no chain-specific error code leaks into `common/`. **Permanent is not terminal.** `-32007` and `-32009` are *permanent* but still retryable across upstreams: eRPC asks every provider once, then stops. Waiting cannot un-skip a slot, so no time-delayed re-sweep runs. "Once" holds for the whole client request: an upstream that gave a permanent verdict is not asked again by a hedge leg, a network retry, or an upstream retry. When every selected upstream has given one, the request ends with the upstream's error. The permanent flag lives on each individual `MissingData` cause, never on the `ErrUpstreamsExhausted` wrapper — the predicate walks only a single-cause chain and stops before entering a multi-error fan-out. #### SVM write-method guard [`architecture/svm/util.go:L20-28`](https://github.com/erpc/erpc/blob/main/architecture/svm/util.go#L20-L28). Case-insensitive, so a mis-cased method name cannot slip past the guard: ``` sendTransaction sendRawTransaction requestAirdrop ``` These are **never auto-dispatched to a second upstream** by any machinery — network hedge ([`erpc/network_executor.go:L583-587`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L583-L587)), upstream retry and hedge ([`upstream/upstream_executor.go:L250-251,288-289`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go#L250-L251,288-L289)), and selection probe mirroring ([`internal/policy/prober.go:L433`](https://github.com/erpc/erpc/blob/main/internal/policy/prober.go#L433)) all gate on this helper. On top of that, an error from one of these methods is wrapped as `ClientSideException` on the response path, which is what makes the network-level upstream loop bail out: that loop checks `common.IsClientError` — specifically for `ErrCodeEndpointClientSideException` — rather than walking `retryableTowardNetwork` details, so without the wrap a `ServerSideException` from the primary would be silently failed over to the secondary. The reasons differ per method, and the distinction matters: - `sendTransaction` / `sendRawTransaction`: Solana transaction broadcasts are **same-signature idempotent on-chain**, so the risk is not a double-spend — it is duplicate broadcasts burning vendor quota and violating the documented single-broadcast guarantee. - `requestAirdrop`: genuinely non-idempotent. It **mints per call**, so a failover after an effective first attempt mints twice. `simulateTransaction` is intentionally absent — it is read-only and safe to retry and hedge. (It is still never *cached*; see the [SVM cache](/config/database/svm-json-rpc-cache.llms.txt).) SVM and EVM method names cannot collide: EVM methods are `eth_*`-prefixed, SVM methods are bare, so call sites simply check both sets. ### `IsNonRetryableWriteMethod` (EVM) — write-method guard [`architecture/evm/util.go:L7-L17`](https://github.com/erpc/erpc/blob/main/architecture/evm/util.go#L7-L17). The EVM half of the guard; the SVM twin is [above](#svm-write-method-guard). Returns `true` for methods that MUST NOT be retried or hedged because they mutate state non-idempotently: ``` eth_sendTransaction eth_createAccessList eth_submitTransaction eth_submitWork eth_newFilter eth_newBlockFilter eth_newPendingTransactionFilter ``` **`eth_sendRawTransaction` is deliberately excluded.** The comment explains: it supports idempotency handling (the `ErrEndpointNonceException` `already_known`/`nonce_too_low` path lets eRPC detect and safely retry/hedge `sendRawTransaction` without double-submission risk). **Call sites** — used in two places in [`upstream/upstream_executor.go`](https://github.com/erpc/erpc/blob/main/upstream/upstream_executor.go): 1. **Retry guard** (L243): if the method is a non-retryable write, `isRetryableTowardsUpstream` returns `false` even if the error would otherwise qualify. 2. **Hedge guard** (L281): if the method is a non-retryable write, the hedge path is bypassed entirely. **Interaction with `ErrEndpointExecutionException` N-flag override.** For `eth_sendRawTransaction`, the normalizer overrides `retryableTowardNetwork=true` for revert/out-of-gas results (rules 9 and 14). This is safe precisely because `eth_sendRawTransaction` is NOT in `IsNonRetryableWriteMethod` — the two predicates are complementary. ### `ErrUpstreamsExhausted.SummarizeCauses()` — bucket categories [`common/errors.go:L955-L1101`](https://github.com/erpc/erpc/blob/main/common/errors.go#L955-L1101). Iterates joined children and buckets into 19 categories. Category labels appended to error message as `"(N upstream X, M upstream Y)"`: | Category label | Codes detected | |---|---| | unsupported | `ErrCodeEndpointUnsupported` | | missing | `ErrCodeEndpointMissingData` | | rateLimit | `ErrCodeEndpointCapacityExceeded`, `ErrCodeUpstreamRateLimitRuleExceeded` | | billing | `ErrCodeEndpointBillingIssue` | | cbOpen | `ErrCodeFailsafeCircuitBreakerOpen` | | timeout | `context.DeadlineExceeded`, `ErrCodeEndpointRequestTimeout`, `ErrCodeNetworkRequestTimeout`, `ErrCodeFailsafeTimeoutExceeded` | | serverError | `ErrCodeEndpointServerSideException` | | cancelled | `ErrCodeUpstreamHedgeCancelled` | | client | `ErrCodeEndpointClientSideException`, `ErrCodeJsonRpcRequestUnmarshal`, `ErrCodeInvalidRequest`, `ErrCodeInvalidUrlPath` | | transport | `ErrCodeEndpointTransportFailure` | | unsynced | `ErrCodeUpstreamSyncing`, `ErrCodeUpstreamBlockUnavailable` | | excluded | `ErrCodeUpstreamExcludedByPolicy` | | nodeTypeMismatch | `ErrCodeUpstreamNodeTypeMismatch` | | ignores | `ErrCodeUpstreamMethodIgnored` | | skips | `ErrCodeUpstreamRequestSkipped` | | tooLarge | `ErrCodeEndpointRequestTooLarge`, `ErrCodeGetLogsExceededMaxAllowedRange`, `ErrCodeGetLogsExceededMaxAllowedAddresses`, `ErrCodeGetLogsExceededMaxAllowedTopics` | | auth | `ErrCodeEndpointUnauthorized` | | validation | `ErrCodeEndpointContentValidation` | | other | anything not matched above | ### `TranslateToJsonRpcException` — ordered translation steps Entry: [`common/json_rpc.go:L1501`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1501). Steps applied in order — first match wins: | Step | Input condition | Output code / behavior | |---|---|---| | 1 | `ErrUpstreamsExhausted` | Scan children for dominant code (highest count; `ErrCodeUpstreamRequestSkipped` and `ErrCodeEndpointUnsupported` excluded; earliest per code wins ties). Replace with dominant child. When NO children exist, translate `ErrUpstreamsExhausted` itself (→ −32603). When all children are skipped/unsupported, client sees the first child's code (typically −32601 or −32603). | | 2 | Chain already contains `ErrCodeJsonRpcExceptionInternal` | Return as-is (upstream-derived normalized code preserved). | | 3 | `ErrCodeAuthRateLimitRuleExceeded` / `ErrCodeProjectRateLimitRuleExceeded` / `ErrCodeNetworkRateLimitRuleExceeded` / `ErrCodeUpstreamRateLimitRuleExceeded` | −32005 CapacityExceeded, message `"rate-limit exceeded"` | | 4 | `ErrCodeAuthUnauthorized` | −32016 Unauthorized, message `"unauthorized"` | | 5 | `ErrCodeUpstreamMethodIgnored` | −32601 UnsupportedException, message `"method ignored by upstream: "` | | 6 | `ErrCodeJsonRpcRequestUnmarshal` | −32700 ParseException, message `"failed to parse json-rpc request"` | | 7 | `ErrCodeInvalidRequest` / `ErrCodeInvalidUrlPath` | −32602 InvalidArgument, message `"invalid request url and/or body"` | | 8 | `ErrCodeGetLogsExceededMaxAllowedRange` / `...Addresses` / `...Topics` | −32012 EvmLargeRange, message `"getLogs request exceeded max allowed range"` | | 9 | Fallback (anything else) | −32603 ServerSideException with deepest message | ### Helper predicates | Predicate | Returns false / behavior | Source | |---|---|---| | `HasErrorCode(err, codes...)` | Traverses StandardError cause chain AND joined multi-errors; a non-retryable code anywhere poisons the whole chain | [`common/errors.go:L2333-L2359`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2333-L2359) | | `IsCapacityIssue(err)` | Returns true for: `ErrCodeProjectRateLimitRuleExceeded`, `ErrCodeNetworkRateLimitRuleExceeded`, `ErrCodeUpstreamRateLimitRuleExceeded`, `ErrCodeAuthRateLimitRuleExceeded`, `ErrCodeEndpointCapacityExceeded` | [`common/errors.go:L2500-L2509`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2500-L2509) | | `IsClientError(err)` | Returns true for: `ErrCodeEndpointClientSideException`, `ErrCodeJsonRpcRequestUnmarshal`, `ErrCodeGetLogsExceededMaxAllowedRange`, `ErrCodeGetLogsExceededMaxAllowedAddresses`, `ErrCodeGetLogsExceededMaxAllowedTopics` | [`common/errors.go:L2511-L2520`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2511-L2520) | | `IsClientDisconnect(err)` | Returns true for `context.Canceled`, `context.DeadlineExceeded`, or error message containing: `"use of closed network connection"`, `"broken pipe"`, `"connection reset by peer"`, `"ECONNRESET"`, `"EPIPE"` | [`common/errors.go:L129-L150`](https://github.com/erpc/erpc/blob/main/common/errors.go#L129-L150) | | `IsRetryableTowardsUpstream(err)` | Returns false if `HasErrorCode` finds any of: `ErrCodeFailsafeCircuitBreakerOpen`, `ErrCodeUpstreamRequestSkipped`, `ErrCodeUpstreamMethodIgnored`, `ErrCodeEndpointUnsupported`, `ErrCodeEndpointBillingIssue`, `ErrCodeJsonRpcRequestUnmarshal`, `ErrCodeEndpointExecutionException`, `ErrCodeEndpointUnauthorized`, `ErrCodeEndpointRequestTooLarge`, `ErrCodeEndpointContentValidation`, or any `IsCapacityIssue` code. For `ErrUpstreamsExhausted` recurses over children — retryable iff ANY child is retryable. | [`common/errors.go:L2438-L2498`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2438-L2498) | ### Extractor plumbing | Component | Role | Source | |---|---|---| | `JsonRpcErrorExtractor` interface | Injects arch-specific normalization into HTTP clients; avoids import cycles | [`common/error_extractor.go:L10-L12`](https://github.com/erpc/erpc/blob/main/common/error_extractor.go#L10-L12) | | `JsonRpcErrorExtractorFunc` | `http.HandlerFunc`-style adapter | [`common/error_extractor.go:L17-L21`](https://github.com/erpc/erpc/blob/main/common/error_extractor.go#L17-L21) | | `evm.JsonRpcErrorExtractor` | EVM impl delegating to `ExtractJsonRpcError` | [`architecture/evm/extractor.go:L11-L17`](https://github.com/erpc/erpc/blob/main/architecture/evm/extractor.go#L11-L17) | | Injection site | `evm.NewJsonRpcErrorExtractor()` passed to client registry | [`upstream/registry.go:L79`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L79) | | HTTP invocation | `c.errorExtractor.Extract(r, nr, jr, c.upstream)` | [`clients/http_json_rpc_client.go:L930`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L930) | | gRPC invocation | `common.ExtractGrpcErrorFromGrpcStatus(st, c.upstream)` | [`clients/grpc_bds_client.go:L925`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L925) | | SVM HTTP invocation | `svm.JsonRpcErrorExtractor.Extract(resp, nr, jr, upstream)`; no-ops unless `upstream.Config().Type == svm` | [`architecture/svm/error_normalizer.go:L68-77`](https://github.com/erpc/erpc/blob/main/architecture/svm/error_normalizer.go#L68-L77) | | Vendor hook | `getVendorSpecificErrorIfAny` → `vn.GetVendorSpecificErrorIfAny(...)` fires BEFORE all generic rules | [`architecture/evm/error_normalizer.go:L878-L900`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L878-L900) | ### Worked examples **1. Diagnosing why a request exhausted all upstreams.** You see `erpc_network_failed_request_total` spike with `error="ErrUpstreamsExhausted/ErrEndpointRequestTimeout"`. The compound label (compact mode) tells you the inner code. Check `erpc_upstream_request_errors_total` filtered by `error` containing `Timeout` to see which upstream timed out most. Switch `metrics.errorLabelMode` to `"verbose"` temporarily in a staging environment to read the full message — never in production. **2. `eth_sendRawTransaction` returning `−32003` but the tx went through.** The normalizer sets N=yes for reverts and out-of-gas on `eth_sendRawTransaction` (rules 9 and 14). eRPC retried on a different upstream. The first upstream returned `ErrEndpointExecutionException` with code 3 (revert), which is kept and surfaced to the caller — this is expected behavior. Insufficient-funds stays N=no even for sendRawTransaction; no retry occurs in that case. **3. All upstreams returning `ErrEndpointMissingData` — request retried despite "exhausted".** `ErrUpstreamsExhausted` wrapping only missing-data children is still N=true (any retryable child makes the whole error retryable). Outer retry logic will try again. If data is genuinely absent from all nodes (e.g. pruned historical state), retry will keep failing — configure a dedicated archive upstream or catch `−32014` in your client. **4. Alert fires on `severity="warning"` for hedge discards.** `ErrUpstreamHedgeCancelled` is severity=warning. This is normal — it means a sibling hedge leg won the race. Alert only on `severity="critical"` in production; `warning` includes hedge discards and client disconnects that are expected at scale. **5. A Solana client sees `−32002` with populated `logs`.** That is the designed path, not a leak: the SVM extractor preserves the native code and forwards `error.data` verbatim, so `@solana/web3.js` recognizes `-32002` and raises `SendTransactionError` with `.logs` from the `RpcSimulateTransactionResult`. eRPC classes it `ErrEndpointClientSideException` with `retryableTowardNetwork=false`, so no second upstream is tried — the transaction, not the node, is the problem. **6. Two Solana upstreams disagree on the same slot.** One returns `−32004 BlockNotAvailable` (not propagated yet), the other `−32007 SlotSkipped` (permanently gone). The client deterministically sees `−32004`: `orderCauses` sorts retryable-toward-network causes ahead of terminal ones, and the dominant-code scan takes the first cause in the winning bucket. Reporting the terminal `−32007` could make an indexer permanently skip a slot that does exist; reporting the retryable `−32004` only costs a retry. **7. Every Solana upstream returns `−32009` and the client gets `−32009` after one pass.** `LongTermStorageSlotSkipped` says that this node's long-term storage does not hold the slot. Another provider's archive can, so eRPC asks each upstream once and then returns the error. A hedge leg or a retry does not ask an upstream that already answered `−32009` for this request, and no time-delayed re-sweep runs. Stop retrying in the client too. Contrast `−32019 LongTermStorageUnreachable`, which is a statement about *this node's* backend being down and stays retryable. **8. Solana `requestAirdrop` fails and is not retried.** `requestAirdrop` is in the SVM write-method guard because it **mints per call** — a failover after an effective first attempt mints twice. `sendTransaction`/`sendRawTransaction` are in the same set for a different reason: same-signature broadcasts are idempotent on-chain, so the risk is duplicate broadcasts burning vendor quota, not a double-spend. **9. A chain answers `is initializing; please retry shortly` forever.** That message is only correct while a bootstrap is in progress. Once a network has been in initialization for `upstream.NoUpstreamsAvailableAfter` (5 minutes) with **zero** upstreams registered, eRPC swaps it for `ErrNetworkNoUpstreamsAvailable` — `no RPC providers are available for network '' in project ''` on HTTP 404, and increments `erpc_network_no_upstreams_available_total{project,network}`. It means no configured upstream or provider covers that chain (removed from config, deprecated, or never supported), so retrying will not help; fix the config or provider coverage. The status is 404 rather than 5xx because the condition is a coverage gap, not a server fault — but it is still an operator-actionable state, so alert on `erpc_network_no_upstreams_available_total` rather than on wire 5xx. The initializer keeps re-attempting in the background, so a network that later gains an upstream recovers on its own. Past that threshold the verdict is immediate: the request does not wait out the 30s bootstrap budget first, even while an unrelated upstream task (one with no `evm.chainId`, such as a revoked API key) keeps failing. ### Best practices - Alert on `severity="critical"` only — `severity="info"` covers client errors and EVM reverts; `severity="warning"` covers hedge discards and client disconnects. - Keep `metrics.errorLabelMode` at `"compact"` in production. `"verbose"` creates a new Prometheus time series per unique error message and will exhaust memory. - When `ErrUpstreamsExhausted` appears in logs, check `SummarizeCauses` bucket in the message (e.g. `"2 upstream timeout, 1 upstream rateLimit"`) to identify the dominant failure mode before tuning retry or circuit-breaker config. - `ErrEndpointTransportFailure` strips endpoint URLs from cause messages — if you need the raw URL for debugging, check the upstream config or traces, not the error log. - `ErrUpstreamClientInitialization` is not fatal by default. If you see it at startup for an upstream that should have resolved (chain-ID mismatch, wrong type), check whether callers wrap it in `TaskFatalError` for permanent failures. - `ErrUpstreamRateLimitRuleExceeded` returns HTTP 200, not 429, on the wire. If your client is polling on 429 to detect upstream budget exhaustion, it will miss this case — filter on JSON-RPC code `−32005` instead. - For `eth_sendRawTransaction`, a `−32003` response may be a successful idempotent retry (nonce-duplicate or out-of-gas handled by normalizer rule 11/14). Check the `reason` field in error details (`already_known` vs `nonce_too_low`) to distinguish. ### Edge cases & gotchas 1. **`ErrUpstreamsExhausted` with NO cause is terminal (N=false).** An exhausted error wrapping zero children means no upstream was tried; retrying at network scope cannot make progress. Source: [`common/errors.go:L2393-L2394`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2393-L2394) 2. **All-missing-data exhausted IS retryable.** `ErrUpstreamsExhausted` wrapping only `ErrEndpointMissingData` children is N=true because any retryable child makes the whole exhausted error retryable. Source: [`common/errors_retry_test.go:L51-L74`](https://github.com/erpc/erpc/blob/main/common/errors_retry_test.go#L51-L74) 3. **`ErrEndpointExecutionException` is N=false — except `eth_sendRawTransaction` reverts.** The normalizer overrides N=yes for `eth_sendRawTransaction` reverts and out-of-gas (rules 9 and 14). Insufficient-funds (rule 13) does NOT get the override. Source: [`architecture/evm/error_normalizer.go:L263-L272`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L263-L272) 4. **`ErrEndpointClientSideException` is N=true by default.** Only rules 17 (malformed tx), 18d (invalid params), and gRPC/BDS `InvalidArgument` set N=false. Rule 6 (block-tag-unsupported) deliberately keeps N=true to allow other upstreams to attempt the tag. Source: [`common/errors_retry_test.go:L175-L187`](https://github.com/erpc/erpc/blob/main/common/errors_retry_test.go#L175-L187) 5. **`ErrUpstreamRateLimitRuleExceeded` returns 200 on the wire.** It is NOT in the wire 429 switch despite its `ErrorStatusCode()` returning 429. Source: [`erpc/http_server.go:L1484-L1490`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1484-L1490) 6. **OP-stack "sender is over rate limit" is capacity-exceeded but N=false.** All eRPC provider entries proxy the same OP sequencer; retrying on a different provider hits the same limit. All other `ErrEndpointCapacityExceeded` are N=true. Source: [`architecture/evm/error_normalizer.go:L125-L139`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L125-L139) 7. **Nonce-duplicate detection must run before generic −32003.** Some vendors use −32003 for "already known"/"nonce too low". Rules 11/12 appear before rule 14 in the normalizer. "Replacement transaction underpriced" is never an idempotent success; rule 12b treats it as a node-local refusal. Source: [`architecture/evm/error_normalizer.go:L297-L301`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L297-L301) 8. **200-OK revert detection checks `dt[1:11]`.** Index 0 is the JSON quote character; the ABI selector `0x08c379a0` starts at index 1. Source: [`architecture/evm/error_normalizer.go:L609-L624`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L609-L624) 9. **Trace/debug timeout detection scans raw bytes.** Rule 22 does a raw string search to avoid parsing up to ~50MB trace responses. Source: [`architecture/evm/error_normalizer.go:L626-L629`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L626-L629) 10. **`buildErrorResponseBody` unwraps single-child exhausted.** When exactly one upstream tried, the wrapper is removed and clients see the real upstream error. Source: [`erpc/http_server.go:L1397-L1403`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1397-L1403) 11. **Compact `ErrorSummary` compound labels are not universal.** Only `ErrFailsafeRetryExceeded`, `ErrUpstreamRequest`, and `ErrUpstreamRequestSkipped` produce `OuterCode/InnerCode` labels. `ErrFailsafeTimeoutExceeded` does NOT compound even with a cause. Source: [`common/errors_summary_test.go:L24-L30`](https://github.com/erpc/erpc/blob/main/common/errors_summary_test.go#L24-L30) 12. **`ErrDynamicTimeoutExceeded` distinguishes failsafe from HTTP deadline.** Set as `context.WithTimeoutCause` cause by the timeout policy. `context.Cause(ctx) == ErrDynamicTimeoutExceeded` tells you the failsafe policy fired, not the HTTP server's global deadline. Source: [`common/errors.go:L1981-L1984`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1981-L1984) 13. **`TranslateToJsonRpcException` skips `UpstreamRequestSkipped` and `EndpointUnsupported` when counting dominant error.** When all upstreams returned one of these codes, the first child's wire code is used (typically −32601 or −32603). Source: [`common/json_rpc.go:L1523-L1526`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1523-L1526) 14. **BDS gRPC legacy extractor diverges from live path.** `evm.ExtractGrpcError` (no call sites) maps `TIMEOUT_ERROR`/`DeadlineExceeded` to `ErrEndpointServerSideException`; live `common.ExtractGrpcErrorFromGrpcStatus` maps both to `ErrEndpointRequestTimeout`. If the legacy function is ever restored, BDS timeout retry behavior will regress. 15. **`ErrConsensusDispute` and `ErrConsensusLowParticipants` retryability follows the any-child rule.** Both aggregate per-upstream participant errors via `errors.Join`. If ANY single child is retryable, the consensus error is retryable network-wide. Source: [`common/errors.go:L2397-L2411`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2397-L2411) 16. **`ErrEndpointClientSideException.ErrorStatusCode()` returns 200 for revert-class causes.** When the inner `ErrJsonRpcExceptionInternal` has `normalizedCode` of `3` (`JsonRpcErrorEvmReverted`), `-32000` (`JsonRpcErrorCallException`), or `-32003` (`JsonRpcErrorTransactionRejected`), the method returns 200 rather than 400 — an EVM revert is a valid execution outcome. Note that `ErrorStatusCode()` is dead code (zero call sites), but the wire behavior is consistent: `determineResponseStatusCode`/`handleErrorResponse` always return 200 for these cases via the default switch branch. Source: [`common/errors.go:L1894-L1905`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1894-L1905) 17. **Legacy `evm.ExtractGrpcError` (dead code) has no `Canceled` branch.** The live `common.ExtractGrpcErrorFromGrpcStatus` maps gRPC `Canceled` to `ErrEndpointRequestCanceled`; the dead legacy function falls through to the default `ErrEndpointServerSideException` case. Additionally, the legacy function maps both BDS `TIMEOUT_ERROR` and gRPC `DeadlineExceeded` to `ErrEndpointServerSideException` (live path maps both to `ErrEndpointRequestTimeout`). If the legacy function is ever restored, BDS/gRPC timeout and cancellation retry behavior will regress. Source: [`architecture/evm/error_normalizer.go:L660-L876`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L660-L876) vs [`common/grpc_errors.go:L86-L97`](https://github.com/erpc/erpc/blob/main/common/grpc_errors.go#L86-L97) 18. **`buildErrorResponseBody` sets `error.data` only under two conditions.** The `data` field is included only when `includeErrorDetails` is true AND the method is NOT `eth_call`. For `eth_call`, the revert data is intentionally suppressed in the top-level error body. Source: [`erpc/http_server.go:L1425-L1433`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1425-L1433) 19. **`ErrJsonRpcExceptionInternal` prefixes its `CodeChain()` with the numeric normalized code.** The overridden `CodeChain()` produces `" <- ErrJsonRpcExceptionInternal"` (e.g. `"-32014 <- ErrJsonRpcExceptionInternal"`). `NormalizedCode()` returns `details["normalizedCode"]` as a `JsonRpcErrorNumber`; `OriginalCode()` handles both `int` and `float64` types (JSON round-trip issue). Source: [`common/errors.go:L2202-L2222`](https://github.com/erpc/erpc/blob/main/common/errors.go#L2202-L2222) 20. **On an SVM path, `−32005` and `−32016` always mean the agave semantic.** They collide with eRPC's own `CapacityExceeded` and `Unauthorized` constants, so the invariant is that eRPC never *synthesizes* either number on an SVM path: a `-32005` is `NodeUnhealthy` (with `data.numSlotsBehind`), a `-32016` is `MinContextSlotNotReached`. eRPC's capacity verdict arrives as HTTP 429 with wire code `-32000`, and its auth verdict as HTTP 401/403 with `-32600`. 21. **SVM `ErrEndpointClientSideException` is N=false, unlike EVM's.** The SVM extractor calls `WithRetryableTowardNetwork(false)` explicitly on every client-side branch, scoping the opt-out to SVM. EVM's `ClientSideException` remains N=true by default. 22. **`permanent` does not mean `terminal` on SVM missing-data errors.** `-32007` and `-32009` are both permanent but retryable: eRPC asks every provider once per client request, then stops (no time-delayed re-sweep, because waiting cannot un-skip a slot). `failedPermanentlyLocked` counts a permanent missing-data verdict as final for that upstream, so a hedge leg or a retry does not re-ask it, and `AllUpstreamsFailedPermanently` ends the request when every selected upstream has given one ([`common/request.go:L1728-1742`](https://github.com/erpc/erpc/blob/main/common/request.go#L1728-L1742)). The permanent flag lives on each individual cause, never on the `ErrUpstreamsExhausted` wrapper — the predicate stops before entering a multi-error fan-out, so the wrapper reports `false` even when every child is permanent. 23. **HTTP 401/403 outranks an SVM JSON-RPC error body.** Helius and QuickNode return 401/403 *with* an error object; classifying from the body first sent expired API keys down whichever generic path their code happened to map to. The status wins, and the codeless fallback is deliberately `-32600` rather than eRPC's `-32016`, which an SVM client would decode as `MinContextSlotNotReached` and retry forever instead of fixing the key. 24. **`simulateTransaction` is retryable and hedgeable on SVM.** It is read-only, so it is deliberately excluded from the SVM write-method guard — but it is still in `neverCacheMethods`, so it is never served from cache. 25. **The HyperEVM precompile-state reply is missing data, not out of gas.** A HyperEVM read precompile (`0x…0800` onwards) needs HyperCore state for the requested block. Many nodes hold it only for their live tip and answer older blocks with `-32003 "out of gas: gas exhausted during precompiled contract execution: "`, while other nodes answer the same call. Rule 7b maps that wording to `ErrEndpointMissingData`, so the sweep moves on to the next upstream. If every upstream lacks the state, the client gets `-32014` with the node's message verbatim. A contract that calls the precompile through a library which catches the failure and reverts with its own error (for example `PrecompileLib__SpotBalancePrecompileFailed()`) produces a plain `execution reverted`, which stays rule 9. `eth_sendRawTransaction` keeps rule 14. Confirmed by `TestNetworkForward_PrecompileStateGap_FailsOverToUpstreamWithState` and `TestHttpServer_PrecompileStateGap_AllUpstreamsLackStateSurfacesNodeMessage`. 26. **`gas required exceeds allowance` is final, not a server fault.** go-ethereum's gas estimator (`eth/gasestimator`) answers `eth_estimateGas` with `-32000 "gas required exceeds allowance (N)"` when the call still runs out of gas at its cap N, most often a sender whose balance buys only N gas. Arbitrum nitro nodes return it (nitro carries the estimator in its go-ethereum fork); other go-ethereum-derived clients may too. Rule 14 maps it to `ErrEndpointExecutionException`, so one upstream answers and the client gets the node's message with code `-32003` (the code rule 14 gives "out of gas" too). Before, it fell through to rule 20: the estimate was sent to every upstream and the client got `ErrUpstreamsExhausted`. A node's own RPC gas cap setting can also produce it; like "out of gas", it is not retried for that reason. Confirmed by `TestExtractJsonRpcError_GasRequiredExceedsAllowance`. 27. **`invalid chain id` is final, even for writes.** A transaction signed for another chain (`eth_estimateGas`, `eth_sendRawTransaction`) fails the same way on every correctly configured upstream. Rule 14b maps it to `ErrEndpointExecutionException` and, unlike rule 14, does not make it retryable for `eth_sendRawTransaction`, so the client gets the node's message after one upstream. Before, it fell through to rule 20: every upstream was tried and the client got `ErrUpstreamsExhausted`. Confirmed by `TestExtractJsonRpcError_InvalidChainID`. 28. **`exceeds block gas limit` is final, even for writes.** go-ethereum's txpool answers it when a transaction's gas limit is above the block gas limit; the block gas limit is consensus state, so every upstream refuses the same transaction. Rule 14c maps it to `ErrEndpointExecutionException`, not retryable even for `eth_sendRawTransaction`. Before, it fell through to rule 20: a broadcast with retry and hedge asked every upstream again and again until the retry budget ran out, and the client got `ErrFailsafeRetryExceeded` after seconds instead of the node's message. Confirmed by `TestExtractJsonRpcError_ExceedsBlockGasLimit` and `TestNetwork_SendRawTransaction_FireAndForget/ExceedsBlockGasLimitIsNotRetried`. 29. **`underpriced` gets one try per upstream.** "transaction underpriced" (below the node's minimum gas price) and "replacement transaction underpriced" (fee bump too small for the transaction in that node's pool) depend on node-local policy and pool contents, so rule 12b keeps `eth_sendRawTransaction` failover to other upstreams but never asks the refusing upstream again. Once every upstream has refused, the broadcast ends and the client gets the node's message. Before, they fell through to rule 20 and were retried on the same upstreams until the retry budget ran out (`ErrFailsafeRetryExceeded`). Confirmed by `TestExtractJsonRpcError_Underpriced` and `TestNetwork_SendRawTransaction_FireAndForget/UnderpricedFromEveryUpstreamIsNotRetried`. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_errors_total` | counter | project, vendor, network, upstream, category, **error**, **severity**, composite, finality, user, agent_name | Each upstream attempt returning an error; `error` label = `ErrorFingerprint(err)` | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, **error**, **severity**, finality, user, agent_name | Request failed at network/project level | | `erpc_cache_set_error_total` | counter | project, network, category, connector, policy, ttl, **error** | Cache set errored | | `erpc_cache_get_error_total` | counter | project, network, category, connector, policy, ttl, **error** | Cache get errored | | `erpc_unexpected_panic_total` | counter | scope, extra, **error** | Recovered panic | Alert on `severity="critical"` only. `severity="info"` covers client errors and EVM reverts; `severity="warning"` covers hedge discards and client disconnects. **Tracing.** `common.ErrorSummary(err)` is used as the OTel span status description on error. The `error.summary` span attribute is set in failsafe operations. Cache errors set `cache.error` / `cache.connector_error` span attributes. gRPC send errors set a `grpc.send_error` attribute. Source: [`common/tracing_core.go:L181`](https://github.com/erpc/erpc/blob/main/common/tracing_core.go#L181), [`data/failsafe.go:L240`](https://github.com/erpc/erpc/blob/main/data/failsafe.go#L240) ### Source code entry points - [`common/errors.go:L1-L2800`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1) — Complete error type definitions, all `ErrCode*` constants, retryability predicates, severity classification, `ErrorSummary`, `ErrorFingerprint`, `HasErrorCode`, `IsClientDisconnect`, `TaskFatalError`, `ErrDynamicTimeoutExceeded`, `JsonRpcErrorNumber` constants - [`architecture/evm/error_normalizer.go:L20-L658`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L20-L658) — `ExtractJsonRpcError`: all 22 generic HTTP normalization rules in order; vendor hook dispatch at L29-L31 - [`architecture/svm/error_normalizer.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/error_normalizer.go) — `JsonRpcErrorExtractor.Extract`: the full SVM code map, `wireCode` native-code preservation and the eRPC/Solana collision note, `error.data` passthrough, `isRateLimitMessage`, `newAuthoritativeMissingData`, `newSweptSkipMissingData` - [`architecture/svm/util.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/util.go) — `IsNonRetryableWriteMethod` (SVM): `sendTransaction`, `sendRawTransaction`, `requestAirdrop` - [`common/errors.go` — `orderCauses`](https://github.com/erpc/erpc/blob/main/common/errors.go) — the deterministic total order over exhausted causes (retryable before terminal, then upstream id) - [`common/grpc_errors.go:L12-L225`](https://github.com/erpc/erpc/blob/main/common/grpc_errors.go#L12-L225) — Live gRPC/BDS error normalization; BDS code priority then gRPC code fallback - [`common/json_rpc.go:L1501-L1630`](https://github.com/erpc/erpc/blob/main/common/json_rpc.go#L1501-L1630) — `TranslateToJsonRpcException`: internal error → wire JSON-RPC numeric code; dominant-child selection for `ErrUpstreamsExhausted` - [`erpc/http_server.go:L1280-L1491`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1280-L1491) — `determineResponseStatusCode`, `buildErrorResponseBody`, `handleErrorResponse`; the only two places that actually set wire HTTP status - [`architecture/evm/util.go:L7-L49`](https://github.com/erpc/erpc/blob/main/architecture/evm/util.go#L7-L49) — `IsNonRetryableWriteMethod`; `IsMissingDataError` patterns for rule 7 - [`common/config.go:L2536-L2550`](https://github.com/erpc/erpc/blob/main/common/config.go#L2536-L2550) — `LabelMode` type, `ErrorLabelModeVerbose`/`ErrorLabelModeCompact` constants, `MetricsConfig.ErrorLabelMode` field - [`common/errors_retry_test.go`](https://github.com/erpc/erpc/blob/main/common/errors_retry_test.go) — Tests for `IsRetryableTowardNetwork`/`IsRetryableTowardsUpstream`/`HasErrorCode` behavioral invariants ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — retryability flags in this table drive retry decisions. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — `ErrFailsafeCircuitBreakerOpen` and capacity errors feed circuit scoring. - [Hedge](/config/failsafe/hedge.llms.txt) — `ErrUpstreamHedgeCancelled` is the discard signal for losing hedge legs. - [Rate limiters](/config/rate-limiters.llms.txt) — `ErrUpstreamRateLimitRuleExceeded` / `ErrEndpointCapacityExceeded` are the rate-limit error types. - [Auth](/config/auth.llms.txt) — `ErrAuthUnauthorized` / `ErrAuthRateLimitRuleExceeded` are auth-layer errors. - [SVM commitment & finality](/reference/svm/commitment.llms.txt) — where `-32016` comes from and how the `minContextSlot` pre-filter tries to avoid it. - [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) — the guard that turns an unindexed `getBlock` into the `-32004` family without an upstream call. --- --- # Block tracking & served tip > Source: https://docs.erpc.cloud/reference/evm/block-tracking > eRPC keeps a live pulse on every upstream's chain head and finality, then distills a single honest block number your clients can trust — with no "block not found" surprises. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Block tracking & served tip Every upstream sees the chain at a slightly different block. Without coordination, routing a request to the one node that is a block behind causes silent "block not found" failures. eRPC polls every upstream continuously and advertises one **served tip** per axis (`latest`, `finalized`): the highest block at least `servedTip.quorum` (default 2) eligible upstreams already have. **What you get** - Chain head and finality tracked per upstream, refreshed automatically at the right cadence for each chain's block time - One rule for every config: a block is served only once a quorum of upstreams has it — a lone far-ahead or wrong-chain node never defines `latest` - Stalled heads benched automatically, so one frozen node cannot hold `latest` back - `finalized` never steps back while an upstream still reports the block already served, even when a lagging group of upstreams becomes the quorum; replicas sharing state serve the highest one any of them served - Optional per-group guarantee so the advertised tip stays servable by the upstreams your consensus policy requires - Per-upstream lag gauges that feed selection policies so slow nodes are deprioritized before requests reach them - Redis-backed counters share heads across replicas; each replica samples latest-block timestamps on its own debounce schedule. ## Quick taste Illustrative, not a tuned production config — require a strict majority of upstreams instead of the default 2: **Config path:** `projects[].networks[].evm.servedTip` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 1 servedTip: # serve the highest block a strict majority of upstreams has quorum: majority ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1, servedTip: { // serve the highest block a strict majority of upstreams has quorum: "majority", }, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: eliminate block-not-found errors across my upstream fleet** ```text My app gets occasional "block not found" errors right after a new block is produced because some upstreams lag behind. Set servedTip.quorum in my eRPC config so eRPC only advertises a block number enough upstreams actually have, and explain when a stalled upstream gets benched out of the ballot. Read the full reference first: https://docs.erpc.cloud/reference/evm/block-tracking.llms.txt ``` **Prompt Example #2: tune block polling for a fast chain like Arbitrum** ```text I'm running eRPC against Arbitrum (250ms block time) and want block tracking tight from the first second after startup. Adjust the polling and debounce settings in my eRPC config so the EMA warms up quickly and block tracking stays tight. Reference: https://docs.erpc.cloud/reference/evm/block-tracking.llms.txt ``` **Prompt Example #3: set up guaranteed-method floor for a mixed trace fleet** ```text My eRPC pool mixes trace-capable archive nodes with cheaper non-archive upstreams. Without a floor, the served tip can advance to a block that only the non-archive nodes have, causing trace_block requests to hit "block not found". Configure guaranteedMethods in my eRPC config and explain how the method floor interacts with the quorum. Reference: https://docs.erpc.cloud/reference/evm/block-tracking.llms.txt ``` --- ### Block tracking & served tip — full agent reference ### How it works Each upstream gets its own `EvmStatePoller` background goroutine. On each tick of `statePollerInterval` (default 30 s), three concurrent goroutines fetch the latest block, finalized block, and syncing state. A synchronous `Poll()` runs once at bootstrap time to seed the upstream before any request traffic arrives. Remote head updates do not postpone local latest-block sampling. A local fetch can attach a missing timestamp to the same block already received from a peer. The block-time estimator accepts that matched observation without advancing the head again. Latest-block polling cost scales with replica count. **Routing the `safe` tag.** On op-stack chains, `safe` is node-relative because each verifier chooses its own L1 confirmation depth. If providers in one pool use different depths, they can honestly return different blocks for the same tag. Set `evm.safeBlockSource` to an upstream id/tag selector when one pool should define that answer: ```yaml networks: - architecture: evm evm: chainId: 8453 safeBlockSource: "tier:trusted" upstreams: - id: node-a tags: ["tier:trusted"] - id: node-b tags: ["tier:trusted"] - id: provider-a ``` eRPC keeps the `safe` tag verbatim and routes standard block-tagged JSON-RPC requests only to matching upstreams, so the selected pool defines both block height and hash. Cache reads are skipped because an older entry may have been produced by a different source. Operator routing overrides client `use-upstream`; retry and consensus still run inside the selected JSON-RPC pool, so configure participant thresholds accordingly. `eth_query*` and direct gRPC Query APIs retain their existing behavior and are outside this option's scope. If no source is configured or inherited, routing is unchanged. If trusted sources are unavailable, prefer `finalized` for a provider-independent answer. **Debounce resolution.** To avoid redundant RPC calls, each fetch is gated by `resolveDebounce()`, which picks the first applicable value from: 1. `upstream.evm.statePollerDebounce` — hard per-upstream override; short-circuits all other steps. 2. `tracker.GetNetworkBlockTime × dynamicBlockTimeDebounceMultiplier` (default 0.7) — set by the first block-time sample, which needs 2 timestamp changes after the first observed header. 3. `network.evm.fallbackStatePollerDebounce` (no default) — when set, used until step 2 applies. 4. The 1 s cold block time × the multiplier (0.7 s) — until step 2 applies. On a 12 s Ethereum Mainnet chain this yields ~8.4 s debounce — fresh enough to catch every block, conservative enough that concurrent pollers share one actual RPC call per window. In Redis-backed multi-pod deployments, the shared counter coalesces fetches across replicas too. **Finalized debounce.** The finalized fetch widens that debounce to `(latest − finalized) × EMA block time × finalizedDebounceDepthMultiplier` (default 0.05) when this is longer, using the upstream's own latest and finalized blocks. Finalized advances once per finality window, so polling it at the latest-block cadence mostly returns the number already held. With the default the finalized block trails by at most about 5% of the window: ~43 s on Ethereum Mainnet (~72 blocks × 12 s), ~45 s on an Arbitrum-style L2 with a 15 min window. An upstream behind the network's corroborated finalized block (second-highest across upstreams) keeps the regular debounce until it catches up: once a peer sees the next finalized block, the others sample it at the regular cadence. This also covers vendors whose load balancer mixes stale and fresh backends. Chains with near-instant finality (depth of a few blocks) keep the regular debounce. Unknown finalized, latest at or below finalized, or a cold EMA also keep it. Source: [`architecture/evm/evm_state_poller.go:L449-471`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L449-L471) **Dynamic block-time EMA.** The EMA (`alpha = 0.1`, ~19-sample effective window) lives in `health.Tracker` and updates whenever the corroborated network-level latest block advances, using the on-chain timestamp of the upstream report that holds that head (each upstream's latest timestamp is stored beside its head, so the sample comes from whichever poller reported the block). All head publication for a network is serialized under one per-network lock, so a slow re-derivation can never overwrite a newer one. Source headers (pushes and poll-source polls) sample it too, once the network's confirmed head reaches them, so a lagging or bogus header is no sample. A sample spans two observations whose timestamps differ: seconds elapsed over blocks elapsed; blocks that share a timestamp extend the span. Spans start at the first timestamp change after the first observation, so the first sample needs 2 timestamp changes after it, and seeds the EMA. A sample above 3× the EMA counts as 3× the EMA, so one span across a chain halt never sets W to its 60 s cap; values outside `[10 ms, 120 s]` are rejected. `GetNetworkBlockTime` returns 0 until the first sample; the chain tracker's W and the poll cadence use the 1 s cold block time meanwhile (poll cadence 0.7 s). **Per-upstream block counters.** Both `latestBlockShared` and `finalizedBlockShared` are forward-only shared counters: `TryUpdate` rejects values ≤ the current value. A value more than 1024 blocks lower applies only once the lower side moves: a later reading above the first lower one, with no reading near the counter in between. Applied, it fires an `OnLargeRollback` callback and records `erpc_upstream_block_head_large_rollback`. A provider that sometimes answers from a node stuck far behind repeats one value, so its drops never reach `latest` or `finalized`; a real deep reorg or a chain restarted lower applies one reading later, and lower readings alone for 5 minutes apply too. **Network head and `blockHeadLag` / `finalizationLag`.** The tracker's network-level latest and finalized heads are *corroborated*: the second-highest head across the non-benched reporting upstreams, or the only head while a single one has reported (the same order statistic as the served tip's default quorum). When every reporter is benched it falls back to all of them. One upstream can therefore never move the reference every other upstream is measured against — a lone far-ahead report (an endpoint answering for another chain, a corrupted response) is not corroborated, and a benched (stalled) upstream cannot hold the head back. With exactly two reporters the head is the lower one, so a lone high report and a lone stale report are indistinguishable there; per-upstream block-availability checks still gate block-specific requests. The reporting set is every upstream that has reported a latest or finalized head to the tracker. `blockHeadLag = max(0, network_latest − presumed_latest)`; `finalizationLag = max(0, network_finalized − presumed_finalized)`. An upstream's presumed head is its last reported head plus what the network head made since that report, counted for at most one poll period (`max(statePollerInterval, statePollerDebounce or the block time)`): within the period its lag stays what it was at the report, because a stored head ages between polls by design. Without this, an upstream polled every 10s on a 0.4s chain read up to 25 blocks behind late in each poll window, and a selection policy ticking at the same period read the same phase on every tick, excluding a healthy upstream for good on some processes. Past the period the credit freezes, so a missing report counts as lag again; a benched head gets no credit. Both are recomputed on every `SetLatestBlockNumber` / `SetFinalizedBlockNumber` call and exposed as Prometheus gauges; the raw per-upstream `erpc_upstream_latest_block_number` still shows an outlier's own report. These drive selection-policy predicates such as `blockNumberLagAbove`. Source: [`health/tracker.go:L1468-1519`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1468-L1519) #### One view (latest) `latest` is one view per lane, `{Head, Firm}`, published by the lane's chain tracker as one pointer. HTTP reads (`eth_blockNumber`, an interpolated `latest`, cache keys) and every stream (ws `newHeads`, ws `logs`, gRPC `StreamBlocks`) read that one state, so they never show two heads. - **Head:** the highest pinned block (parent-hash linked) that at least one counted hash vote holds, undisputed, at most each guarantee subset's floor. It only moves back when the pins move (a reorg), which streams replay as a proper reorg. - **Undisputed:** no hash voter votes another branch at that height, unless `servedTip.quorum` voters on the pinned branch outnumber it: one upstream on a minority fork never holds the view back. - **Firm:** the highest block at or below `Head` that `servedTip.quorum` voters hold. It decides routing: a block above `Firm` goes to its holders first. - **Held:** a block above `Firm` that the view pins exists, so a request for it asks no upstream for its head, even where a method only some upstreams serve keeps that method's `latest` below it. Its first attempt and its one retry go to the upstream that most likely holds it soonest, by the block's first sight plus that upstream's measured hold time, and wait for it, at most W. Each answer is a new measurement, and no head fetch is sent for it. - **Block clock:** while a stream needs heads, or a `latest` read came within 2 W, the tracker spends the voters' poll turns at the times each block may arrive. A voter's `statePollerInterval` is its read budget: it takes at most one turn per block and per interval, and its full poll skips the latest fetch the turn made. The turns form a ladder across the block's arrival spread; the first sight stops it, and the turns not sent fetch at once as hash votes. With no turn due, the fastest voter fetches once per block. Budget: at most max(1, Σ min(1, block time / interval)) + 0.05 head fetches per new block. A wss `newHeads` push skips the ladder. - **Idle edge:** the first `latest` read after that fetches `servedTip.quorum` voters at once; tag reads wait until the view reaches the fetched head (at most W); `eth_blockNumber` never waits: it answers the view at once. #### Served tip Both axes but `latest`'s number, every config. `Network.EvmHead` returns one `Head` per request: `Latest` and `LatestHash` from the view above; `Finalized`, `Leader` and the ceiling from `computeHead`, when an upstream head, a bench or the eligible set changes, and every 1s. Each of these runs one pipeline: 1. **Candidates** (`tipCandidates`): the selection policy's eligible upstreams in routing order (all registered upstreams until the policy's first decision), narrowed to the request's `use-upstream` selector when present and to the upstreams that serve the request's method (`ignoreMethods`/`allowMethods`, the filter routing applies; all of them when none does). An upstream that does not serve the method never raises the block a request is pinned to. `eth_blockNumber` keeps every voter: it reports the view's `Head`. 2. **Voter rank** (`tipVoterRank`): each candidate with a head on the axis ranks live 0, benched 1, static cap 2, benched static cap 3. A static cap is a `blockAvailability.upper.exactBlock` the chain has passed: a serving range, not a head observation (`latestBlockMinus` upstreams are live). A candidate that is syncing per `eth_syncing`, has no state poller, has no head yet or is on a minority fork casts no number vote. 3. **Ballot** (`evmTipBallot`): only the heads of the best voter rank present vote. A benched head votes only when no non-benched live head exists; a static cap only when no live head exists. One voter set (`voterSet`) applies these rules for the ballots, `Leader`, the refresh, catch-up and band Asks, the hash voters and topic admission; a hash vote keeps a voter on a minority fork, and topic admission also keeps a poller with no head yet. 4. **Pick** (`PickServedTip`): the highest block at least `servedTip.quorum` voters already have — the q-th highest head, or the lowest when fewer than q vote. 5. The [regression guard](#regression-guard), then the [guarantee floors](#guarantee-subsets), then the [finalized floor](#finalized-floor) (`finalized` only). The result is the value served, recorded on the request's [lane](#selector-scoped-served-tip) and [exported as gauges](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking). The network-wide lane is also evaluated every second, both axes, so its gauges, advance age and guard memory stay current on a network with little traffic; use-upstream lanes are evaluated only by their requests. Only the network-wide [finalized floor](#finalized-floor) is shared; nothing is predicted. Source: [`erpc/networks.go:L870-942`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L870-L942), [`erpc/networks.go:L430-506`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L430-L506), [`common/served_tip.go:L112-157`](https://github.com/erpc/erpc/blob/main/common/served_tip.go#L112-L157), [`erpc/networks_served_tip_refresh.go:L9-42`](https://github.com/erpc/erpc/blob/main/erpc/networks_served_tip_refresh.go#L9-L42) **Quorum.** `servedTip.quorum` is an integer ≥ 1 or `"majority"` (`floor(N/2)+1` of N voters), capped at N ([config](/config/projects/networks.llms.txt#config-schema)). Which head is served (heads sorted descending): | Voters N | `quorum: 2` (default) | `quorum: majority` | `quorum: 1` | |---|---|---|---| | 1 | 1st | 1st | 1st | | 2 | 2nd | 2nd | 1st | | 3 | 2nd | 2nd | 1st | | 4 | 2nd | 3rd | 1st | | 5 | 2nd | 3rd | 1st | `quorum: 1` serves the highest head, so a single upstream defines `latest`. A higher quorum trades freshness for servability: more upstreams already have the advertised block. Source: [`common/served_tip.go:L36-56`](https://github.com/erpc/erpc/blob/main/common/served_tip.go#L36-L56) #### Benching The health tracker re-evaluates every reporter on each latest-head report (`evaluateHeadBench`). An upstream is *behind* while a non-benched peer proves the chain went on without it (`headIsBehind`): - **By height:** a peer that moved after the upstream last moved is higher by no more than a plausible lead: 1024 blocks plus twice the blocks the chain produced since the upstream's head was current (by its last change and its head timestamp). Chain progress uses the network block time, else the peer's own, so a process that starts mid-stall still sees the stall. One such peer is enough. Each move of the upstream resets this rule. - **By staleness:** a peer that moved within its own or the upstream's stall window is higher within the plausible lead, and its newest block (never counted as newer than now) is at least the stall window younger than the upstream's head block. This holds while the upstream moves, so it catches a node replaying far behind the tip: after a restore, a restart or a deep rollback. One such peer is enough. Only the upstream's own head timestamp proves it stale: a head stored without one (a peer pod's poll through shared state) keeps the last verdict only while a live peer stays a stall window of blocks ahead. A node at the tip has a head block as young as any honest peer's, so a node that trails by less than the stall window of chain time is never benched. - **By block age:** a peer that moved after the upstream last moved has a newest block at least the stall window younger than the upstream's head block, whatever the heights. This catches a head frozen above a chain that restarted lower (a dead fork), a static far-ahead head, and an endpoint that serves another, slower chain under the same chain id. It takes two such peers while two exist. Behind without a break for its stall window (`headStallAfter`), `max(30s, 3 × max(statePollerInterval, statePollerDebounce or the block time))`, it is benched: its voter rank drops to benched and it leaves the lag reference. Its `blockHeadLag` keeps growing so `blockNumberLagAbove` routes around it: while its head has not moved since the bench (`movedSinceBench`), the head counts as no higher than the network head at the bench (a head frozen above a dead fork lags by what the network made since, even after the network passes its height); once it moves again, it lags by its real distance. It rejoins once it has moved since being benched (a move in the evaluation that benched it does not count), no rule above still proves it behind, and its head reached the corroborated non-benched head (second-highest, or the only one); or when no non-benched peer has a head. A voter at or above that head never lowers `latest`, and a lone far-ahead head cannot keep it out. A bench or rejoin also re-derives the finalized lag reference. Stall windows run on the monotonic clock, so a wall-clock step benches nobody. Each bench increments `erpc_upstream_head_benched_total` and logs a WARN. Bench state is per process. Source: [`health/tracker.go:L1463-1653`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1463-L1653) - **Nobody is benched** for a chain halt itself (no peer moves; a node already a stall window behind when the chain halted is benched like any trailing node), by a moving wrong-chain head above (its lead is implausible), or by one wrong-chain peer whose blocks are younger (the block-age rule needs two). - **Boundary:** a node that trails by less than the stall window of chain time (for example, 1-3 blocks on a 2s chain) is never benched. It votes with its lower head, which holds the pick back only when it is needed for the quorum (N=2 with the default quorum). `quorum: 1` serves the highest head instead. - **Boundary:** eRPC compares heights and block times, never block hashes, so it cannot tell a live fork from the canonical chain. During a halt, a node that moves within the plausible lead benches the halted ones after their stall window, and then defines `latest` alone. A benched dead-fork node that starts producing blocks again rejoins once its head reaches the corroborated head. - **Boundary:** the block-age rule cannot tell two heads frozen above one moving peer (a dead fork the minority left) from two halted honest nodes and one wrong-chain peer. It keeps the frozen pair, so a dead fork that most upstreams stayed on still defines `latest`. - **Boundary:** two chains under one chain id (an endpoint pointed at the wrong chain) differ by far more than any plausible lead, so only block age tells them apart. Until the slower chain goes twice its stall window without a block, quorum 2 over the pair serves the lower head; then the slower chain is benched, right or wrong. A wrong chain that makes blocks more often than that is never benched. Exclude such an endpoint in config. - **Boundary:** benching a voter that sat between the pick and a slower voter lowers `latest` to that slower voter's head, as any upstream leaving the ballot does. The regression guard holds only drops beyond `maxRegressionBlocks`; `finalized` holds at the [finalized floor](#finalized-floor). - **Boundary:** a `latestBlockMinus: N` upstream rejoins on its raw head but votes N below it, so its rejoin can lower `latest` by up to N. - **Boundary:** rejoin needs the benched head to reach the bar at one report. A node that always trails the second-highest head by a block or two rejoins late; until then it serves traffic while its lag stays under the policy threshold, but does not vote. - **Boundary:** a bench changes the ballots at once, but routing leaves the benched upstream at the selection policy's next evaluation (`evalInterval`, 15s by default). Until then a request for the new `latest` can reach it; without a configured availability bound nothing gates it, so its missing-data error is retried on another upstream. #### Regression guard `finalized` axis only. When a pick falls more than `maxRegressionBlocks` below the corroborated evidence — the second-highest live head, or the last live-corroborated pick — the lane serves its last corroborated pick instead, never above the highest live head (`guardServedTipRegression`). Unset (`0`), the tolerance is 1024 widened to twice the lane's typical finality step: the lower median of its last eight finalized advances, once two were seen. A chain that finalizes in batches (base: median 1,914 blocks a step) thus does not hold when one voter lags a batch; an explicit value is used as configured. It holds for at most 1 minute, then fails open and serves the pick as computed. In-process only; selectors without a lane get no guard; `-1` disables it. Each transition increments `erpc_network_served_tip_regression_total`. `latest` needs no guard: its view moves back only when the pins move. #### Subscriber delivery ws `newHeads`, ws `logs` and gRPC `StreamBlocks` send up to the lane's view `Head`, read from the same state HTTP reads: a block streams the instant `eth_blockNumber` shows it, and never before. A block a reorg removes is replayed as removed (ws `removed: true`, gRPC resend) before the new branch. A subscription on a `use-upstream` connection reads the network-wide pins cut at its lane's `Head`. A request whose method only some upstreams serve reads its lane's view capped at the block `servedTip.quorum` of those upstreams hold or most likely hold (the block's first sight plus each upstream's measured hold time passed, at most its head plus the blocks the chain made since its last report), so it may be pinned below a block subscribers already got. An upstream that still lacks that block answers missing data, and the request's retry goes to one that holds it; `Firm` counts proven holders only. Model, reorgs and wait bounds: [WebSocket](/operation/websocket.llms.txt#how-heads-reach-subscribers). Source: [`architecture/evm/chain_tracker.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/chain_tracker.go) #### eth_blockNumber With `enforceHighestBlock` on (the default) and the view known, eRPC answers `eth_blockNumber` from the view's `Head` without dispatching, scoped to the request's `use-upstream` selector; `erigon_blockNumber` likewise with no param or `"latest"`, `"finalized"` answers `Head.Finalized`, and any other param is forwarded as is, unpinned. It never waits: at the idle edge it answers the view, as old as the voters' last polls, and the edge's fetch serves the next read. An interpolated `"latest"` tag of `eth_getBlockByNumber` and its family reads the same view; at the idle edge it waits until the view reaches the fetched head, at most W. A `"finalized"` request takes `Head.Finalized` at once and waits for its finalized refresh only at its idle edge (item 15 below). The head is taken before the cache, so a cache hit is pinned to the same head. With no view yet (cold start) the request is forwarded. Every response that reaches the post-forward hook — an upstream answer or a cache hit — is pinned exactly to the head when it is known: higher values are lowered, lower values are raised (an upstream answer below it increments `erpc_upstream_stale_latest_block_total`). `enforce-highest-block=false` forwards and returns the upstream's answer unchanged. Source: [`architecture/evm/eth_blockNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go), [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) An `eth_getBlockByNumber("latest")` that the cache misses, or that no cache holds, goes to its upstream as the `"latest"` tag, as before the chain tracker: each such read is that upstream's poll of its head, at no extra request. Upstreams whose evidence shows them behind the head (a head counter below it after the ordering credit, a newest report that found them behind the network head, and no measured hold wait passed since the head's first sight) go last; the rest go fastest first. Its header goes through the same checks as a poll's and votes, so a block a client read sights first moves the view at once. The answer is served only once the view pins it at or above the request's head, waiting at most 50 ms for the tracker to take the vote; otherwise (a lagging upstream, another branch, a header the tracker cannot verify) the request serves the view's head block, from the cache or by number from a holder, the upstream that answered included: its answer counts as no result, so it stays available to the read and its retries. A `use-upstream` directive, a consensus policy or `servedTip.followCacheHead` keeps the number. `erpc_chain_tracker_latest_read_total{outcome}` counts them: `served`, `head`, `failed`. Source: [`erpc/network_latest_read.go`](https://github.com/erpc/erpc/blob/main/erpc/network_latest_read.go) #### Cache head A network whose cache has a head-aware realtime policy (the source the anchor below reads) polls that connector's head while the network-wide lane has a reader: every eighth of a block or of the TTL, whichever is sooner (50ms–1s), each fetch allowed up to the TTL, with or without `followCacheHead`. Without a reader it fetches nothing; the connector's own head poll runs once a minute. Each new head young enough for the TTL is used once: - **The cache's own voter's poll:** when a lane voter's endpoint host:port is the connector's server (Prism's upstream), the head is that voter's poll of `latest`: the same request to the same server. It passes intake's checks and votes as the voter's own poll would, so the view moves when the cache holds a block, at most an eighth of a block after it. The block clock takes it as a push: it hedges a block only a slot after its predicted sight, since earlier the poll brings it first. Each other voter whose turn falls in that block votes once it most likely holds the block (its measured hold time, as for a held block), at most a block later, not at the poll's sight, when vendors still lack it: so a method only the vendors serve (`eth_call`) gets its `latest` quorum on the new block. - **A sighting:** with no such voter, the head tells the network-wide block clock that its block exists, and the clock fetches it at once as the block's one probe, to a voter whose turn falls in that block once that voter most likely holds it, else to the clock's fastest voter. A by-hash answer above `Latest` is the same proof, and a cache answer prefers the cache's own upstream. A later proof of a block already probed fetches nothing. - **Methods:** a gRPC BDS upstream serves only the methods its client maps (blocks, receipts, logs, traces, balances). For any other method (`eth_call`) it is no server, so that method's `latest` stops at a block the upstreams that serve it hold. #### Cache-head anchor `servedTip.followCacheHead: true` lowers the `Latest` a network-wide read takes to the newest block the network's cache serves, and keeps its `Finalized` and `Firm` at or below it. The source is the first realtime cache policy, with a TTL, on a head-aware connector (the `grpc` driver) that serves `eth_getBlockByNumber("latest")` for the network. While that connector's newest block is young enough for the policy's TTL — the [realtime age guard](/config/database/evm-json-rpc-cache.llms.txt)'s own rule, in whole seconds — the read's `Latest` stops at it and takes the view's pinned hash there: `eth_blockNumber`, `eth_getBlockByNumber("latest")` and tag interpolation name a block the cache already holds, so a client's follow-up reads of it (receipts, logs, the block by number) hit the cache instead of upstreams. Older or unknown: reads take the view's `Head`. Source: [`architecture/evm/cache_head_anchor.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/cache_head_anchor.go), `anchorHead` in [`erpc/network_head.go`](https://github.com/erpc/erpc/blob/main/erpc/network_head.go) - **Only lowers:** `min(Head, cache head)`, so a cache ahead of the upstreams changes nothing. - **Never steps back:** a fresh cache head below the `Latest` reads last took holds `Latest` there, for at most one TTL. A cache that does not catch up within its bound (one reporting another chain, say) stops anchoring until it goes stale or reaches that value, so it cannot freeze `Latest`. A reorg or walk-back the view makes lowers `Latest` as it does without the anchor. - **Read Head only:** the view, its pins, intake, hash votes and the refusal ceiling stay on the tracker's own head, and ws `newHeads`, ws `logs`, gRPC `StreamBlocks` and taps keep sending up to the view's `Head`. So `eth_blockNumber` may sit below the newest block a subscriber got, never above it, and a glitching cache cannot delay, reorder or drop a stream's block. - **Network-wide only:** a read on a `use-upstream` selector, or of a method only some upstreams serve, takes its lane's Head as computed. - **One connector:** it assumes the connector that serves latest blocks also serves the follow-up reads. - **Poll:** the cache head's poll above. - **Signal:** `time() − erpc_cache_connector_latest_block_timestamp_seconds` is the cache head's age; an absent or stalled series means no fresh head. - **Side effect:** the age guard reads the same connector head for realtime responses without a block timestamp (`eth_getLogs`, `eth_blockNumber`), so it judges them by a freshly polled head. #### Guarantee subsets `guaranteedMethods` and `guaranteedFor` clamp the advertised tip down to the lowest majority pick of every configured guarantee subset, so it is never a block a required subset cannot serve. `guaranteedMethods` names a subset by method support; `guaranteedFor` names one by upstream id/tag selector — the same vocabulary as `use-upstream` and `consensus.requiredParticipants`. Each subset runs the same ballot (`guaranteedSubsetPick` → `evmTipBallot`, same voter ranks) at `quorum: majority` whatever the network quorum, folded to the minimum in `guaranteedFloor`; only the membership predicate differs. A majority, never a minimum, so a single frozen member is outvoted inside its group. A subset with no voters constrains nothing (the tip is never pinned to 0), and the clamp can only lower the tip — a group ahead of the network pick never raises it. A subset whose ballot holds only static caps floors the tip only when no REGISTERED member is live (`anyRegisteredLiveHead`): live members that are merely absent from the eligible set (lag-excluded, cordoned, mid-restart) must not hand back a frozen cap. Source: [`erpc/networks.go:L1411-1500`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1411-L1500) #### Finalized floor On `finalized`, each lane serves the higher of the tip computed above and its floor: the highest `finalized` it served since an evaluation last found no voter reporting it (`holdFinalized`). Finality never reverts, so a lower tip while a voter still reports the floor means the voters changed — a leader left the ballot (excluded, benched, syncing), or a lagger rejoined a lone leader, and a lagging group became the quorum — not the chain. The floor holds only while a voter of the lane's ballot, and of every constraining guarantee subset, reports a finalized block at or above it, and only a drop of at most `maxRegressionBlocks` (0 = 1024, also when the guard is off): a deeper drop is the [regression guard](#regression-guard)'s, so a far-ahead voter once served alone cannot hold it up. The first evaluation outside those bounds drops it to the computed tip, and a voter that returns later does not restore it. A held value never exceeds the lane's served `latest` of the same evaluation: above it, `finalized` serves `latest`, never less than the computed tip, since every voter's finalized is at or below its own latest. A request interpolated to the floor block can go to any upstream whose head passed it: routing checks configured bounds only, and response finality is the serving upstream's own. Per lane, computed under the lane's lock with the ballot it compares; a selector without a lane gets no floor, and `latest` has none. On the network-wide lane the floor is also shared across instances through the counter `network///finalizedBlock` (`shareFinalized`, `publishFinalized`), so a client moved to another instance does not see `finalized` step back. A computed value above the shared one raises it (a held value never publishes): the in-process copy at once, the store in the background, so the head computation never waits on it. A computed value below the shared one is served as the shared one under the same rule: at most the tolerance above the computed value, and while the same backing reaches it. Any other shared value is ignored. Only raises are published: a value the chain left behind stays in the counter until the chain passes it, unserved by the tolerance bound. Another instance's raise reaches this one's `Head` at its next evaluation, within 1s. Source: [`erpc/networks.go:L186-245`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L186-L245), [`erpc/network_head.go:L356-379`](https://github.com/erpc/erpc/blob/main/erpc/network_head.go#L356-L379) #### Selector-scoped served tip With a `use-upstream` selector, `EvmRoutableUpstreams` narrows the candidates to the matching upstreams; the pick is the same rule over that subset. `laneFor` returns the selector's lane: the network-wide lane (`lane="all"`) without a selector, a group's own lane for a simple group selector, else none. A lane holds no pick state: only its gauge label, advance-age anchor, regression-guard memory and finalized floor. A selector without a lane gets the same pick with no guard, no finalized floor and no gauges. A request whose method only some of its selector's upstreams serve (`tipScope`) gets the same stateless pick over those upstreams: its selector lane's view capped at the block `servedTip.quorum` of them hold, `Finalized` and `Leader` from their ballot. Each method's voter set is built on its first request and rebuilt when the network's upstreams or an upstream's method filter (an auto-ignore included) change, so a request resolves it with one lookup; when every upstream filters methods alike, every method uses its selector's lane. Which selectors form a lane, naming and the 16-lane cap: [Lanes](/reference/lanes.llms.txt). Source: [`erpc/networks.go:L621-807`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L621-L807) #### Syncing, finality and earliest block **Syncing state machine.** `eth_syncing` is called with a 5 s sub-context on each tick. The upstream is declared fully synced only after 4 consecutive "not syncing" responses (`synced counter ≥ 4`); any syncing response resets the counter to 1. The non-standard `{Ok: bool}` response shape is supported: `Ok=false` is treated as still-syncing. After 10 consecutive failures with no prior success, the syncing check is given up (see below) and the state is `Unknown`. If `upstreams[*].evm.skipSyncingCheck: true` is set in config, `eth_syncing` is never called at all and the state is immediately fixed at `NotSyncing` — use this for nodes that always return a syncing object regardless of actual sync status. **Give-up semantics.** Latest, finalized and the syncing check share one give-up: 10 refusals in a row with no prior success give the method up for 10 minutes (`evm.PollerGiveUpExpiry`); then it is retried once, a refused retry gives it up again, and an answer ends the give-up for good. Once the method has answered at least once, refusals are only logged. Latest and finalized count empty answers, unsupported, ignored and client errors as refusals; finalized also counts missing-data errors once the upstream's latest holds a block, since a node without the finalized tag can answer so. A missing-data error before that, or on latest, is no refusal: an upstream that starts without blocks is polled at its cadence until it holds one. The syncing check counts every error. While finalized is given up, and through its retries, finality is derived from latest. Source: [`architecture/evm/evm_state_poller.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go) (`giveUp`) **`IsBlockFinalized` decision tree** (it compares against `FinalizedBlock()`, the upstream's vote for `Head.Finalized`): 1. Both `finalizedBlock == 0` and `latestBlock == 0` → `ErrFinalizedBlockUnavailable`. 2. `finalizedBlock > 0` → `blockNumber ≤ finalizedBlock`. 3. `finalizedBlock == 0`, the upstream not yet known to lack the finalized tag → nothing is finalized: the upstream reports 0 until its tag first answers. 4. `finalizedBlock == 0`, the upstream known to lack the finalized tag (`skipFinalizedCheck`, item 14 below) and `latestBlock > 0` → infer `finalizedBlock = latestBlock − depth`, the deeper of `FallbackFinalityDepth` (default 1024) and 30 minutes of chain, and compare. The 30 minutes count at the block time floor: the shorter of the EMA and what the blocks seen since start, or since the last halt, allow, so an estimate running long at a cold start never shortens them; 1s while the block time is unknown. **Earliest block detection.** When `blockAvailability.lower.earliestBlockPlus` is configured, `binarySearchEarliest` finds the first block in `[0, latestBlock]` where a probe RPC call returns data. Probe types: `blockHeader` (`eth_getBlockByNumber`), `eventLogs` (`eth_getLogs`, requires ≥1 log entry), `callState` (`eth_getBalance`), `traceData` (tries `trace_block`, `debug_traceBlockByHash`, `trace_replayBlockTransactions` in order). Results are stored in cross-pod shared counters. If `blockAvailability.*.updateRate` is set, a scheduler goroutine re-runs the search at that interval. ### Config schema #### Upstream-level (`upstreams[*].evm.*`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `upstreams[*].evm.statePollerInterval` | Duration | `30s` | How often `Poll()` fires. **`0` disables the poller entirely**: no background goroutine, no initial synchronous poll. Consequences: `LatestBlock()` returns 0, `FinalizedBlock()` returns 0, `SyncingState()` returns `Unknown`, block-availability checks fail-open, `IsBlockFinalized` returns `ErrFinalizedBlockUnavailable` immediately. Intentional opt-out for chains where polling is expensive. Source: [`architecture/evm/evm_state_poller.go:L147-160`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L147-L160) | | `upstreams[*].evm.statePollerDebounce` | Duration | `0` (defer to dynamic/fallback) | Hard per-upstream override for the debounce window. When non-zero, short-circuits the entire `resolveDebounce` algorithm — EMA path and `fallbackStatePollerDebounce` are both bypassed. Source: [`architecture/evm/evm_state_poller.go:L360-363`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L360-L363) | | `upstreams[*].evm.blockAvailability.lower.updateRate` | Duration | `0` (freeze after first detection) | Re-detection cadence for `earliestBlockPlus`-based lower bounds. `0` means the binary-search result is never refreshed within a process lifetime. **Ignored for `latestBlockMinus` and `exactBlock` bounds.** The scheduler goroutine is NOT restarted on config hot-reload. Source: [`architecture/evm/evm_state_poller.go:L694-700`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L694-L700) | | `upstreams[*].evm.blockAvailability.upper.updateRate` | Duration | `0` (freeze after first detection) | Same semantics as `lower.updateRate`. The minimum non-zero rate across lower and upper bounds for the same probe governs the scheduler goroutine. Source: [`architecture/evm/evm_state_poller.go:L694-700`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L694-L700) | #### Network-level (`networks[*].evm.*`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[*].evm.fallbackStatePollerDebounce` | Duration | unset | Debounce used while the block time is not yet known (step 3 of `resolveDebounce`). Unset, the 1 s cold block time × the multiplier (0.7 s) applies. Source: [`architecture/evm/evm_state_poller.go:L505-530`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L505-L530) | | `networks[*].evm.fallbackFinalityDepth` | int64 | `1024` | Blocks subtracted from latest to infer finalized when the upstream does not support `eth_getBlockByNumber("finalized")`. Applied only when `skipFinalizedCheck` is set, `finalizedBlock == 0` and `latestBlock > 0`. Source: [`common/defaults.go:L1975`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1975) | | `networks[*].evm.dynamicBlockTimeDebounceMultiplier` | \*float64 | `0.7` | Scales the EMA block time to compute the debounce. **`0` is silently treated as unset** — the default 0.7 is used. Valid useful range: `0.1`–`1.0`; values above `1.0` make the debounce longer than one block time, causing stale data between polls. To eliminate the EMA-derived debounce, use `statePollerDebounce` on the upstream instead. Source: [`architecture/evm/evm_state_poller.go:L368-372`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L368-L372) | | `networks[*].evm.finalizedDebounceDepthMultiplier` | \*float64 | `0.05` | Finalized polls wait until the upstream's finalized block is older than `(latest − finalized) × EMA block time × multiplier`, when that is longer than the regular debounce. `0` disables it: finalized uses the regular debounce, as before. Also throttles the forced finalized re-check of `blockAvailability` with finalized confidence. Source: [`common/defaults.go:L2446`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2446) | `networks[*].evm.servedTip.*` keys (`quorum`, `maxRegressionBlocks`, `guaranteedMethods`, `guaranteedFor`, `followCacheHead`) and the removed keys with their migration: [Networks config](/config/projects/networks.llms.txt#config-schema). ### Worked examples **1. Majority quorum for a five-provider Mainnet pool.** The default quorum serves the 2nd-highest head; `majority` serves the 3rd of 5, so three providers already have every advertised block and fewer interpolated requests land on a node without it: **Config path:** `networks[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 servedTip: quorum: majority ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, servedTip: { quorum: "majority" }, }, }] ``` **2. Faster polling for a sub-second chain (Arbitrum).** The block time auto-tunes the debounce to ~70% of block time from its first sample, 2 timestamp changes after the first header; before that the cold debounce is 0.7 s (the 1 s cold block time × 0.7). `fallbackStatePollerDebounce` shortens those first headers: **Config path:** `networks[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 42161 fallbackStatePollerDebounce: 200ms ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 42161, fallbackStatePollerDebounce: "200ms", }, }] ``` **3. Guaranteed method floor for a mixed trace/non-trace fleet.** Some upstreams support `trace_*`; others do not. Without `guaranteedMethods`, the served tip could advance to a block no trace-capable upstream has yet: **Config path:** `networks[].evm.servedTip` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 servedTip: guaranteedMethods: ["trace_*"] ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, servedTip: { guaranteedMethods: ["trace_*"], }, }, }] ``` **4. Keep the advertised tip servable by the group consensus requires.** A mixed pool whose own nodes trail the third-party majority by a few blocks: `consensus.requiredParticipants` demands them in the winning group, but `"latest"` resolves to a block they do not have yet, so every request becomes a composition dispute. Name the same tag in `guaranteedFor` and the tip tracks whatever the group can actually serve — no cushion constant to size or revisit: **Config path:** `networks[].evm.servedTip` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 servedTip: # the same tag consensus.requiredParticipants names guaranteedFor: ["type:internal"] ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, servedTip: { // the same tag consensus.requiredParticipants names guaranteedFor: ["type:internal"], }, }, }] ``` **5. Disable the poller for a static archive upstream.** When an archive node is used only for historical queries and tracking chain head is unnecessary or costly: **Config path:** `upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: archive-node evm: statePollerInterval: 0 ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "archive-node", evm: { statePollerInterval: 0 }, }] ``` ### Request/response behavior - A block-tagged request for `"latest"` / `"finalized"` is interpolated to the served tip, which at least `quorum` voters already have; `"finalized"` may instead be the [finalized floor](#finalized-floor), which a voter still reports finalized. Routing does not exclude upstreams below it; per-upstream block-availability checks and retries handle a node that lacks the block. - `ErrFinalizedBlockUnavailable` is retryable (N:yes). Requests are automatically retried on a different upstream. On the wire it maps to HTTP 200 with JSON-RPC error code `-32603`. - `ErrUpstreamBlockUnavailable` is produced by `CheckBlockRangeAvailability` (used for `eth_getLogs`, `trace_filter`, `arbtrace_filter`) when both block bounds are outside the upstream's availability window. Retryable at the network level. - The `SuggestLatestBlock` fast path (called when a response is observed during request forwarding) is non-blocking and uses no debounce. `SuggestFinalizedBlock` uses `TryLock` and is async — suggestions may be dropped under high concurrency. ### Best practices - Use `guaranteedMethods: ["trace_*"]` when mixing archive and non-archive upstreams — prevents the served tip from advancing past what trace-capable nodes have. - Lower `fallbackStatePollerDebounce` to 200–500 ms on sub-second chains (Arbitrum, Base, Optimism) to poll faster than the 0.7 s cold cadence during warm-up. - Avoid setting `dynamicBlockTimeDebounceMultiplier: 0`; it is silently ignored and the default 0.7 is used. To impose a fixed debounce, use `statePollerDebounce` on the upstream instead. - Monitor `erpc_upstream_block_head_lag` per upstream, and alert on `erpc_network_served_tip_advance_age_seconds` (stuck tip), `erpc_network_served_tip_regression_total` and `erpc_upstream_head_benched_total` ([metrics reference](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking)). ### Edge cases & gotchas 1. **`statePollerInterval: 0` disables the poller silently.** All block numbers return 0, syncing state is `Unknown`, `IsBlockFinalized` returns `ErrFinalizedBlockUnavailable` immediately, and block availability checks fail-open. The upstream is not excluded from selection but its head is 0, so it never votes. 2. **Two upstreams with the default quorum serve the lower head.** One stalled node holds `latest` until it is benched (its stall window: 90s at the default 30s `statePollerInterval`); then the other votes alone. A node that is catching up slowly is not benched and holds `latest` at its head until `eth_syncing` reports it syncing. 3. **A rogue head needs `quorum − 1` accomplices.** One far-future or wrong-chain head never moves the pick at quorum ≥ 2. 4. **`dynamicBlockTimeDebounceMultiplier: 0` is silently treated as unset.** The guard `> 0` causes the value to fall through to the default 0.7. 5. **`eventLogs` probe requires ≥1 log entry.** A block with no events returns an empty array, treated as "not available" — the binary search may incorrectly mark data-sparse blocks as unavailable. 6. **`updateRate` goroutine is NOT restarted on config hot-reload.** Only a process restart picks up a changed `updateRate` for `earliestBlockPlus` bounds. Setting `updateRate` alongside `latestBlockMinus` produces a validation warning (not an error); the value is silently ignored at runtime. 7. **`ErrFinalizedBlockUnavailable` is retryable.** It carries no explicit opt-out flag, so `IsRetryableTowardNetwork` returns true. On the wire it maps to HTTP 200 with JSON-RPC error code `-32603`. 8. **`OnValue` callback passes `blockTimestamp=0` for cross-pod replications.** Only the replica that actually fetches feeds the EMA with a real timestamp; replicas receiving shared-counter updates use `blockTimestamp=0`, so only one pod per network feeds the EMA per debounce window. 9. **`ErrFinalizedBlockUnavailable` never fires if only `latestBlock == 0`.** The error requires BOTH counters to be 0. An upstream with a latest block but no finalized block yet answers "not finalized"; only once it is known to lack the finalized tag (item 14) does `IsBlockFinalized` compare against `latestBlock −` the derived depth. 10. **`SuggestFinalizedBlock` may drop updates under load.** It uses `TryLock`; if an update is already in progress the suggestion is discarded. Finalized block updates may lag under high request volume. 11. **`SuggestLatestBlock` monotonic within a process but not across pod restarts.** It calls `TryUpdate` which the shared counter rejects if the value is ≤ current. Across pod restarts the shared counter (Redis) retains the last value, so a restarted upstream reporting a lower block number after a reorg is silently ignored for up to 1024 blocks of rollback. 12. **`eth_syncing` result `{Ok: false}` is interpreted as SYNCING.** The non-standard `{Ok: bool}` response shape is handled by `!Ok`: `Ok=false` means not-ok = still syncing. Source: [`architecture/evm/evm_state_poller.go:L1087-L1100`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L1087-L1100) 13. **`guaranteedFor` on a ONE-member group lets that upstream set the tip.** The clamp is the group's majority, and a group of one has no majority to outvote a stall — a single frozen member holds the network tip at its head. Naming exactly one upstream is declaring it mandatory; name ≥3 for a group that tolerates one stall. Same property `guaranteedMethods` already has for a method only one upstream supports. 14. **Finalized block polling is given up on unsupported chains.** After 10 consecutive `eth_getBlockByNumber("finalized")` refusals without any prior success, finalized is given up and retried every 10 minutes. `IsBlockFinalized` then falls back exclusively to `latestBlock −` the derived depth, also during the retries. On PoW chains or chains without EIP-4895 finality, this is the only reachable path. 15. **Finalized trails by up to `finalizedDebounceDepthMultiplier` of the finality window.** Reads and cache hits classify a block as finalized against the request's `Head.Finalized`; an upstream's answer needs that upstream's own finalized block too, and an upstream on a minority fork never makes one final. Only the full poll and a `finalized` tag request move `Head.Finalized`: a request that names the `finalized` tag (any method, any param) starts the lane's finalized refresh in the background and takes `Head.Finalized` at once. Only when fewer than the quorum's voters reported finalized within W does it wait for the refresh, at most W, before interpolation and the cache lookup. A numbered read above `Head.Finalized` polls nothing. 16. **Instances agree on network-wide `finalized` once their own voters report it.** An instance serves another's value only while one of its voters reports it finalized, so during poll lag two instances behind one load balancer can still differ. Use-upstream lanes keep a separate floor per instance. 17. **`finalized` steps back when every voter at the floor leaves at once, or by more than `maxRegressionBlocks`.** For example, one policy evaluation excludes the whole leading group: the floor drops to the pick of the voters left. A deeper drop is held by the regression guard for at most 1 minute instead. 18. **A voter within `maxRegressionBlocks` above the honest ones can hold the floor while it stays.** The floor never passes the served `latest`, so such a voter can lift `finalized` only into blocks the honest upstreams already have. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_latest_block_number` | gauge | project, vendor, network, upstream | Updated on every `SetLatestBlockNumber` call; `upstream="*"` = corroborated network head (second-highest non-benched) | | `erpc_upstream_finalized_block_number` | gauge | project, vendor, network, upstream | Updated on every `SetFinalizedBlockNumber` call | | `erpc_upstream_block_head_lag` | gauge | project, vendor, network, upstream | Recomputed on each `SetLatestBlockNumber`; value = `network_latest − presumed_latest` (corroborated network head; presumed head = last report plus the network head's progress since, for at most one poll period); a benched head that has not moved since its bench counts as no higher than the network head at the bench | | `erpc_upstream_finalization_lag` | gauge | project, vendor, network, upstream | Recomputed on each `SetFinalizedBlockNumber`; value = `network_finalized − presumed_finalized` (corroborated network head, same presumed-head credit) | | `erpc_upstream_latest_block_polled_total` | counter | project, vendor, network, upstream | Incremented before each actual `eth_getBlockByNumber("latest")` call (debounce elapsed). Two paths increment this counter: (1) proactive timer-driven `Poll()` on the background goroutine, and (2) forced-fresh polls triggered by block-availability checks (`EvmAssertBlockAvailability` / `EvmIsBlockFinalized`) when a request arrives for a block above the current known latest. Both paths still respect the debounce window — if a pod already fetched within the window, `TryUpdateIfStale` returns the cached value without incrementing. | | `erpc_upstream_finalized_block_polled_total` | counter | project, vendor, network, upstream | Same dual-path semantics as `latest_block_polled_total` for the finalized axis | | `erpc_upstream_block_head_large_rollback` | gauge | project, vendor, network, upstream, finality | Fired when a new value would regress >1024 blocks. `finality` is the head axis (`latest` or `finalized`) — the two pollers would otherwise share one series | | `erpc_network_dynamic_block_time_milliseconds` | gauge | project, network | Current EMA block-time estimate in ms; absent until ≥3 samples | | `erpc_network_latest_block_timestamp_distance_seconds` | gauge | project, network, origin | `(now_ms − block.timestamp × 1000) / 1000`; `origin="evm_state_poller"` | Served-tip and bench metrics (`erpc_network_served_tip_*`, `erpc_upstream_head_benched_total`): [metrics reference](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking). **OTel trace spans** (under detailed tracing): `EvmStatePoller.Ask`, `EvmStatePoller.PollFinalizedBlockNumber`, `ChainTracker.Fetch`, `Tap.Read`, `Evm.ExtractBlockReferenceFromRequest`, `Evm.ExtractBlockReferenceFromResponse`. **Notable log messages:** | Level | Message | Trigger | |---|---|---| | `INFO` | `"bootstrapped evm state poller to track upstream latest/finalized blocks and syncing states"` | Successful `Bootstrap` | | `INFO` | `"node is marked as fully synced"` | `synced counter >= 4` consecutive not-syncing responses | | `WARN` | `"upstream refused eth_syncing in evm state poller N times with no success, giving it up"` | syncing check given up (10 refusals, no prior success) | | `WARN` | `"upstream refused latest in evm state poller N times with no success, giving it up"` | latest given up | | `WARN` | `"upstream refused finalized in evm state poller N times with no success, giving it up"` | finalized given up | | `WARN` | `"failed to poll evm state"` | `Poll()` returns a non-cancel error | | `INFO` | `"initial earliest block detection completed for this instance"` | Binary search for `earliestBlockPlus` bound completes | | `INFO` | `"started periodic scheduler for earliest block availability bound"` | `updateRate` configured and scheduler goroutine launched | | `WARN` | `"benched upstream head: it stayed behind peers that kept advancing; ..."` | Upstream benched | | `INFO` | `"upstream head rejoined: it caught up with its non-benched peers"` | Benched upstream rejoined | | `ERROR` | `"served tip regressed far below the corroborated live head; serving the last corroborated tip"` | Regression guard starts holding | | `ERROR` | `"served tip regression outlasted the guard window; failing open and serving the current pick"` | Hold exceeded 1 minute | | `WARN` | `"served tip recovered; the regression guard is no longer holding"` | Guard back to healthy | ### Source code entry points - [`architecture/evm/evm_state_poller.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go) — `Bootstrap`, `Poll`, `Ask`, `PollLatestBlockNumber`, `PollFinalizedBlockNumber`; debounce resolution; syncing state machine - [`common/served_tip.go:L36-L157`](https://github.com/erpc/erpc/blob/main/common/served_tip.go#L36-L157) — `ServedTipQuorum`, `PickServedTip` - [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) — `evmTipBallot`, `EvmRoutableUpstreams`, `requestSelector`, `laneFor`, `EvmAskHead`, `guardServedTipRegression`, `holdFinalized`, `guaranteedFloor`, `guaranteedSubsetPick`, `anyRegisteredLiveHead`, `bindLaneGauges` - [`erpc/network_intake.go`](https://github.com/erpc/erpc/blob/main/erpc/network_intake.go) — `voterSet`, `tipVoterRank` - [`erpc/network_head.go`](https://github.com/erpc/erpc/blob/main/erpc/network_head.go) — `EvmHead`, `EvmLaneHead`, `computeHead`, `markLanes`, `refreshDirtyHeads` - [`architecture/evm/eth_blockNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go) — `eth_blockNumber` pre-forward answer and post-forward pin - [`health/tracker.go:L1428-L1664`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1428-L1664) — `corroboratedNetworkHead`, `headStallAfter`, `evaluateHeadBench`, `movedSinceBench`, `headIsBehind`, `benchPlausibleLead`, `IsHeadBenched` - [`health/tracker.go:L1666-L1918`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1666-L1918) — `SetLatestBlockNumber`, EMA update (`updateBlockTimeSample`, `sampleBlockTime`), `BlockHeadLag` computation - [`health/tracker.go:L1937-L2033`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1937-L2033) — `SetFinalizedBlockNumber`, `rederiveNetworkFinalized`, `FinalizationLag` computation - [`common/defaults.go:L1718-L1977`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1718-L1977) — `DefaultEvmFinalityDepth=1024`, `DefaultDynamicBlockTimeDebounceMultiplier=0.7` - [`common/served_tip_test.go`](https://github.com/erpc/erpc/blob/main/common/served_tip_test.go) — unit tests for `PickServedTip` and quorum parsing - [`erpc/networks_served_tip_test.go`](https://github.com/erpc/erpc/blob/main/erpc/networks_served_tip_test.go) — integration tests: quorum, voter ranks, benching, static caps, selector scoping, guarantee floors, finalized floor ### Related pages - [Selection policies](/config/projects/selection-policies.llms.txt) — uses `blockNumberLagAbove` and `blockHeadLag` produced by this subsystem to deprioritize lagging upstreams. - [Upstream config](/config/projects.llms.txt) — where `evm.statePollerInterval`, `evm.statePollerDebounce`, and `evm.blockAvailability` are set. - [Network config](/config/projects/networks.llms.txt) — where `evm.servedTip`, `evm.fallbackStatePollerDebounce`, and `evm.dynamicBlockTimeDebounceMultiplier` are set. - [Cache](/config/database.llms.txt) — uses `ExtractBlockReferenceFromRequest` / `ExtractBlockReferenceFromResponse` to build cache keys from block numbers and tags. - [eth\_getLogs splitting](/reference/evm/getlogs-splitting.llms.txt) — calls `CheckBlockRangeAvailability` from this subsystem to gate range queries. --- --- # getLogs auto-splitting > Source: https://docs.erpc.cloud/reference/evm/getlogs-splitting > Large eth_getLogs queries silently split into parallel chunks and merge back — no more range-limit errors from any provider, no client changes required. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # getLogs auto-splitting Most RPC providers reject `eth_getLogs` requests that span too many blocks. eRPC fixes this transparently: each upstream with a configured limit gets a large query as parallel sub-requests sized to that limit, and eRPC merges the results into a single ordered response. If an upstream rejects a smaller range than expected, eRPC bisects and retries automatically. Your indexer just works. ## Quick taste Illustrative, not a tuned production config — split proactively at 5 000 blocks, fall back to bisection on provider rejection: **Config path:** `projects[].networks[].evm + projects[].upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 1 # hard cap — requests over this are rejected before splitting getLogsMaxAllowedRange: 30000 # bisect and retry when an upstream rejects a range as too large getLogsSplitOnError: true # max concurrent sub-requests per split operation getLogsSplitConcurrency: 10 upstreams: - id: alchemy endpoint: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY" evm: # split proactively at 5 000 blocks before the upstream complains getLogsAutoSplittingRangeThreshold: 5000 ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1, // hard cap — requests over this are rejected before splitting getLogsMaxAllowedRange: 30000, // bisect and retry when an upstream rejects a range as too large getLogsSplitOnError: true, // max concurrent sub-requests per split operation getLogsSplitConcurrency: 10, }, }], upstreams: [{ id: "alchemy", endpoint: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", evm: { // split proactively at 5 000 blocks before the upstream complains getLogsAutoSplittingRangeThreshold: 5000, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure proactive splitting for my indexer** ```text My indexer sends large eth_getLogs queries and keeps hitting "block range exceeded" errors from Alchemy and Infura. Configure eRPC in my eRPC config to proactively split those queries into per-provider-sized chunks before any upstream sees them, and enable reactive bisection as a fallback. Read the full reference first: https://docs.erpc.cloud/reference/evm/getlogs-splitting.llms.txt ``` **Prompt Example #2: audit splitting config across a multi-upstream pool** ```text Review my eRPC config at my eRPC config: I have multiple upstreams with different getLogsAutoSplittingRangeThreshold values. Tell me how each upstream will chunk a large range, whether getLogsMaxAllowedRange is set correctly as a client-protection cap, and whether getLogsSplitConcurrency could trigger rate-limit failures on any of my providers. Reference: https://docs.erpc.cloud/reference/evm/getlogs-splitting.llms.txt ``` **Prompt Example #3: debug why large getLogs queries are returning errors** ```text My clients are getting HTTP 413 errors from eRPC on eth_getLogs requests that span large block ranges, but I expected the splitting to handle those transparently. Walk me through what could cause that (hard limits vs reactive splitting, re-entrancy guard, partial failure behavior) given my config in my eRPC config. Reference: https://docs.erpc.cloud/reference/evm/getlogs-splitting.llms.txt ``` **Prompt Example #4: tune concurrency to avoid 429s during heavy indexing** ```text My eRPC instance is hammering provider rate limits during bulk getLogs indexing — I'm seeing 429 errors that fail entire split operations. Help me set getLogsSplitConcurrency and per-upstream thresholds in my eRPC config to stay under provider rate limits while keeping throughput high. Reference: https://docs.erpc.cloud/reference/evm/getlogs-splitting.llms.txt ``` --- ### getLogs auto-splitting — full agent reference ### How it works Two independent splitting paths handle different failure modes. **Proactive path (upstream pre-forward)** fires after upstream selection, once per attempt. When the block range exceeds the chosen upstream's `getLogsAutoSplittingRangeThreshold`, eRPC generates contiguous sub-requests of exactly that many blocks (last chunk may be smaller), pins every one to that upstream (`UseUpstream`), dispatches them concurrently (bounded by `getLogsSplitConcurrency`), and returns the merged result as that upstream's answer. That upstream never sees the oversized parent. **Each upstream splits to its own threshold.** A 1 000-block range goes whole to an upstream with threshold `0` or `≥ 1000`, and as 34 pieces to an upstream with threshold `30`. One small-limit upstream never cuts the range for the others. If any piece fails, the attempt fails, and the network's retry gives the whole range to the next upstream, which splits it to its own threshold. A range sent as a block tag (`latest`, `finalized`) moves with the head and is never split proactively. **Under consensus the range splits once, at network pre-forward.** Participants must vote on the same bytes, so when a consensus policy matches `eth_getLogs` (and the request does not skip it), eRPC splits the range at the smallest positive threshold of the selected upstreams, and each piece is voted on alone. No participant re-splits a piece or gets the whole range. **Reactive path (network post-forward)** fires when an upstream returns a too-large error (`ErrCodeEndpointRequestTooLarge` or JSON-RPC code `-32012`). Unlike proactive splitting, it always **bisects** the block range at the midpoint rather than producing threshold-sized chunks. If the bisected sub-request also triggers a too-large error, bisection recurses: block range first, then address list (when block range = 1), then `topics[0]` OR-list (when single block, single address). This continues until the request cannot be split further. **What happens when one sub-request fails.** Any single sub-request failure aborts the entire split. If 9 of 10 sub-requests succeed and 1 fails, eRPC calls `errors.Join` across all errors and returns an error response to the caller. Partial results from successful sub-requests are discarded. There is no partial-results mode. This applies equally to proactive and reactive splits. **Re-entrancy guard.** Sub-requests generated by proactive splitting have `ParentRequestId` set. The re-entrancy guard at network post-forward skips reactive bisection for any sub-request that carries this flag. A too-large error on a piece fails that upstream's attempt; the network then retries the whole range on the next upstream. **Merge ordering.** Sub-requests are dispatched concurrently, but results are stored in a positionally-indexed slice matching the original split order. The `GetLogsMultiResponseWriter` iterates this slice in insertion order, so the output is always deterministic and reflects ascending block range regardless of goroutine completion order. No deduplication is performed. Empty or `null` sub-responses are silently skipped during the merge write. **Hard limits before the cache and before splitting.** Three hard limits fire at project pre-forward, before the cache read, the multiplexer and upstream selection, in this order: block range (`getLogsMaxAllowedRange`, default 30 000), address count (`getLogsMaxAllowedAddresses`), topics OR-list length (`getLogsMaxAllowedTopics`). Exceeding any of these returns HTTP 413 immediately, even when the cache holds an answer for that exact request, so an over-cap request never costs a cache connector (such as a Prism scan of the whole range). Network pre-forward re-checks them before any upstream is chosen, as a backstop for callers that reach `Network.Forward` directly. They do NOT trigger `getLogsSplitOnError` reactive splitting. Only upstream-originated errors (HTTP 413 or JSON-RPC `-32012`) trigger the reactive path. Split sub-requests are exempt: their parent was already checked. **Block tag handling.** Block tags `latest` and `finalized` are resolved to hex numbers using the highest known block from the network's state poller. Tags `safe`, `pending`, and `earliest` — and any unresolvable tag — cannot be resolved to a numeric block. When either `fromBlock` or `toBlock` is one of these unresolvable tags, all range validation and proactive splitting are skipped and the request is forwarded verbatim. Requests using a `blockHash` filter (EIP-234) bypass all splitting logic entirely at every hook stage. **Cache interaction.** Sub-requests flow through the full eRPC forward path independently: cache reads and writes, upstream selection, failsafe, and retry all apply to each chunk. The merged parent response is marked `fromCache = true` only when every sub-request was a cache hit; any single cache miss sets it to `false`. The parent's `SkipCacheRead` directive is propagated verbatim to all sub-requests. ### Config schema #### Upstream-level (`upstreams[].evm`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `getLogsAutoSplittingRangeThreshold` | `int64` | `5000` | Proactive split threshold in blocks, for this upstream only. When this upstream is chosen for a request whose block range exceeds this value, the upstream pre-forward hook splits it into chunks of this size, all pinned to this upstream. Other upstreams are unaffected. `0` disables proactive splitting for this upstream: it receives the whole range. Source: [`common/defaults.go:L146`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L146), [`common/config.go:L1129`](https://github.com/erpc/erpc/blob/main/common/config.go#L1129) | **Deprecated upstream fields** (accepted for back-compat; functionality moved to network-level): | Field | YAML key | Note | |---|---|---| | `DeprecatedGetLogsMaxAllowedRange` | `getLogsMaxAllowedRange` | Moved to `networks[].evm.getLogsMaxAllowedRange` | | `DeprecatedGetLogsMaxAllowedAddresses` | `getLogsMaxAllowedAddresses` | Moved to `networks[].evm.getLogsMaxAllowedAddresses` | | `DeprecatedGetLogsMaxAllowedTopics` | `getLogsMaxAllowedTopics` | Moved to `networks[].evm.getLogsMaxAllowedTopics` | | `DeprecatedGetLogsSplitOnError` | `getLogsSplitOnError` | Moved to `networks[].evm.getLogsSplitOnError` | | `DeprecatedGetLogsMaxBlockRange` | `getLogsMaxBlockRange` | Unused (no-op at runtime) | Source: [`common/config.go:L1138-1151`](https://github.com/erpc/erpc/blob/main/common/config.go#L1138-L1151) #### Network-level (`networks[].evm`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `getLogsMaxAllowedRange` | `int64` | `30000` | Hard cap on block range. Requests exceeding this are rejected with HTTP 413 (`ErrGetLogsExceededMaxAllowedRange`) before any splitting. `0` = no limit (not recommended). Source: [`common/defaults.go:L121`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L121), [`common/config.go:L2189`](https://github.com/erpc/erpc/blob/main/common/config.go#L2189) | | `getLogsMaxAllowedAddresses` | `int64` | `0` (no limit) | Hard cap on number of addresses. Only counted when `address` is a JSON array; a single-string address is never counted. `0` = no limit. Source: [`common/defaults.go:L1862-1863`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1862-L1863) | | `getLogsMaxAllowedTopics` | `int64` | `0` (no limit) | Hard cap on `topics[0]` OR-list length. Only `topics[0]` is counted; positions 1–3 are not. If `topics[0]` is a single string, count = 1. **Footgun:** this cap does not trigger reactive splitting — the client gets HTTP 413 and must reduce the query. Source: [`common/defaults.go:L1865-1866`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1865-L1866) | | `getLogsSplitOnError` | `*bool` | `true` | When enabled, upstream-originated too-large errors (`ErrCodeEndpointRequestTooLarge` or JSON-RPC `-32012`) trigger reactive bisection and retry. Source: [`common/defaults.go:L122`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L122), [`common/config.go:L2192`](https://github.com/erpc/erpc/blob/main/common/config.go#L2192) | | `getLogsSplitConcurrency` | `int` | `10` | Maximum concurrent in-flight sub-requests **per split operation**. Two simultaneous splitting operations can each dispatch up to 10 sub-requests concurrently. **Footgun:** high values on rate-limited providers trigger 429 errors, which are not `ErrCodeEndpointRequestTooLarge` and will fail the parent request without further splitting. Source: [`common/defaults.go:L2098-2099`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2098-L2099), [`architecture/evm/eth_getLogs.go:L660-665`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L660-L665) | | `getLogsMaxResponseBytes` | `int64` | `0` (no limit) | Cap on the size of the **merged** response — the sum of every sub-response a split assembles, not any one piece. Splitting exists to get past an upstream's per-request limits, so without this nothing bounds what one request can make eRPC hold in memory. Sub-requests are cancelled as soon as the running total crosses the cap; the client gets HTTP 413 (`ErrGetLogsExceededMaxAllowedResponseSize`). That code is deliberately **not** `ErrEndpointRequestTooLarge`, so the refusal cannot re-enter the splitting path. `0` keeps the historical unbounded behaviour. Source: [`architecture/evm/eth_getLogs.go:L695-770`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L695-L770) | #### Directive defaults (`networks[].directiveDefaults` or deprecated `networks[].evm.integrity`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `enforceGetLogsBlockRange` | `*bool` | `true` | When true, the upstream pre-forward hook verifies both `fromBlock` and `toBlock` are within the upstream's known available block range. Unavailable blocks produce `ErrUpstreamBlockUnavailable` (retryable). Source: [`common/defaults.go:L118`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L118), [`common/config.go:L2115`](https://github.com/erpc/erpc/blob/main/common/config.go#L2115) | ### Worked examples **1. Archive indexer querying multi-million block spans.** Set a generous `getLogsMaxAllowedRange` and a per-upstream `getLogsAutoSplittingRangeThreshold` that matches provider limits. eRPC fans out proactively and assembles the ordered result in a single response: **Config path:** `projects[].networks[].evm + upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 getLogsMaxAllowedRange: 100000 getLogsSplitOnError: true getLogsSplitConcurrency: 20 upstreams: - id: alchemy evm: getLogsAutoSplittingRangeThreshold: 2000 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, getLogsMaxAllowedRange: 100000, getLogsSplitOnError: true, getLogsSplitConcurrency: 20, }, }], upstreams: [{ id: "alchemy", evm: { getLogsAutoSplittingRangeThreshold: 2000 }, }] ``` **2. Multi-upstream pool where providers have different limits.** Set each upstream's threshold to its known limit. Each upstream chunks a request to its own limit when it is chosen: **Config path:** `upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: alchemy evm: getLogsAutoSplittingRangeThreshold: 2000 - id: infura evm: getLogsAutoSplittingRangeThreshold: 10000 ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [ { id: "alchemy", evm: { getLogsAutoSplittingRangeThreshold: 2000 } }, { id: "infura", evm: { getLogsAutoSplittingRangeThreshold: 10000 } }, ] ``` A 10 000-block request goes to Infura whole, or to Alchemy as five 2 000-block pieces. If one Alchemy piece fails, the retry sends the whole range to Infura. **3. Reactive-only mode for unknown provider limits.** Disable proactive splitting (set threshold to `0`) and rely entirely on bisection when the upstream complains. Useful when you do not know the provider's block-range limit ahead of time: **Config path:** `projects[].networks[].evm + upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 getLogsSplitOnError: true upstreams: - id: unknown-provider evm: getLogsAutoSplittingRangeThreshold: 0 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, getLogsSplitOnError: true }, }], upstreams: [{ id: "unknown-provider", evm: { getLogsAutoSplittingRangeThreshold: 0 }, }] ``` Reactive bisection will recurse until chunks fit: 1 000 blocks → 500 → 250 → … Each recursion level requires a round-trip to the upstream, so this is slower than proactive splitting for large ranges. **4. Address-count-heavy queries on Alchemy.** When your filter has many contract addresses, Alchemy rejects with `"exceed max addresses or topics per search position"`. eRPC normalizes this to `ErrCodeEndpointRequestTooLarge`, triggering reactive splitting. The split priority is: block-range bisection first; once block range = 1, address-list bisection. Enable both mechanisms: **Config path:** `projects[].networks[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: chainId: 1 getLogsSplitOnError: true getLogsSplitConcurrency: 10 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { chainId: 1, getLogsSplitOnError: true, getLogsSplitConcurrency: 10 }, }] ``` ### Request/response behavior - Proactive sub-requests have `ParentRequestId` set to the parent request's ID and `UseUpstream` set to the upstream that split them. Their range fits that upstream's threshold, so they are never re-split proactively, and the re-entrancy guard excludes them from reactive splitting. [[`architecture/evm/eth_getLogs.go:L392-496`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L392-L496)] - Reactive splitting always bisects (never uses threshold): `mid = fromBlock + blockRange/2`. A 1 000-block range produces `[500, 500]`; a 5-block range `[1,2]` + `[3,5]` (`mid = 1 + 5/2 = 3`). [[`architecture/evm/eth_getLogs.go:L562-577`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L562-L577)] - Any sub-request failure causes `errors.Join` across all errors; the caller receives the joined error and all partial results are discarded. [[`architecture/evm/eth_getLogs.go:L783-787`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L783-L787)] - Merged response `fromCache = true` only when every sub-request was a cache hit. [[`architecture/evm/eth_getLogs.go:L796`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L796)] - Empty or `null` sub-responses are normalized to `[]` at upstream post-forward, then silently skipped during merge. If all sub-ranges return empty, the merged output is `[]`. [[`architecture/evm/eth_getLogs.go:L349-362`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L349-L362), [`architecture/evm/eth_getLogs.go:L442-443`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L442-L443)] - `blockHash` filter requests (EIP-234) bypass all splitting logic at every hook stage. [[`architecture/evm/eth_getLogs.go:L101-104`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L101-L104)] - Vendor-specific address-count and filter-count messages are normalized to `ErrCodeEndpointRequestTooLarge` by the error normalizer, enabling reactive splitting: Alchemy/DRPC `"exceed max addresses or topics per search position"`, Infura `"This query contains N filters. The current limit is 5000."`, and the generic pattern `"please specify less number of address in the getLogs query"`. [[`architecture/evm/error_normalizer.go:L102-116`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L102-L116)] - HTTP 413 errors triggered by eRPC's own hard limits (`ErrGetLogsExceededMaxAllowedRange`, `ErrGetLogsExceededMaxAllowedAddresses`, `ErrGetLogsExceededMaxAllowedTopics`) are distinct error codes and do **not** trigger reactive splitting. The client must reduce query dimensions itself. ### Best practices - Set `getLogsAutoSplittingRangeThreshold` per upstream to that provider's documented block-range limit. This eliminates the round-trip cost of reactive bisection for typical queries. - Keep `getLogsSplitOnError: true` (the default) as a backstop for providers that have tighter limits than configured or that enforce address/topic count limits (Alchemy, Infura, DRPC). - Do not set `getLogsSplitConcurrency` above 20 on rate-limited providers — 429 errors are not `ErrCodeEndpointRequestTooLarge` and will fail the parent request without further splitting. Monitor `erpc_network_evm_get_logs_split_failure_total` for a spike in failures. - Use `getLogsMaxAllowedRange` as a client-protection cap, not as the split trigger. Set it to the largest range your slowest downstream consumer might legitimately request; eRPC will split within that cap automatically. - Avoid setting `getLogsMaxAllowedTopics` if you intend to rely on reactive topic splitting — the hard cap returns HTTP 413 before any upstream sees the request, bypassing the reactive path. Set it only when you want to fail fast on pathologically large topic filters. - With reactive-only mode (`threshold: 0`), large ranges bisect recursively: 1 000 blocks at a 100-block upstream limit requires ~10 round-trips. Prefer proactive splitting when the upstream limit is known. - `enforceGetLogsBlockRange: true` (default) pre-validates that both `fromBlock` and `toBlock` are available on the upstream before forwarding. Leave it enabled to avoid sending requests for blocks beyond an upstream's archive depth — unavailable-block errors are retryable, which can cascade into unexpected latency for archive queries. ### Edge cases & gotchas #### A split response has no size limit of its own The range caps (`getLogsMaxAllowedRange`, `…Addresses`, `…Topics`) bound the *request*. Nothing about them bounds the *response*, and splitting is specifically the path that sets a provider's own size limits aside: when an upstream answers "too large", eRPC halves the range, fetches the halves concurrently (`getLogsSplitConcurrency`, default 10) and merges every piece into one result. A provider's refusal is often the only size signal in the system, and the reactive-split path treats it as a cue to try harder rather than as a limit. On a chain with a hot `topics[0]`, a range the provider refuses can still be assembled from pieces that each individually succeed — arriving in memory all at once. Set `getLogsMaxResponseBytes` on any network that serves untrusted clients. The budget is checked as each sub-response lands, before it is cloned into the merge buffer, and the remaining sub-requests are cancelled the moment it is crossed — so the in-flight fan-out does not materialise either. Without it, the practical ceiling is whatever the process can allocate before the OOM killer intervenes. 1. **Any single sub-request failure aborts the entire split.** 9/10 success still means caller gets an error. Source: [`architecture/evm/eth_getLogs.go:L783-787`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L783-L787). 2. **Proactive sub-requests cannot trigger reactive splitting.** The `ParentRequestId` re-entrancy guard skips reactive bisection for any sub-request generated by proactive splitting. A too-large error from such a sub-request fails that upstream's attempt; the network retries the whole range on the next upstream. Source: [`architecture/evm/eth_getLogs.go:L373-374`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L373-L374). 3. **`safe` and `pending` tags skip all validation and splitting.** Requests with these unresolvable tags in `fromBlock` or `toBlock` are forwarded verbatim — no range check, no proactive split. Source: [`architecture/evm/json_rpc.go:L77-80`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L77-L80). 4. **`ErrGetLogsExceededMaxAllowedRange` does NOT trigger reactive splitting.** eRPC's own hard-limit error has a distinct error code not matched by the `isTooLarge` check. The client must reduce the query. Source: [`architecture/evm/eth_getLogs.go:L379`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L379). 5. **Reactive splitting always bisects — never uses the configured threshold.** A 1 000-block range triggers two 500-block sub-requests regardless of `getLogsAutoSplittingRangeThreshold`. If the upstream limit is 100 blocks, bisection recurses many times, each round-trip reaching the upstream. Source: [`architecture/evm/eth_getLogs.go:L562-577`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L562-L577). 6. **`getLogsSplitConcurrency` is per-operation, not global.** N concurrent splitting operations each hold up to `getLogsSplitConcurrency` in-flight sub-requests. 429 errors from rate-limited providers fail the parent request and are not re-split. Source: [`architecture/evm/eth_getLogs.go:L660-665`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L660-L665). 7. **Merged `fromCache = false` if any sub-request was a cache miss.** Even if 9 of 10 sub-requests hit cache, the merged response is not marked from cache. Source: [`architecture/evm/eth_getLogs.go:L796`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L796). 8. **Address-count errors from Alchemy/DRPC/Infura trigger reactive splitting.** The error normalizer maps vendor address/filter-count messages to `ErrCodeEndpointRequestTooLarge`. Three patterns are matched: Alchemy/DRPC `"exceed max addresses or topics per search position"`, Infura `"This query contains N filters. The current limit is 5000."`, and the generic `"please specify less number of address in the getLogs query"`. On a multi-block request, block-range bisection fires first — the address list is not split until the block range is reduced to 1 block. Source: [`architecture/evm/error_normalizer.go:L102-116`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L102-L116). 9. **`getLogsMaxAllowedTopics` and reactive topic bisection are orthogonal.** The hard cap rejects the request before any upstream sees it; reactive topic bisection handles upstream-originated too-large errors. `getLogsMaxAllowedTopics: 0` (no cap) combined with `getLogsSplitOnError: true` is a valid configuration. Source: [`architecture/evm/eth_getLogs.go:L215-217`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L215-L217). 10. **Merge output is never deduplicated.** eRPC's own splitting produces non-overlapping ranges. If overlapping ranges were somehow produced externally, duplicate log entries would appear in the output. Source: [`architecture/evm/eth_getLogs.go:L426-473`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L426-L473). 11. **Empty `eth_getLogs` results are normalized to `[]`, never retried.** eRPC does not treat an empty `eth_getLogs` response as an error — not even for blocks ahead of the chain tip. Source: [`architecture/evm/eth_getLogs.go:L349-362`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L349-L362). 12. **`fromBlock > toBlock` is rejected immediately** with `ErrInvalidRequest` (HTTP 400) at network pre-forward, but only when both tags can be resolved to numeric blocks. Source: [`architecture/evm/eth_getLogs.go:L196-200`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L196-L200). 13. **Sub-requests inherit `SkipCacheRead`; proactive pieces also get `UseUpstream`.** The parent request's `SkipCacheRead` directive is propagated to every sub-request. Proactive pieces are pinned to the upstream that split them. Reactive sub-requests are not pinned: they go through full upstream selection, health checks, failsafe, and retry independently. Source: [`architecture/evm/eth_getLogs.go:L799-870`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L799-L870). 14. **`GetLogsMultiResponseWriter.Release()` is idempotent.** Calling it multiple times is safe. `Size()` after `Release()` returns 0. Concurrent `WriteTo` and `Release` calls are safe — `WriteTo` holds a read lock, `Release` holds a write lock. Source: [`architecture/evm/eth_getLogs.go:L511-528`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L511-L528). 15. **Reactive splitting applied to sub-requests from reactive splits recursively.** Unlike proactive sub-requests (which have `ParentRequestId` set and are excluded from further splitting), sub-requests produced by reactive splitting go through the full network forward path and can themselves trigger further reactive bisection if they also receive a too-large error. Source: [`architecture/evm/eth_getLogs_test.go:L1052-1157`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs_test.go#L1052-L1157). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_evm_get_logs_range_requested` | histogram | `project`, `network`, `category`, `user`, `finality` | Once per parent `eth_getLogs` call with resolvable numeric blocks; buckets at 1, 10, 100, 500, 1000, 5000, 10000, 30000 | | `erpc_network_evm_get_logs_split_success_total` | counter | `project`, `network`, `user`, `agent_name` | Each successful sub-request during any split (proactive or reactive) | | `erpc_network_evm_get_logs_split_failure_total` | counter | `project`, `network`, `user`, `agent_name` | Each failed sub-request during any split (build error, forward error, nil response, JSON-RPC error) | | `erpc_network_evm_get_logs_forced_splits_total` | counter | `project`, `network`, `dimension`, `user`, `agent_name` | Each reactive split; `dimension` ∈ `{block_range, addresses, topics0}`. Proactive splits do NOT increment this counter. | OTel spans are created for each hook stage: `Upstream.PreForwardHook.eth_getLogs` (only when `enforceGetLogsBlockRange` is enabled), `Upstream.PostForwardHook.eth_getLogs`, and the wrapper spans `Project.PreForwardHook`, `Network.PreForwardHook`, `Network.PostForwardHook`, `Upstream.PreForwardHook`, `Upstream.PostForwardHook`. **Notable log messages:** | Level | Message | Notes | |---|---|---| | `DEBUG` | `"executing eth_getLogs sub-request"` | Emitted for each sub-request before dispatch; includes the full `JsonRpcRequest` object. Source: [`architecture/evm/eth_getLogs.go:L679-682`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L679-L682) | ### Source code entry points - [`architecture/evm/eth_getLogs.go:L336-L385`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L336-L385) — `networkPreForward_eth_getLogs`: tag resolution, hard-limit backstop - [`architecture/evm/eth_getLogs.go:L392-L496`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L392-L496) — `upstreamPreForward_eth_getLogs`: block availability, per-upstream proactive split, pinned pieces - [`architecture/evm/eth_getLogs.go:L364-L412`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L364-L412) — `networkPostForward_eth_getLogs`: reactive split trigger, re-entrancy guard - [`architecture/evm/eth_getLogs.go:L537-L626`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L537-L626) — `splitEthGetLogsRequest`: bisection priority (block range → addresses → topics0) - [`architecture/evm/eth_getLogs.go:L650-L797`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L650-L797) — `executeGetLogsSubRequests`: concurrent fan-out, semaphore, positional result storage, failure handling - [`architecture/evm/eth_getLogs.go:L799-L804`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs.go#L799-L804) — `mergeEthGetLogsResults` and `GetLogsMultiResponseWriter`: lazy ordered merge, empty-skip logic - [`architecture/evm/hooks.go:L14-L139`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go#L14-L139) — Hook registration for all `eth_getLogs` hook points - [`architecture/evm/error_normalizer.go:L102-L116`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L102-L116) — Vendor too-large message normalization (Alchemy, DRPC, Infura) - [`common/defaults.go:L121-L122`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L121-L122) — `GetLogsMaxAllowedRange=30000`, `GetLogsSplitOnError=true` network defaults - [`architecture/evm/eth_getLogs_test.go:L1011-L1050`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getLogs_test.go#L1011-L1050) — `TestExecuteGetLogsSubRequests_DeterministicOrder`: concurrent ordering guarantee - [`erpc/http_server_logs_test.go:L168-L307`](https://github.com/erpc/erpc/blob/main/erpc/http_server_logs_test.go#L168-L307) — `TestHttp_EvmGetLogs_ProactiveRangeSplit_MergedResponse`: end-to-end proactive split ### Related pages - [Cache](/config/database.llms.txt) — sub-requests hit the cache independently; merged result is cached when all sub-requests hit cache. - [Retry](/config/failsafe/retry.llms.txt) — each sub-request runs through failsafe and retry independently. - [Rate limiters](/config/rate-limiters.llms.txt) — high `getLogsSplitConcurrency` can trigger provider rate limits; cap upstream call rates here. - [Block availability](/reference/evm/block-availability.llms.txt) — `enforceGetLogsBlockRange` uses the block availability check before forwarding each sub-request. - [Upstream selection](/config/projects/selection-policies.llms.txt) — the chosen upstream's own threshold decides the proactive split, per attempt. --- --- # Method Handlers > Source: https://docs.erpc.cloud/reference/evm/method-handlers > eRPC's per-method EVM hooks eliminate entire classes of provider inconsistency — stale blocks, duplicate broadcasts, range-exceeded traces — before your application ever sees them. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Method Handlers Every EVM node lies a little differently: one returns a block behind on `eth_blockNumber`, another rejects `eth_sendRawTransaction` as "already known" after a successful broadcast, a third chokes on a wide `trace_filter`. eRPC intercepts those inconsistencies before they reach your application — normalizing block tags for cache correctness, making transaction broadcast idempotent across retries, and auto-splitting trace ranges that upstreams can't handle. ## Quick taste Illustrative, not a tuned production config — idempotent broadcast and reactive trace splitting enabled: **Config path:** `projects[].networks[].evm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 1 # "already known" / "nonce too low" replies become synthetic success idempotentTransactionBroadcast: true # reactive bisection when an upstream rejects a trace_filter range traceFilterSplitOnError: true ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1, // "already known" / "nonce too low" replies become synthetic success idempotentTransactionBroadcast: true, // reactive bisection when an upstream rejects a trace_filter range traceFilterSplitOnError: true, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: make eth_sendRawTransaction retries safe and idempotent** ```text My wallet app retries eth_sendRawTransaction on timeout but sometimes gets "already known" or "nonce too low" errors that confuse users. Configure eRPC in my eRPC config to make broadcast idempotent — "already known" should become a synthetic success, and "nonce too low" should probe whether the same tx is already in-chain before deciding. Read the full reference: https://docs.erpc.cloud/reference/evm/method-handlers.llms.txt ``` **Prompt Example #2: stop stale block numbers from reaching my app** ```text Some of my upstreams occasionally return a block number that is one block behind the network head. Configure eRPC in my eRPC config so that eth_blockNumber and eth_getBlockByNumber always return the highest confirmed block across all upstreams, and explain which integrity flags control this behavior. Reference: https://docs.erpc.cloud/reference/evm/method-handlers.llms.txt ``` **Prompt Example #3: enable trace_filter auto-splitting for wide block ranges** ```text My trace pipeline sends trace_filter requests spanning thousands of blocks and some upstreams reject them with range-too-large errors. Set up proactive splitting per upstream and reactive bisection as a fallback in my eRPC config. Also tell me which metric to watch for split failures so I can tune concurrency. Reference: https://docs.erpc.cloud/reference/evm/method-handlers.llms.txt ``` **Prompt Example #4: debug why my markEmptyAsErrorMethods customization is wrong** ```text I added a custom markEmptyAsErrorMethods list in my eRPC config but now some methods that returned empty arrays correctly are getting retried in a loop. Explain the footgun (custom list fully replaces defaults, not merges), show me the default list, and help me rebuild a correct combined list. Reference: https://docs.erpc.cloud/reference/evm/method-handlers.llms.txt ``` --- ### Method handlers — full agent reference ### How it works **Hook topology.** Five hook layers fire at specific points in the request lifecycle, ordered around the cache read and the failsafe retry loop: 1. **Project.PreForward** (`HandleProjectPreForward`, `architecture/evm/hooks.go:L10`) — fires before cache read. Answers the [local-answer methods](#local-answers), handles `eth_blockNumber` (returns highest known, replaces real upstream response), `eth_call` and `eth_estimateGas` (inject missing block param), and records `trace_filter`/`arbtrace_filter` range histogram. 2. **Network.PreForward** (`HandleNetworkPreForward`, `architecture/evm/hooks.go:L40`) — fires after upstream selection. Handles proactive `trace_filter`/`arbtrace_filter` auto-splitting when the request range exceeds the per-upstream threshold. 3. **Upstream.PreForward** (`HandleUpstreamPreForward`, `architecture/evm/hooks.go:L86`) — fires once per upstream attempt. Handles `eth_getLogs`/`trace_filter` block-range availability. 4. **Upstream.PostForward** (`HandleUpstreamPostForward`, `architecture/evm/hooks.go:L109`) — fires after each upstream response. Handles `eth_getBlockByNumber`/`eth_getBlockByHash` block validation, `eth_getBlockReceipts` integrity checks, and `eth_sendRawTransaction` nonce-exception interception. Also applies the configurable `markEmptyAsErrorMethods` gate to convert null/empty results to retryable `ErrEndpointMissingData`. Conversion only fires when the `RetryEmpty` directive is `true` on the request; when `RetryEmpty=false`, null/empty passes through unchanged even for methods in the list. 5. **Network.PostForward** (`HandleNetworkPostForward`, `architecture/evm/hooks.go:L62`) — fires once after the failsafe loop. Pins `eth_blockNumber` to the served head, applies `enforceNonNullTaggedBlocks` to `eth_getBlockByNumber`, and handles `eth_sendRawTransaction` exhausted-broadcast recovery and reactive `trace_filter` splitting. **Block-tag interpolation.** `NormalizeHttpJsonRpc` (`architecture/evm/json_rpc.go:L92`) runs on every request before upstream selection. It resolves `"latest"` to the highest known block number and `"finalized"` to the highest known finalized block number (when available), normalizes numeric hex to canonical form, caches the result in the request for downstream cache-key generation, and sets `EvmBlockRef` metadata (`"latest"`, `"finalized"`, or `"*"` when both appear) for routing and observability. `"safe"` and `"pending"` pass through unchanged. When a `ReqRefs` path points to a map/object param (rather than a scalar block tag), the function skips replacing that param — this prevents accidentally replacing a complex call-data object with a hex string. Resolution is lock-efficient: param values are extracted under a read lock, resolved outside the lock, then deep-copy + write-commit only occur when a change is actually needed. The `SkipInterpolation` directive and per-method `translateLatestTag`/`translateFinalizedTag` flags can disable interpolation on a per-request or per-method basis. **Future/missing block guard (`emptyResultBeyondConfidence`).** When an upstream returns null/empty for a numeric block request, `emptyResultBeyondConfidence` (`architecture/evm/common.go:L62`) compares the request's cached block number against the network's confidence head (`Head.Latest` by default; `Head.Finalized` when `emptyResultConfidence: finalizedBlock`). If the requested block is strictly above the head, the result is truthful — no retry is triggered. If the head is unknown (0) the guard fails open: any block is treated as retryable. This prevents retry storms for not-yet-produced future blocks while preserving normal retry behavior for stale nodes. **eth_call / eth_estimateGas missing-block-param injection.** If the request arrives with exactly one parameter (the call object, no block tag), the project pre-forward hook appends `"latest"` as the second param before forwarding; interpolation then pins it to the network's latest block number, so no upstream applies its own default block. `eth_call` is intentionally excluded from `markEmptyAsErrorMethods` and from structured error wrapping — callers expect raw ABI revert data (a hex string), not a structured error object. #### Local answers eRPC answers these methods itself, before cache and upstream selection, because the true answer does not depend on which upstream serves it, or is about eRPC, the node the client talks to. Routing them made one upstream a single point of failure for a constant (upstreams often reject `net_*` methods) or returned one node's view where eRPC fronts several. | Method | eRPC's answer | Routed instead when | |---|---|---| | `eth_chainId` | `networks[].evm.chainId` as hex | chain id not configured | | `net_version` | `networks[].evm.chainId` as a decimal string | chain id not configured | | `net_listening` | `true` | never | | `net_peerCount` | the number of upstreams eRPC can route the request to now (the selection policy's eligible set, narrowed by `use-upstream`), as hex | never | | `web3_clientVersion` | `erpc//-/` | never | | `eth_syncing` | `false` while one routable upstream is synced | no routable upstream is known synced | Every one is on by default. `networks[].evm.localAnswers` turns one off per network: `{net_peerCount: false}` routes `net_peerCount` to the upstreams as any other method, with no eRPC answer. `networkDefaults.evm.localAnswers` applies to each network per method, unless the network sets that method itself. A key that is not in the table fails config validation. A request with `x-erpc-skip-cache-read: true` is routed too, so a force-refresh can read an upstream's own answer. A network `staticResponses` entry that matches the method and params is explicit config and takes precedence over the local answer. Source: [`common/evm_local_answers.go`](https://github.com/erpc/erpc/blob/main/common/evm_local_answers.go), [`architecture/evm/local_answer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/local_answer.go) **eth_blockNumber highest-block enforcement.** With the `enforceHighestBlock` directive on (`directiveDefaults.enforceHighestBlock`, default `true`, overridable per request), the network pre-forward hook answers from the served tip without dispatching and the post-forward hook pins every response to it; refresh, freshness and pin rules: [Block tracking](/reference/evm/block-tracking.llms.txt#eth_blocknumber). **eth_getBlockByNumber.** `"latest"` and `"finalized"` are interpolated to the request's `Latest`/`Finalized` before forward, like every method's tags; the request takes that head after the voters' refresh ([Block tracking](/reference/evm/block-tracking.llms.txt#eth_blocknumber)). Network.PostForward runs one check: - **`enforceNonNullBlock`:** Converts null/empty results to `ErrEndpointMissingData`. For numeric block params this always applies. For tag params, interpolated or not (the tag the client sent stays in `EvmBlockRef`), it only applies when `enforceNonNullTaggedBlocks` is true. Both branches are guarded by `emptyResultBeyondConfidence`. Upstream.PostForward runs opt-in block validation when directives are set: `ValidateTransactionsRoot`, `ValidateHeaderFieldLengths`, `ValidateTransactionFields`, and `ValidateTransactionBlockInfo`. Phantom/system transactions are handled specially — their blocks legitimately have `transactionsRoot = emptyTrieRoot` despite a non-empty transactions array. Recognized conventions: Polygon PoS / BSC (`from=0x0`, `gas=0x0`) and HyperEVM native/L1 system txs (synthetic signature `r=0x1` and `gasPrice=0`). **eth_getBlockReceipts.** The upstream post-forward hook runs the opt-in [data-integrity module](/config/failsafe/integrity.llms.txt) — when enabled via `networks[].integrity`, its receipt checks (schema, same-block-hash, tx-hash uniqueness, transaction-index consistency, log field shapes/metadata, bloom emptiness/match, log-index contiguity, and — at the authoritative level — receipts-root recompute and receipt-vs-canonical-block corroboration). With no `integrity` config nothing runs. `eth_getBlockReceipts` is intentionally NOT in the default `markEmptyAsErrorMethods` list — empty arrays are the correct response for zero-transaction blocks. **eth_sendRawTransaction idempotency.** eRPC makes `eth_sendRawTransaction` idempotent across retries and failsafe exhaustion. Upstream-level (nonce exception handling): when an upstream returns `ErrCodeEndpointNonceException`: - `already_known` (`NonceExceptionReasonAlreadyKnown`, `common/errors.go:L2754`) → synthesize success with the locally-derived tx hash immediately (no probe). Matched message patterns: `"already known"`, `"known transaction"`, `"already imported"`, `"transaction already in mempool"`, `"tx already in mempool"`, `"already in the mempool"`, `"transaction already exists"`, `"already have transaction"`, `"already exists in mempool"`. Source: [`architecture/evm/error_normalizer.go:L304-L323`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L304-L323). - `nonce_too_low` (`NonceExceptionReasonNonceTooLow`, `common/errors.go:L2756`) → probe `eth_getTransactionByHash` on the same upstream. If the same tx is found (hash matches), return synthetic success. If a different tx with that nonce is found, re-raise as `-32003`. If probe itself errors, the original error is returned unchanged. Matched message patterns: `"nonce too low"`, `"nonce is too low"`, `"nonce has already been used"`. Source: [`architecture/evm/error_normalizer.go:L326-L340`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L326-L340). `ErrEndpointNonceException` always carries `retryableTowardNetwork=false` (`common/errors.go:L2773`). This means N:no: if the upstream-level idempotency hook does not intercept (e.g., `idempotentTransactionBroadcast: false`), the error will NOT be retried on another upstream. This is intentional — once "already known" is established, retrying on another upstream would either echo the same result or erroneously succeed. Network-level (exhausted broadcast recovery): after the failsafe loop exhausts all attempts (`ErrCodeUpstreamsExhausted`, `ErrCodeFailsafeRetryExceeded`, or `ErrCodeFailsafeTimeoutExceeded`), eRPC probes `eth_getTransactionByHash` across the network using `context.WithoutCancel` and a 3-second independent timeout — so the probe runs even when the parent context is already expired. The returned tx hash is cross-checked against the locally-derived hash before granting synthetic success; a mismatch or missing hash field returns the original error. Tx hash extraction supports legacy (type-0 RLP) and EIP-2718 typed transactions (EIP-1559, EIP-2930) via `ethtypes.Transaction.UnmarshalBinary`. Error normalizer N:yes override for `eth_sendRawTransaction`: revert/VM-execution errors and out-of-gas/-32003 errors are flipped to `retryableTowardNetwork=true` (different providers may accept a tx that another rejects). Insufficient-funds errors remain `N:no` — they are deterministic. The nonce detection rules in the error normalizer MUST appear before the generic `-32003` handler. Some vendors use `-32003` for "already known" or "nonce too low" messages; if the generic rule fired first, these would bypass the idempotency machinery entirely. Source: [`architecture/evm/error_normalizer.go:L297-L301`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L297-L301). **trace_filter and arbtrace_filter auto-splitting.** Two splitting modes coexist: Proactive splitting (Network.PreForward): if the request's block range exceeds `min(TraceFilterAutoSplittingRangeThreshold)` across selected upstreams, the request is immediately split into contiguous chunks and dispatched concurrently. Re-entrancy is blocked via `ParentRequestId`. Reactive splitting (Network.PostForward): if an upstream returns a range-too-large error (`ErrCodeEndpointRequestTooLarge` or `JsonRpcErrorEvmLargeRange`) and `traceFilterSplitOnError: true`, eRPC bisects the request — halving block range first (splitting at midpoint `fromBlock + (range/2)`), then `fromAddress` list, then `toAddress` list. Returns an error if a single-block + single-address request still triggers the error. Both proactive and reactive splitting also reject `fromBlock > toBlock` immediately with `-32600` (InvalidRequest) before dispatching sub-requests. Sub-results are concatenated in index order with no deduplication. Any single sub-failure fails the entire merged response. The upstream post-forward hook normalizes `null`/`""`/`{}` results to `[]` — some older Parity/OpenEthereum nodes return `null` for empty ranges. The effective proactive-split threshold is `min` across all upstreams with a positive `TraceFilterAutoSplittingRangeThreshold`. Upstreams with threshold=0 are ignored. If ALL upstreams have threshold=0, no proactive splitting occurs. Concurrency is capped by `traceFilterSplitConcurrency` (default 10). Source: [`architecture/evm/trace_filter.go:L175-L187`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L175-L187). **eth_query\* (Monad MIP-16).** Five methods — `eth_queryBlocks`, `eth_queryTransactions`, `eth_queryLogs`, `eth_queryTraces`, `eth_queryTransfers` — follow [MIP-16](https://github.com/monad-crypto/MIPs/pull/89). One executor (`erpc/query_executor.go`) answers them for JSON-RPC and for the gRPC `bds.evm.QueryService`. The request and response codec is the manifesto's: `evm.Query*RequestFromJsonRpc` parses `params` strictly (one request object; unknown keys, unknown fields, empty `fields` arrays, `target: "0x0"`, bad filter values → `-32602`), and `evm.Query*ResponseToJsonRpc` renders exactly the selected fields. Monad chains (143, 10143) use the MIP-16 Appendix 1 schema; other chains accept every field of the proto selections. JSON-RPC entry: `Network.Forward` hands an `eth_query*` request to the executor right after static responses and safe-block routing, before multiplexing, cache and per-upstream dispatch. The HTTP server's auth, project rate limit and project `allowMethods`/`ignoreMethods` run first like for any request; the network rate limit is taken in `forwardQuery`; `HandleNetworkPostForward` and the project metrics run on the result. One JSON call returns one page. Execution order: 1. **Range.** Omitted `fromBlock` is `earliest` (asc) or `latest` (desc); omitted `toBlock` is `latest` (asc) or `earliest` (desc). Each tag resolves once per request (`latest` → `Head.Latest`, `finalized` → `Head.Finalized`, `safe` → finalized else latest, `earliest` → `0`), so two equal tags name the same block. In `desc` order `fromBlock` is the upper bound. An inverted range fails with `-32602` (`evm.ValidateQueryRange`); bounds are never swapped. 2. **Method served.** No native `QueryService` upstream that allows the method and no upstream whose `evm.queryShim` allows it → `-32004`. 3. **Availability.** A range end above the network's highest known block, or a block outside the union of the availability windows (`blockAvailability` bounds) of the upstreams that can serve the method natively or through the shim sub-requests → `-32001`, before any scan. For the shim, an upstream counts only when its method allow/ignore config accepts every sub-request the request will issue (`ShouldHandleMethod` returns true without an error): `eth_getBlockByNumber` always, plus `eth_getLogs` for `eth_queryLogs`, `trace_block` or `debug_traceBlockByNumber` for traces and transfers, and `eth_getBlockReceipts` when the selection reads receipt fields; none counting → `-32004`. 4. **Native pipe-through.** Native upstreams are tried in selection-policy order with the MIP-16 proto request unchanged. An upstream that fails before its first page (for example `UNIMPLEMENTED` for `eth_queryTraces` on a reader without traces) falls through to the next one, then to the shim. After a page went out, a stream error ends the request: no other upstream continues it. A JSON call takes the first page and cancels the stream; that page's `cursorBlock` is the page end. 5. **Shim.** The shim builds pages from `eth_getBlockByNumber`, `eth_getBlockReceipts`, `eth_getLogs` and `trace_block` / `debug_traceBlockByNumber` sub-requests, each sent through `Network.Forward` (cache, failsafe, upstream selection) with the request id as parent id. The sub-requests of one page prefer the upstream that served the first one (`UseUpstream` set to its id), for methods that upstream accepts (`ShouldHandleMethod` true without an error); others go unpinned. A pinned sub-request that fails is sent once more unpinned, and one answered with `null` (a lagging upstream that does not have the block yet) is asked once more of every other upstream that takes the method (`!`), so a lagging upstream never turns an available block into `-32001`; that answer stands, an error included, except an error saying the block is missing (`ErrEndpointMissingData`, `ErrUpstreamBlockUnavailable`), which keeps the `null` and so `-32001`. The upstream that answers with data becomes the page's pin; a pin that answered `null` where no other upstream had data is dropped, so later sub-requests of the page go unpinned. A sub-request no upstream serves (`eth_getBlockReceipts`, or both trace methods) fails with `-32004`. **Shim pages.** A page scans blocks from its `fromBlock` in traversal order, in chunks fetched concurrently (4, doubling to 64; 16 sub-requests in flight), and ends at the first of: `toBlock`; the block that brings the primary count to `target` or more (the whole block is in the page); the budget; a break in chain consistency. A block is complete once its header, its primary objects and the transactions they join (with receipts when selected) are fetched, all of it inside the page's time budget, so the budget bounds every sub-request of the page. The budget is `queryShim.maxBlocksPerPage` blocks (default 1000) and `queryShim.maxPageDuration` (default `10s`), the smallest across the upstreams that enable the shim for the method. A page that hits the time budget ends at the last complete block; if `fromBlock` itself did not complete, the request fails with `-32005`. Only the page's own deadline ends a page early: a sub-request that times out or fails on its own fails the request. `fromBlock` and `cursorBlock` are the verified headers of the page's first and last block; `toBlock` is the header of the resolved `toBlock`, fetched once more only when the page ends before it. Related objects (`transactions`, `blocks`) appear only when selected, once each, only for blocks and transactions a primary object references; they do not count toward `target`. They come from the block already fetched during the scan (`eth_getBlockByNumber` with full transactions when transactions are selected), never from a second fetch; logs without `blockTimestamp` take the scanned header's timestamp. Transactions carry receipt fields merged from `eth_getBlockReceipts` (`evm.MergeReceipt`) whenever the selection reads one of `status`, `gasUsed`, `cumulativeGasUsed`, `effectiveGasPrice`, `contractAddress`, `logsBloom`. Primary and related arrays are sorted by the MIP-16 ordering keys and reversed as a whole in `desc` order, including objects inside one block. **Shim chain consistency.** One response never mixes blocks from before and after a reorg (MIP-16 Chain consistency). Each scanned block is checked against its own header: every log, receipt, transaction and `trace_block` frame must carry the header's `blockHash`, each `trace_block` frame with a `transactionHash` must name one of the block's transactions, and each `callTracer` result's `txHash` must be the block's transaction at its index (callTracer results carry no block hash). Consecutive headers must link by `parentHash` in traversal order (in `desc`, the earlier block's `parentHash` is the next block's `hash`). At the first break, the scan stops; the blocks from the one before the break are scanned once more with cache reads skipped (`skipCacheRead`) and no pin, and the longer consistent run wins. The page ends at the last consistent block, so the next page starts on whichever chain the upstreams then serve; clients detect the switch by comparing `fromBlock.parentHash` with the previous `cursorBlock.hash`. If `fromBlock` itself is still inconsistent after the re-scan, the request fails as transient: erpc's retryable server error `-32603` on JSON-RPC, `UNAVAILABLE` on gRPC; retry. **Shim filters.** `null` and `[]` place no constraint; an array matches any element; fields combine with AND. `selector` matches only inputs of 4 bytes or more. `eth_queryLogs` passes `address` and `topics` to `eth_getLogs` (one call per chunk), so topic semantics are exactly `eth_getLogs`'. `eth_queryBlocks` filters on `miner`. **Shim traces and transfers.** `trace_block` frames convert with `evm.TraceFromParity` and `evm.PropagateParityReverted` (reward frames are dropped); when `trace_block` is unsupported, `debug_traceBlockByNumber` with `callTracer` converts per transaction with `evm.TraceFromGethDebug`. The network remembers which method answered and asks it directly afterwards. Transfers are `evm.NativeTransfersFromTraces`. Frames with `reverted: true` are dropped unless `filter.includeReverted` is `true`. System transactions and precompile calls are kept. **Errors.** JSON-RPC errors carry the MIP-16 code in `error.code`: `-32602` invalid params, `-32001` range outside availability, `-32004` method not served, `-32005` budget exceeded before `fromBlock` completed. gRPC returns `INVALID_ARGUMENT`, `OUT_OF_RANGE`, `UNIMPLEMENTED` and `RESOURCE_EXHAUSTED` for the same conditions. `fromBlock` not consistent across sub-requests (reorg in progress, lagging upstream) is transient and no MIP-16 condition: `-32603` on JSON-RPC, `UNAVAILABLE` on gRPC. A sub-request failure that has no MIP-16 meaning (upstream error, timeout) passes through erpc's usual error normalization on JSON-RPC, and erpc's gRPC status mapping on gRPC (`DEADLINE_EXCEEDED`, `RESOURCE_EXHAUSTED`, `UNAVAILABLE`, ...; see [gRPC & BDS](/reference/grpc-bds.llms.txt)). A native upstream's own error is unwrapped from the stream wrapper, so its gRPC status keeps its MIP-16 code on both transports (`OUT_OF_RANGE` → `-32001`, and so on) when no shim takes over. ### Config schema #### Network-level fields (`networks[].evm.*`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `integrity.enforceHighestBlock` | `*bool` | `true` | Answers `eth_blockNumber` from the served head and pins every response to it. `eth_getBlockByNumber("latest"/"finalized")` is not re-fetched: its tag is interpolated to the request's Head before forwarding. Also propagated to `DirectiveDefaults.EnforceHighestBlock`. **Deprecated path** — new canonical path is `networks[].directiveDefaults`. Source: [`common/config.go:L2114`](https://github.com/erpc/erpc/blob/main/common/config.go#L2114), [`common/defaults.go:L1458-1459`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1458-L1459) | | `integrity.enforceNonNullTaggedBlocks` | `*bool` | `true` | When true, null responses for tagged block queries (`"latest"`, `"finalized"`) trigger `ErrEndpointMissingData`. Propagated to `DirectiveDefaults.EnforceNonNullTaggedBlocks`. Source: [`common/config.go:L2116`](https://github.com/erpc/erpc/blob/main/common/config.go#L2116), [`common/defaults.go:L1464-1465`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1464-L1465) | | `integrity.enforceGetLogsBlockRange` | `*bool` | `true` | Enables upstream-level block range availability checking for `trace_filter`/`arbtrace_filter` and `eth_getLogs`. Source: [`common/config.go:L2115`](https://github.com/erpc/erpc/blob/main/common/config.go#L2115), [`common/defaults.go:L2121-2122`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2121-L2122) | | `emptyResultConfidence` | `AvailabilityConfidence` | `blockHead` | Confidence head for `emptyResultBeyondConfidence`: `blockHead` uses `Head.Latest`; `finalizedBlock` uses `Head.Finalized`. Source: [`common/config.go:L2250`](https://github.com/erpc/erpc/blob/main/common/config.go#L2250), [`common/defaults.go:L2075-2078`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2075-L2078) | | `markEmptyAsErrorMethods` | `[]string` | see default list | Methods for which null/empty upstream responses become `ErrEndpointMissingData`. `nil` = use default list. `[]` (empty slice) = disable entirely. **Footgun:** setting a custom list does NOT merge with defaults — the default list is fully replaced. Source: [`common/config.go:L2218`](https://github.com/erpc/erpc/blob/main/common/config.go#L2218), [`common/defaults.go:L2111-2113`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2111-L2113) | | `idempotentTransactionBroadcast` | `*bool` | `true` (nil = enabled) | Enables idempotency handling for `eth_sendRawTransaction`. Set `false` to disable. Source: [`common/config.go:L2239`](https://github.com/erpc/erpc/blob/main/common/config.go#L2239) | | `traceFilterSplitOnError` | `*bool` | `nil` (off) | Enables reactive bisection of `trace_filter` on too-large errors. Intentionally off by default. Source: [`common/config.go:L2197`](https://github.com/erpc/erpc/blob/main/common/config.go#L2197), [`common/defaults.go:L2103-2104`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2103-L2104) | | `traceFilterSplitConcurrency` | `int` | `10` | Max in-flight sub-requests during trace_filter splitting. Source: [`common/config.go:L2200`](https://github.com/erpc/erpc/blob/main/common/config.go#L2200), [`common/defaults.go:L2105-2106`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2105-L2106) | **Default `markEmptyAsErrorMethods`** ([`common/defaults.go:L2044-2064`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2044-L2064)): `eth_blockNumber`, `eth_getBlockByNumber`, `eth_getTransactionByHash`, `eth_getTransactionByBlockHashAndIndex`, `eth_getTransactionByBlockNumberAndIndex`, `eth_getUncleByBlockHashAndIndex`, `eth_getUncleByBlockNumberAndIndex`, `debug_traceTransaction`, `trace_transaction`, `trace_block`, `trace_get`. Excluded by design: `eth_getBlockByHash` (subgraphs return empty legitimately), `eth_getTransactionReceipt` (null for pending is valid), `eth_getBlockReceipts` (empty array for 0-tx blocks is valid). #### Per-method fields (`networks[].methods.definitions..*`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `translateLatestTag` | `*bool` | `nil` (enabled) | When nil or true, `"latest"` in this method's block param is replaced with the concrete hex from `Head.Latest`. **Footgun:** disabling causes the cache key to omit a concrete block number, breaking cache deduplication with concrete-block requests for the same block. Source: [`common/config.go:L307-309`](https://github.com/erpc/erpc/blob/main/common/config.go#L307-L309), [`architecture/evm/json_rpc.go:L130`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L130) | | `translateFinalizedTag` | `*bool` | `nil` (enabled) | Same as above for `"finalized"` and `Head.Finalized`. Both flags are evaluated independently. Even when disabled, `seenFinalized` is still recorded so `EvmBlockRef` metadata is still written. Source: [`common/config.go:L310-312`](https://github.com/erpc/erpc/blob/main/common/config.go#L310-L312), [`architecture/evm/json_rpc.go:L131`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L131) | #### Upstream-level fields (`upstreams[].evm.*`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `traceFilterAutoSplittingRangeThreshold` | `int64` | `0` (disabled) | Max block range per chunk for proactive trace_filter splitting at this upstream. Effective threshold is `min` across all selected upstreams with positive values. Zero = this upstream doesn't constrain. Source: [`common/config.go:L1134`](https://github.com/erpc/erpc/blob/main/common/config.go#L1134), [`common/defaults.go:L1546-1547`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1546-L1547) | | `queryShim.enabled` | `*bool` | `nil` (disabled) | This upstream may serve the shim sub-requests of `eth_query*`. At least one upstream must enable it (or serve `QueryService` natively) for a method, else the method returns `-32004`. Source: [`common/config.go:L1373-1383`](https://github.com/erpc/erpc/blob/main/common/config.go#L1373-L1383) | | `queryShim.allowedMethods` | `[]string` | `[]` (all allowed) | Wildcard-matched `eth_query*` methods the shim serves through this upstream. Empty = all five. Source: [`common/config.go:L1404-1419`](https://github.com/erpc/erpc/blob/main/common/config.go#L1404-L1419) | | `queryShim.maxBlocksPerPage` | `int64` | `1000` | Budget: blocks one shim page may scan. The smallest value across shim upstreams wins. Source: [`erpc/query_executor.go:L48-53`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go#L48-L53) | | `queryShim.maxPageDuration` | `Duration` | `10s` | Budget: time one shim page may scan. The page ends at the last complete block; `-32005` when `fromBlock` did not complete. The smallest value across shim upstreams wins. Source: [`erpc/query_executor.go:L48-53`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go#L48-L53) | ### Worked examples **1. Indexer with wide trace_filter ranges.** Proactive splitting per upstream keeps trace requests within each node's limit. The min-threshold is 200 blocks across upstreams, but different providers can declare different constraints and eRPC uses the most restrictive: **Config path:** `projects[].networks[].evm + upstreams[].evm` **YAML — `erpc.yaml`:** ```yaml # Network level — reactive fallback if proactive misses networks: - architecture: evm evm: traceFilterSplitOnError: true traceFilterSplitConcurrency: 20 # Upstream level — proactive split threshold per provider upstreams: - id: quicknode evm: traceFilterAutoSplittingRangeThreshold: 200 - id: alchemy evm: traceFilterAutoSplittingRangeThreshold: 500 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { traceFilterSplitOnError: true, traceFilterSplitConcurrency: 20, }, }], upstreams: [ { id: "quicknode", evm: { traceFilterAutoSplittingRangeThreshold: 200 } }, { id: "alchemy", evm: { traceFilterAutoSplittingRangeThreshold: 500 } }, ] ``` **2. Broadcast-heavy app (wallets, bots).** With idempotent broadcast enabled, retried sends that arrive with "already known" or "nonce too low" from one provider are converted to synthetic success rather than surfacing confusing errors. No config change needed — it is on by default. Disable only if your app has its own nonce tracking and does not want eRPC to probe on its behalf: **Config path:** `projects[].networks[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: idempotentTransactionBroadcast: false # disable if app handles nonces ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { idempotentTransactionBroadcast: false }, }] ``` **3. Finality-sensitive data pipeline.** When your application must never read data above the finalized head (e.g. a settlement system), set `emptyResultConfidence: finalizedBlock`. Blocks between finalized and latest become "beyond confidence" — empty results from that range are returned truthfully rather than retried: **Config path:** `projects[].networks[].evm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: evm evm: emptyResultConfidence: finalizedBlock integrity: enforceHighestBlock: true enforceNonNullTaggedBlocks: true ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "evm", evm: { emptyResultConfidence: "finalizedBlock", integrity: { enforceHighestBlock: true, enforceNonNullTaggedBlocks: true, }, }, }] ``` **4. eth_query\* (MIP-16) from an archive node.** Enable the shim on an archive upstream that serves blocks, receipts, logs and traces to expose the five MIP-16 methods. Leave `allowedMethods` empty to allow all five; lower the budget to keep each page short: **Config path:** `upstreams[].evm.queryShim` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: archive-node evm: queryShim: enabled: true # at most 500 blocks or 5s of scanning per page maxBlocksPerPage: 500 maxPageDuration: 5s ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "archive-node", evm: { queryShim: { enabled: true, // at most 500 blocks or 5s of scanning per page maxBlocksPerPage: 500, maxPageDuration: "5s", }, }, }] ``` ### Request/response behavior - `eth_call` and `eth_estimateGas` with one param always have `"latest"` appended before forwarding; callers never see this normalization. [[`architecture/evm/eth_call.go:L12-34`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_call.go#L12-L34)] - Local answers are skipped when `ShouldSkipCacheRead("")` is true, allowing force-refresh requests to reach real upstreams, and when a network `staticResponses` entry matches the method and params, so the configured reply is served. [[`architecture/evm/local_answer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/local_answer.go)] - `eth_blockNumber` is answered from the served head while it is known; any forwarded or cached response is pinned exactly to it. [[`architecture/evm/eth_blockNumber.go:L13-171`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go#L13-L171)] - Every block-selector form is interpolated: a plain tag, an EIP-1898 `blockNumber` leaf, an absent or null selector of a state method (`eth_call`, `eth_getBalance`, …, `trace_call`), and an absent `eth_getLogs`/`trace_filter` bound. With `translateLatestTag: false` an absent selector is sent as `"latest"`. [[`architecture/evm/json_rpc.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go)] - `emptyResultBeyondConfidence` with head=0 (unknown) fails open — any block is treated as potentially retryable. [[`architecture/evm/common.go:L62-89`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L62-L89)] - `eth_sendRawTransaction` network-level probe uses `context.WithoutCancel` + 3-second fixed timeout; probe runs even when the parent context is expired. [[`architecture/evm/eth_sendRawTransaction.go:L24-26`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L24-L26)] - `eth_sendRawTransaction` synthetic success requires hash cross-check: returned `hash` field must match the locally-derived hash; mismatch or missing field returns the original error. [[`architecture/evm/eth_sendRawTransaction.go:L375-385`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L375-L385)] - `trace_filter`/`arbtrace_filter` upstream post-forward always normalizes `null`/`""`/`{}` to `[]`; errors pass through unchanged. [[`architecture/evm/trace_filter.go:L361-374`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L361-L374)] - trace_filter split sub-requests set `ParentRequestId`; both proactive and reactive splitting skip requests with a non-nil `ParentRequestId` to prevent re-entrancy. [[`architecture/evm/trace_filter.go:L122-125`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L122-L125)] - eth_query\* shim sub-requests carry the client request id as `ParentRequestId` and go through `Network.Forward` (cache, failsafe, selection); the sub-requests of one page prefer the upstream that served its first one (a `null` from it is asked of the other upstreams), and the consistency re-scan skips cache reads. [[`erpc/query_shim.go`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go)] - Error normalizer nonce rules (rules 11/12) appear before the generic `-32003` rule; this ordering is a hard correctness requirement. [[`architecture/evm/error_normalizer.go:L297-301`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L297-L301)] - Insufficient-funds errors remain `N:no` for `eth_sendRawTransaction`; only revert, out-of-gas, and `-32003` codes are flipped to `N:yes`. [[`architecture/evm/error_normalizer.go:L350-361`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L350-L361)] ### Best practices - Enable `traceFilterSplitOnError: true` in production even if you also set `traceFilterAutoSplittingRangeThreshold` per upstream — reactive splitting is your safety net when a new upstream joins that doesn't advertise its limit. - Never add `eth_getBlockReceipts` to `markEmptyAsErrorMethods`: empty arrays are the correct response for 0-transaction blocks and inclusion will cause retry storms against the outer network timeout. - If you set a custom `markEmptyAsErrorMethods` list, the default list is fully replaced — copy the defaults from `common/defaults.go:L2044-L2064` and then add your additions. - Keep `idempotentTransactionBroadcast: true` (the default). The only reason to disable it is if your application manages nonces explicitly and treats "already known" / "nonce too low" as signals for its own retry logic. - Use `emptyResultConfidence: finalizedBlock` for settlement or audit workloads where serving un-finalized data would be a correctness violation. The default `blockHead` is appropriate for all other use cases. - Avoid setting `translateLatestTag: false` or `translateFinalizedTag: false` per-method unless you have a specific reason — disabling tag translation breaks cache deduplication: `"latest"`-tagged and concrete-block requests for the same block will generate different cache keys. - Set `traceFilterSplitConcurrency` conservatively (start at 10, the default) and watch `erpc_network_evm_trace_filter_split_failure_total` before raising it — each concurrent sub-request is a separate upstream call. ### Edge cases & gotchas 1. **eth_call / eth_estimateGas missing block param auto-injection** — a client sending only the call object (no block tag) gets `"latest"` silently appended. Source: [`architecture/evm/eth_call.go:L18-30`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_call.go#L18-L30). 2. **Skip-cache-read routes local answers** — `x-erpc-skip-cache-read: true` sends `eth_chainId`, `net_*`, `web3_clientVersion` and `eth_syncing` to real upstreams. Source: [`architecture/evm/local_answer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/local_answer.go). 3. **eth_blockNumber never reaches an upstream while the served head is known** (with `enforceHighestBlock` on) — the network pre-forward hook answers it; a forwarded or cached response is pinned exactly to the served head, never above or below it. Source: [`architecture/evm/eth_blockNumber.go:L13-171`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_blockNumber.go#L13-L171). 4. **eth_getBlockByNumber(latest) is never raised after forward** — it is interpolated to the request's `Latest`, so it matches `eth_blockNumber`; no second request is sent. Source: [`architecture/evm/eth_getBlockByNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go). 5. **Null for an interpolated tag keeps the tag opt-out** — `enforceNonNullBlock` reads the original tag, not the interpolated number (#477). Source: [`architecture/evm/eth_getBlockByNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go). 6. **eth_getBlockReceipts excluded from default markEmptyAsErrorMethods** — empty arrays are correct for 0-tx blocks; inclusion causes retry storms. Source: [`common/defaults.go:L2054-2064`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2054-L2064). 7. **Phantom transactions (Polygon PoS / BSC / HyperEVM)** — blocks whose transactions are all system/phantom txs legitimately have `transactionsRoot = emptyTrieRoot` on a non-empty array; the integrity module's `transactionsRootConsistency` check skips the inconsistency error for these. Polygon PoS / BSC system txs use `from=0x0, gas=0x0`; HyperEVM native/L1 system txs instead carry a real-looking sender and non-zero gas and are marked by a synthetic signature `r=0x1` with zero `gasPrice` (which also covers the HYPE bridge case where `s=1` ≠ `from`). Source: [`architecture/evm/integrity/checks_block.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/integrity/checks_block.go). 8. **trace_filter null-to-empty normalization** — older Parity/OpenEthereum nodes return `null` for empty ranges; `["result": null]` is converted to `[]`. Source: [`architecture/evm/trace_filter.go:L361-374`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L361-L374). 9. **trace_filter proactive split min-threshold across upstreams** — all-zero thresholds means no proactive splitting occurs. Source: [`architecture/evm/trace_filter.go:L175-187`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L175-L187). 10. **eth_sendRawTransaction independent probe context** — the parent context is always expired when the network-level hook fires; `context.WithoutCancel` is required for the probe to run. Source: [`architecture/evm/eth_sendRawTransaction.go:L346-347`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L346-L347). 11. **eth_sendRawTransaction hash mismatch refuses synthetic success** — prevents a byzantine upstream from faking a successful broadcast. Source: [`architecture/evm/eth_sendRawTransaction.go:L375-385`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L375-L385). 12. **queryShim allowedMethods narrows the shim, not the network** — a method that no shim upstream allows and no native upstream serves returns `-32004`; it is never forwarded raw. Source: [`erpc/query_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go). 13. **eth_queryTraces trace_block → debug fallback** — `-32601`/unsupported `trace_block` switches the network to `debug_traceBlockByNumber` (callTracer); if both are unsupported the request returns `-32004`. Source: [`erpc/query_shim.go`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go). 14. **eth_queryLogs reads one eth_getLogs per scan chunk** — chunks start at 4 blocks and double to 64, so a node's `eth_getLogs` range limit above 64 blocks never bites; `eth_getLogs` also applies the `address`/`topics` filter. Source: [`erpc/query_shim.go`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go). 15. **200-OK ABI-selector revert detection** — responses whose `result` starts with `0x08c379a0` (`Error(string)` selector) are converted to `ErrEndpointExecutionException`. Applies to all methods that can trigger EVM execution, not just `eth_call`. Source: [`architecture/evm/error_normalizer.go:L609-624`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L609-L624). 16. **trace/debug timeout detection via raw-byte scan** — responses from `trace_*`/`debug_*`/`eth_trace` methods can exceed 50 MB; the normalizer uses `strings.Contains(dt, "execution timeout")` instead of JSON parsing to detect server-side timeouts. Source: [`architecture/evm/error_normalizer.go:L626-652`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L626-L652). 17. **validateBlock requires non-nil directives** — all upstream-level block validation for `eth_getBlockByNumber` is skipped when `rq.Directives()` is nil. Source: [`architecture/evm/eth_getBlockByNumber.go:L449-454`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go#L449-L454). 18. **translateLatestTag=false breaks cache deduplication** — disabling tag translation causes cache keys to omit a concrete block number; `"latest"`-tagged and concrete-block requests for the same block produce different cache keys. Source: [`architecture/evm/json_rpc.go:L147-153`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L147-L153). 19. **integrity fields are deprecated** — `networks[].evm.integrity.*` is deprecated; values are migrated to `networks[].directiveDefaults` during `SetDefaults`. Source: [`common/defaults.go:L1957-1964`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1957-L1964). 20. **ErrEndpointClientSideException returns HTTP 200 for revert-class codes** — `JsonRpcErrorEvmReverted` (3), `JsonRpcErrorCallException` (-32000), and `JsonRpcErrorTransactionRejected` (-32003) return HTTP 200, not 400; callers must check the JSON-RPC error code to distinguish execution failures from malformed requests. Source: [`common/errors.go:L1894-1905`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1894-L1905). 21. **markEmptyAsErrorMethods requires RetryEmpty=true to fire** — methods in the list only have their null/empty results converted to `ErrEndpointMissingData` when the `RetryEmpty` directive is `true` on the request. When `RetryEmpty=false`, null/empty passes through unchanged regardless of the list. Methods NOT in the list are never converted. Source: [`architecture/evm/common.go:L62-89`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L62-L89). 22. **trace_filter fromBlock > toBlock returns -32600 immediately** — both the proactive network pre-forward hook and the upstream pre-forward block-range check reject requests where `fromBlock > toBlock` with a `-32600` (InvalidRequest) error before any sub-requests are dispatched. Source: [`architecture/evm/trace_filter.go:L122-200`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L122-L200). 23. **eth_sendRawTransaction upstream probe errors return the original error** — if the `eth_getTransactionByHash` probe issued during `nonce_too_low` handling itself fails (network error, timeout, etc.), the original nonce error is returned unchanged. The probe is a best-effort check, not a retry gate. Source: [`architecture/evm/eth_sendRawTransaction.go:L51-270`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L51-L270). 24. **NormalizeHttpJsonRpc skips top-level object params** — when a `ReqRefs` path points to a map/object param (e.g., the call object in `eth_call`), the function does not attempt to replace it with a hex block number even if the path resolves to a numeric value. Only scalar leaf-level block references within nested objects are replaced. Source: [`architecture/evm/json_rpc.go:L168-194`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L168-L194). 25. **eth_query\* `"pending"` is invalid** — only `latest`, `earliest`, `safe`, `finalized` and QUANTITY are accepted (`-32602`). `"safe"` resolves to the finalized block when known, else latest; `"earliest"` is block `0`, which the availability check requires the union of the serving upstreams' windows to cover. Source: [`erpc/query_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go). 26. **eth_query\* tries native QueryService upstreams first** — gRPC BDS upstreams that serve `bds.evm.QueryService` and allow the method are tried before the shim, in selection-policy order. A native upstream needs `allowMethods` to admit the method (or `eth_query*`). On Monad, Goldsky's endpoint serves `eth_queryLogs` and `eth_queryTransactions` natively; see [Goldsky cache](/config/database/goldsky-cache.llms.txt). Source: [`erpc/query_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go). 27. **eth_query\* JSON calls skip the cache and multiplexer** — each JSON call runs the executor; only the shim's sub-requests are cached. Source: [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go). 28. **eth_query\* shim pages stop at a reorg** — a page whose next block does not link to the previous one by `parentHash`, or whose objects carry another block hash than their header, ends at the last consistent block after one cache-skipping re-scan; a short page near the tip is normal, and `-32603` (gRPC `UNAVAILABLE`) means even `fromBlock` was inconsistent. Retry, or page from `"finalized"`. Source: [`erpc/query_shim.go`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go). ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_stale_latest_block_total` | Counter | `project`, `vendor`, `network`, `upstream`, `category` | An `eth_blockNumber` or `erigon_blockNumber` answer below the request's Head, pinned up to it; `category` = the method | | `erpc_network_latest_block_timestamp_distance_seconds` | Gauge | `project`, `network`, `origin` | `eth_getBlockByNumber(latest)` response received with `origin="network_response"` | | `erpc_network_evm_trace_filter_range_requested` | Histogram | `project`, `network`, `method`, `user`, `finality` | Any `trace_filter`/`arbtrace_filter` request with resolvable block bounds | | `erpc_network_evm_trace_filter_forced_splits_total` | Counter | `project`, `network`, `method`, `dimension`, `user`, `agent_name` | Each split by dimension (`block_range`, `from_address`, `to_address`) | | `erpc_network_evm_trace_filter_split_success_total` | Counter | `project`, `network`, `method`, `user`, `agent_name` | Each successful sub-request in a split execution | | `erpc_network_evm_trace_filter_split_failure_total` | Counter | `project`, `network`, `method`, `user`, `agent_name` | Each failed sub-request in a split execution | **Trace span names** (for distributed tracing / APM): - `Project.PreForwardHook` — parent span for all project-level hooks - `Network.PreForwardHook` - `Network.PostForward.eth_blockNumber`, `Network.PostForward.eth_getBlockByNumber`, `Network.PostForward.eth_sendRawTransaction` - `Upstream.PreForwardHook`, `Upstream.PreForwardHook.trace_filter` - `Upstream.PostForwardHook.eth_getBlockByNumber`, `Upstream.PostForwardHook.eth_getBlockReceipts`, `Upstream.PostForwardHook.eth_sendRawTransaction` - `extractTxHashFromSendRawTransaction`, `createSyntheticSuccessResponse`, `verifyAndHandleNonceTooLow` **Notable log messages** (for debugging): - `"interpolated block tag to concrete block number"` (debug) — `NormalizeHttpJsonRpc` resolved `"latest"` or `"finalized"` to a concrete hex. - `"passed through block tag"` (trace) — `"safe"`, `"pending"`, etc. left unchanged. - `"upstream returned older block than we know, falling back to highest known block"` (debug) — `eth_blockNumber` response below the served head, raised to it. - `"response is ahead of the served tip, pinning to the served tip"` (debug) — `eth_blockNumber` response above the served head, lowered to it. - `"converting 'already known' error to idempotent success"` (info) — `eth_sendRawTransaction` upstream hook. - `"tx FOUND on-chain - converting 'nonce too low' to idempotent success"` (info) — `eth_sendRawTransaction` nonce-too-low probe success. - `"exhausted error overridden: tx found in network, returning synthetic success"` (info) — `eth_sendRawTransaction` network-level hook. - `"verification response carries a different tx hash than submitted — refusing synthetic success"` (warn) — hash mismatch guard. ### Source code entry points - [`architecture/evm/hooks.go:L10-L160`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go#L10-L160) — hook dispatch table; all five entry points routing by method name - [`architecture/evm/json_rpc.go:L92-L321`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L92-L321) — `NormalizeHttpJsonRpc`; block-tag resolution, param deep-copy, path rewriting - [`architecture/evm/common.go:L62-L89`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L62-L89) — `emptyResultBeyondConfidence`; `upstreamPostForward_markUnexpectedEmpty` - [`architecture/evm/eth_sendRawTransaction.go:L51-L400`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go#L51-L400) — upstream/network idempotency; `extractTxHashFromSendRawTransaction`; `verifyAndHandleNonceTooLow` - [`architecture/evm/trace_filter.go:L22-L600`](https://github.com/erpc/erpc/blob/main/architecture/evm/trace_filter.go#L22-L600) — `TraceFilterMethods`; proactive/reactive splitting; `splitTraceFilterRequest`; `executeTraceFilterSubRequests` - [`architecture/evm/eth_getBlockByNumber.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_getBlockByNumber.go) — `enforceNonNullBlock`; block header/tx validation - [`architecture/evm/error_normalizer.go:L246-L652`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L246-L652) — all normalizer rules: revert, nonce ordering, insufficient-funds, out-of-gas, ABI-selector 200-OK, trace timeout scan - [`erpc/query_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go) — `EvmQueryExecutor`: range resolution, availability, native-first routing, MIP-16 error codes, JSON entry `forwardQuery` - [`erpc/query_shim.go`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go) — shim pages: block scanner, budget, chain consistency (hash checks, cache-skipping re-scan), filters, relations, receipts, trace_block→debug fallback - [`common/defaults.go:L2044-L2113`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2044-L2113) — `DefaultMarkEmptyAsErrorMethods`; `EvmNetworkConfig.SetDefaults`; directive default migration ### Related pages - [EVM network config](/config/projects/evm-networks.llms.txt) — where `networks[].evm.*` fields live alongside chain ID, polling, and block tracker settings. - [Upstream config](/config/projects/upstreams.llms.txt) — `upstreams[].evm.*` fields including `queryShim` and `traceFilterAutoSplittingRangeThreshold`. - [Failsafe](/config/failsafe/retry.llms.txt) — the retry/timeout/hedge loop that wraps the hooks; method handlers fire inside this loop. - [Cache](/config/database/evm-json-rpc-cache.llms.txt) — block-tag interpolation (handled here) directly controls cache key stability. - [Matcher](/config/matcher.llms.txt) — controls which requests reach which upstreams before hook logic runs. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — how idempotent broadcast and block enforcement combine during failover. --- --- # gRPC & BDS streaming > Source: https://docs.erpc.cloud/reference/grpc-bds > Use typed protobuf APIs for block, transaction, and log lookups — eRPC routes, caches, and protects every gRPC call exactly like HTTP, with built-in deadlock defenses that keep stuck H2 streams from stalling your traffic. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # gRPC & BDS streaming eRPC speaks gRPC in both directions. Clients can call it over the Blockchain Data Standards (BDS) protobuf API — getting typed, streaming-capable responses — while eRPC routes those requests through the same caching, auth, and failsafe pipeline as HTTP. On the upstream side, eRPC pools and protects gRPC connections to BDS-speaking nodes, with a watchdog that surgically replaces stuck connections without touching healthy ones. **What you get:** - Typed BDS protobuf API — unary lookups and server-streaming bulk queries - Same routing, caching, and auth as the HTTP path — zero duplication in config - H2 deadlock defense — callers unblock immediately when a stream wedges - Per-connection watchdog — stuck connections replaced; healthy ones untouched ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add a BDS upstream and expose the gRPC server** ```text I want to add a BDS-speaking upstream to my eRPC deployment and expose the gRPC server so clients can query it with typed protobuf calls. Read the full reference, then update my eRPC config to enable grpcEnabled, configure the BDS upstream endpoint with TLS and an auth header, and share the shared-port vs separate-port trade-offs. Reference: https://docs.erpc.cloud/reference/grpc-bds.llms.txt ``` **Prompt Example #2: debug wedged BDS streams and watchdog alerts** ```text My eRPC logs show BDS bounded-wait timeout warnings and erpc_grpc_bds_hard_timeout_total is non-zero. Explain what causes wedged H2 streams, how the watchdog detects and replaces them, which metrics to alert on, and whether my failsafe timeout in my eRPC config is set above the 20s hard cap so the watchdog fires first. Reference: https://docs.erpc.cloud/reference/grpc-bds.llms.txt ``` **Prompt Example #3: route gRPC auth through the same pipeline as HTTP** ```text I need gRPC callers to authenticate using the same auth strategies (JWT, secret token, SIWE) as my HTTP clients, and I have a proxy in front that sets x-forwarded-for. Update my eRPC config to configure trustedIPForwarders and trustedIPHeaders for gRPC, and explain the metadata key priority order. Reference: https://docs.erpc.cloud/reference/grpc-bds.llms.txt ``` --- ### gRPC & BDS streaming — full agent reference ### How it works **Dual role.** eRPC is simultaneously a gRPC server and a gRPC client. As a server it exposes `evm.RPCQueryService` (unary) and `evm.QueryService` (server-streaming); both are registered on the same `*grpc.Server` instance. As a client it constructs a `GenericGrpcBdsClient` for any upstream whose endpoint starts with `grpc://`, `grpc+bds://` or `grpcs://`. **Server — port sharing.** By default `server.grpcHostV4`/`grpcPortV4` are copied from the HTTP equivalents, so both protocols share a single TCP port. `grpcSharesHttpV4` detects this ([`erpc/grpc_server.go:L46-57`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L46-L57)) and puts a content-type mux in front of the IPv4 HTTP handler: requests with `content-type: application/grpc` over HTTP/2 route to the in-process `*grpc.Server` via `ServeHTTP`; everything else falls through to the HTTP chain. Without TLS, the cleartext HTTP/2 (h2c prior knowledge) that gRPC clients speak is served natively by the HTTP server. The gRPC path therefore bypasses the HTTP `TimeoutHandler` and `gzipHandler` entirely. When the ports differ, `erpc/init.go` starts a standalone TCP listener. **Server — graceful shutdown.** Standalone listener: a goroutine watches `appCtx.Done()` and calls `gs.server.GracefulStop()`, which drains in-flight RPCs before closing the listener ([`erpc/grpc_server.go:L154-157`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L154-L157)). Shared port: `GracefulStop` never runs; the RPCs ride the HTTP server's HTTP/2 connections, so they drain with the HTTP server — GOAWAY on every connection, then in-flight RPCs (including streams) get up to the HTTP shutdown budget of 30 s to finish ([`erpc/http_server.go:L226-256`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L226-L256)). **Server — request lifecycle.** Every handler calls `extractRequestInput` first ([`erpc/grpc_server.go:L133-158`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L133-L158)), which requires `x-erpc-project` and `x-erpc-chain-id` metadata (returns `codes.InvalidArgument` if absent), resolves auth from metadata, and resolves client IP via the same trusted-forwarder logic as HTTP. Unary methods (`ChainId`, `GetBlockByNumber`, `GetBlockByHash`, `GetLogs`, `GetTransactionByHash`, `GetTransactionReceipt`, `GetBlockReceipts`) go through `ProcessUnary`: a synthetic JSON-RPC request is built, pushed through `project.Forward`, and the result is deserialized into protobuf. A `null` result (block/tx not found) returns an empty proto response rather than an error. Streaming methods (`QueryBlocks`, `QueryTransactions`, `QueryLogs`, `QueryTraces`, `QueryTransfers`) go through `ProcessQueryStream`: auth and rate-limiting run, then the same `EvmQueryExecutor` that answers JSON-RPC `eth_query*` (see [method handlers](/reference/evm/method-handlers.llms.txt)) streams MIP-16 pages back via the `onPage` callback: native `QueryService` upstreams first (request passed through unchanged), then the query shim. Shim pages carry only the selected fields (`gas` selects `gasLimit`). These methods do NOT call `project.Forward`. Every failure ends the stream with a gRPC status (`queryGrpcError`): MIP-16 failures map to `INVALID_ARGUMENT` (malformed request, inverted range), `OUT_OF_RANGE` (range outside availability), `UNIMPLEMENTED` (no upstream serves the method or a sub-request it needs) and `RESOURCE_EXHAUSTED` (page budget ended before `fromBlock` completed), with the BDS `ErrorDetails` attached; a native upstream's own status passes through; `UNAVAILABLE` when `fromBlock` is not consistent across sub-requests (reorg in progress or a lagging upstream: retry); any other failure takes the server mapping below. **Server — error mapping (`grpcStatusOf`).** eRPC error codes map to gRPC status codes: `ErrCodeEndpointUnsupported` → `Unimplemented`; `ErrCodeEndpointUnauthorized`/`ErrCodeAuthUnauthorized` → `Unauthenticated`; `ErrCodeEndpointRequestTimeout`/`ErrCodeNetworkRequestTimeout`/`ErrCodeFailsafeTimeoutExceeded` or a context deadline → `DeadlineExceeded`; `ErrCodeEndpointCapacityExceeded`/`ErrCodeEndpointRequestTooLarge`/`ErrCodeEndpointBillingIssue` and every rate-limit rule error → `ResourceExhausted`; `ErrCodeEndpointMissingData` → `NotFound`; a client error (`common.IsClientError`: client-side exception, invalid or unparsable request, a `getLogs` range/addresses/topics/size limit) → `InvalidArgument`; `ErrCodeEndpointExecutionException` (a revert) → `FailedPrecondition`; `ErrNoUpstreamsLeftToSelect`, or an `ErrUpstreamsExhausted` that is still retryable toward the network (`common.IsRetryableTowardNetwork`) → `Unavailable`; everything else → `Internal`. Both interceptors catch panics and return `codes.Internal`. ([`erpc/grpc_server.go`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go)) **Client — connection pool.** `newBdsPool` dials exactly `bdsPoolSize` (= 3) independent `grpc.ClientConn` instances at startup. Each connection uses `waitForReady: true`, OTel tracing, no client-side cap on a reply's size (`math.MaxInt32`, protobuf's own limit; a wide `eth_getLogs` on a busy chain runs past 100 MiB), a 100 MiB max send, a gRPC-native retry policy (max 2 attempts on `UNAVAILABLE`, 1s→5s backoff), keepalive pings every 30s (5s timeout, `PermitWithoutStream=true`), connect params of 3s minimum connect timeout with 100ms base backoff and 1.5× multiplier, and `dns:///` prefix for round-robin across DNS A-records. The embedded service config selects `round_robin` load-balancing and retries only on `UNAVAILABLE` (max 2 attempts, initialBackoff `1s`, maxBackoff `5s`, multiplier `2`). `Pick()` dispatches calls round-robin via an atomic cursor. ([`clients/grpc_bds_resilience.go:L88-162`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L88-L162)) **Client — TLS selection.** Port 443 → TLS (system CA). Scheme starting with `grpcs` or containing `tls` → TLS. Otherwise → plaintext. Default port when absent from URL: 443 with TLS, 50051 without. ([`clients/grpc_bds_resilience.go:L527-556`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L527-L556)) **Client — bounded-wait defense.** Every gRPC call is wrapped in `callBoundedT` (backed by `util.BoundedCallT`): if `ctx.Err() != nil` on entry, the call is rejected immediately without spawning a goroutine. Otherwise, a goroutine executes the call while the caller selects on both the result channel and `ctx.Done()`. If the context fires first, the caller is unblocked immediately and `context.Cause(ctx)` is returned (not generic `DeadlineExceeded`); the executing goroutine is left to clean up on its own schedule (grpc-go honors context cancellation eventually). Panics inside the goroutine are caught by a deferred `recover` and forwarded as errors on the done channel. Additionally, `SendRequest` imposes a hard cap of 20 seconds (`bdsHardCallTimeout`) via `context.WithTimeoutCause` using `ErrDynamicTimeoutExceeded` as the cause sentinel. `ErrDynamicTimeoutExceeded` is defined at `common/errors.go:L1981-L1984` as `var ErrDynamicTimeoutExceeded = errors.New("dynamic timeout exceeded")`; using `errors.Is` against this specific sentinel (rather than `context.DeadlineExceeded`) is what lets `SendRequest` distinguish eRPC's own hard cap from a caller-imposed deadline. **Client — watchdog.** After each call, `SendRequest` checks `context.Cause(ctx)`. If it equals `ErrDynamicTimeoutExceeded` (our hard cap fired), the event is fed to `pool.OnBoundedTimeout`, which calls `recordStuck`. When `bdsStuckCallThreshold` (= 3) firings accumulate within `bdsStuckCallWindow` (= 60s) on the same connection, `replaceConn` dials a fresh connection and atomically swaps the pool slot. A 5-second dedup window (`bdsReplacementDedupWindow`) prevents concurrent callers from triggering double-replacement. If the dial fails, the old connection stays in place for grpc-go to continue reconnecting through. **Importantly, a caller-side timeout (where the caller's deadline fires before eRPC's 20s cap) does NOT trigger the watchdog.** Only timeouts identified via `errors.Is(err, ErrDynamicTimeoutExceeded)` feed the stuck counter; a parent context expiring from a 500ms caller deadline on an otherwise responsive upstream is not treated as a wedged connection. ([`clients/grpc_bds_resilience.go:L169-242`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L169-L242)) **Client — node-shaped answers.** The manifesto converters render a transaction and a receipt as a node sends them: a field is present only when the record has a value for it, and the receipt's execution figures (`gasUsed`, `effectiveGasPrice`, blob gas, L2 fees) appear on the receipt only, so a cache hit compares equal to an upstream's answer. Fields nodes themselves disagree on (`blockTimestamp`, a pre-Byzantium receipt's `root`) are left as the record has them. **Client — error normalization.** `normalizeGrpcError` walks the Unwrap chain to find a gRPC status, then calls `ExtractGrpcErrorFromGrpcStatus`. BDS-layer error codes are checked first; the raw gRPC code is used only if no BDS detail is present. Every returned error carries `grpcCode`, `grpcMessage`, and `upstreamId`; BDS errors also carry `bdsErrorCode` and optional `cause`. ([`common/grpc_errors.go:L12-225`](https://github.com/erpc/erpc/blob/main/common/grpc_errors.go#L12-L225)) **Client — QueryService.** The client exposes `QueryClient()` for the query executor, which opens the server-streaming call itself. `SendRequest` does not serve `eth_query*`: a JSON-RPC `eth_query*` request never reaches an upstream client as a JSON call, because the executor answers it at the network level. ### Config schema #### Server-side fields (under `server.`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `server.grpcEnabled` | `*bool` | `false` ([`common/defaults.go:L669-671`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L669-L671)) | Master enable. Must be `true` to activate the gRPC server. | | `server.grpcHostV4` | `*string` | copy of `httpHostV4` ([`common/defaults.go:L672-675`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L672-L675)) | gRPC IPv4 bind host. Equal default → port sharing via h2c mux. | | `server.grpcPortV4` | `*int` | copy of `httpPortV4` ([`common/defaults.go:L676-679`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L676-L679)) | gRPC IPv4 bind port. Equal to HTTP by default → h2c mux port sharing. | | `server.grpcHostV6` | `*string` | copy of `httpHostV6` ([`common/defaults.go:L680-683`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L680-L683)) | gRPC IPv6 bind host (no v6 sharing logic). | | `server.grpcPortV6` | `*int` | copy of `httpPortV6` ([`common/defaults.go:L684-687`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L684-L687)) | gRPC IPv6 bind port. | | `server.grpcMaxRecvMsgSize` | `*int` | `104857600` (100 MiB) ([`common/defaults.go:L688-690`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L688-L690)) | Server-side max incoming protobuf message bytes. | | `server.grpcMaxSendMsgSize` | `*int` | `104857600` (100 MiB) ([`common/defaults.go:L691-693`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L691-L693)) | Server-side max outgoing protobuf message bytes. | | `server.tls.enabled` | `bool` | `false` | Loads `certFile`/`keyFile` for the standalone gRPC listener. **Footgun:** has no effect on the shared-port (h2c mux) path; TLS on the shared port is controlled by the HTTP TLS config. Source: [`erpc/grpc_server.go:L105-111`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L105-L111) | | `server.trustedIPForwarders` | `[]string` | `[]` | CIDRs/IPs whose forwarded-IP metadata is trusted for client IP resolution. Invalid entries produce a WARN and are skipped. Source: [`erpc/grpc_server.go:L69-96`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L69-L96) | | `server.trustedIPHeaders` | `[]string` | `[]` | Metadata key names to inspect for real client IP when peer is a trusted forwarder. All values are lowercased at server init. Source: [`erpc/grpc_server.go:L89-95`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L89-L95) | #### Upstream-side fields (under `upstreams[].grpc.`) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `upstreams[].endpoint` | `string` | — (required) | Must start with `grpc://`, `grpc+bds://`, or `grpcs://` to activate the BDS client. Port 443 or `grpcs`/`tls` scheme → TLS; otherwise plaintext. Default port when absent: 443 with TLS, 50051 without. A URL path is the server's mount point and is prepended to every method: `grpcs://edge.goldsky.com/boost` calls `/boost/bds.evm.RPCQueryService/...`. The same applies to `database.*.connector.grpc.servers`. Source: [`clients/registry.go:L102-111`](https://github.com/erpc/erpc/blob/main/clients/registry.go#L102-L111) | | `upstreams[].grpc.headers` | `map[string]string` | `{}` (no headers sent) ([`common/config.go:L1100-1102`](https://github.com/erpc/erpc/blob/main/common/config.go#L1100-L1102)) | Key/value pairs injected as outgoing gRPC metadata on every call via `metadata.NewOutgoingContext` — **replaces** any existing outgoing metadata (does not merge). Use for `authorization: Bearer ` or vendor routing keys. Keys must be lowercase per gRPC spec. Source: [`clients/grpc_bds_client.go:L231-234`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L231-L234) | | `upstreams[].grpc.healthCheckService` | `string` | `""` (off) ([`common/config.go:L407-410`](https://github.com/erpc/erpc/blob/main/common/config.go#L407-L410)) | A `grpc.health.v1` service name. Turns on gRPC client health checking: every pooled connection watches it on each resolved address, and `round_robin` sends only to addresses reporting `SERVING`. A server without the health service answers `UNIMPLEMENTED`, which counts as healthy; a health server that does not register the name reports `SERVICE_UNKNOWN` on `Watch`, which counts as unhealthy. Same field on `database.*.connector.grpc`. Source: [`clients/grpc_bds_client.go:L1636-1663`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L1636-L1663) | #### Resilience tunables (constants in `clients/grpc_bds_resilience.go:L29-L51`) | Variable | Value | Meaning | |---|---|---| | `bdsHardCallTimeout` | `20s` | Absolute per-call ceiling; fires as `ErrDynamicTimeoutExceeded` | | `bdsPoolSize` | `3` | Number of independent connections per upstream | | `bdsStuckCallThreshold` | `3` | Hard-cap firings within window before watchdog replaces the connection | | `bdsStuckCallWindow` | `60s` | Rolling window for stuck-call counting | | `bdsReplacementDedupWindow` | `5s` | Minimum gap between replacements of the same pool slot, by the watchdog or the unservable re-dial | ### Worked examples **1. BDS upstream behind an authenticated provider.** The most common setup: a private BDS node requiring a bearer token, running on a non-443 port and therefore needing the `grpcs://` scheme for TLS: **Config path:** `upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: my-bds-node endpoint: grpcs://bds.example.com:9443 grpc: headers: authorization: "Bearer " ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ id: "my-bds-node", endpoint: "grpcs://bds.example.com:9443", grpc: { headers: { authorization: "Bearer ", }, }, }] ``` **2. Enabling the gRPC server on a separate port.** When you need the gRPC API isolated from HTTP traffic (e.g. different load-balancer rules or TLS termination), set `grpcPortV4` to a distinct value. eRPC starts a standalone TCP listener and exit code 1002 is fatal if it fails: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: grpcEnabled: true grpcPortV4: 50051 ``` **TypeScript — `erpc.ts`:** ```typescript server: { grpcEnabled: true, grpcPortV4: 50051, } ``` **3. Shared port (default) with gRPC metadata auth.** When the gRPC and HTTP ports match (the default), both protocols co-exist on one port. gRPC callers send `x-erpc-project`, `x-erpc-chain-id`, and an `authorization` metadata header; HTTP callers use `X-ERPC-Project` and `Authorization` — eRPC routes both through the same auth and routing pipeline: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: grpcEnabled: true # grpcPortV4 omitted → shares httpPortV4 (default :4000) ``` **TypeScript — `erpc.ts`:** ```typescript server: { grpcEnabled: true, // grpcPortV4 omitted → shares httpPortV4 } ``` **4. Trusted-forwarder setup for gRPC behind a proxy.** Real client IPs arrive in metadata; configure the same fields used by the HTTP path: **Config path:** `server` **YAML — `erpc.yaml`:** ```yaml server: grpcEnabled: true trustedIPForwarders: - 10.0.0.0/8 trustedIPHeaders: - x-forwarded-for ``` **TypeScript — `erpc.ts`:** ```typescript server: { grpcEnabled: true, trustedIPForwarders: ["10.0.0.0/8"], trustedIPHeaders: ["x-forwarded-for"], } ``` ### Request/response behavior **Required metadata (inbound gRPC calls):** - `x-erpc-project` — project ID (string, mandatory; `codes.InvalidArgument` if absent) - `x-erpc-chain-id` — chain ID (mandatory; `codes.InvalidArgument` if absent) - `x-erpc-architecture` — defaults to `"evm"` if absent - `user-agent` — optional; if present, populates the `agent_name` label on downstream Prometheus metrics **Auth metadata priority** (via `auth/grpc.go:L12-L54`): 1. `x-erpc-secret-token` → `AuthTypeSecret` 2. `authorization: Basic ` → `AuthTypeSecret` (password field used as secret) 3. `authorization: Bearer ` → `AuthTypeJwt` 4. `x-siwe-message` + `x-siwe-signature` → `AuthTypeSiwe` 5. None of the above → `AuthTypeNetwork` (IP-based) **Unary method dispatch:** | gRPC method | JSON-RPC method | Special handling | |---|---|---| | `ChainId` | `eth_chainId` | Hex→uint64 conversion on result | | `GetBlockByNumber` | `eth_getBlockByNumber` | EIP-1898 `blockHash` param → silently routes to `GetBlockByHash` | | `GetBlockByHash` | `eth_getBlockByHash` | `null` result → empty proto response | | `GetLogs` | `eth_getLogs` | Numeric hex `fromBlock`/`toBlock`, or an EIP-234 `blockHash`; block tags return an error | | `GetTransactionByHash` | `eth_getTransactionByHash` | `null` → empty proto | | `GetTransactionReceipt` | `eth_getTransactionReceipt` | `null` → empty proto | | `GetBlockReceipts` | `eth_getBlockReceipts` | `codes.InvalidArgument` if neither `blockHash` nor `blockNumber` present | **Streaming method dispatch:** | gRPC method | JSON-RPC method | |---|---| | `QueryBlocks` | `eth_queryBlocks` | | `QueryTransactions` | `eth_queryTransactions` | | `QueryLogs` | `eth_queryLogs` | | `QueryTraces` | `eth_queryTraces` | | `QueryTransfers` | `eth_queryTransfers` | **BDS error-code mapping to eRPC errors** (BDS codes take priority over raw gRPC codes): | BDS `ErrorCode` | eRPC error | Retryable toward network? | |---|---|---| | `UNSUPPORTED_BLOCK_TAG`, `UNSUPPORTED_METHOD` | `ErrEndpointUnsupported` | default | | `RANGE_OUTSIDE_AVAILABLE` | `ErrEndpointMissingData` | default | | `INVALID_PARAMETER`, `INVALID_REQUEST` | `ErrEndpointClientSideException` | **false** | | `RATE_LIMITED` | `ErrEndpointCapacityExceeded` | default | | `TIMEOUT_ERROR` | `ErrEndpointRequestTimeout` | default | | `RANGE_TOO_LARGE` | `ErrEndpointRequestTooLarge` | default | | `INTERNAL_ERROR` | `ErrEndpointServerSideException` | default | **gRPC code fallback** (when no BDS detail present): | gRPC code | eRPC error | |---|---| | `Canceled` | `ErrEndpointRequestCanceled` | | `Unimplemented` | `ErrEndpointUnsupported` | | `InvalidArgument` | `ErrEndpointClientSideException` (non-retryable) | | `ResourceExhausted` | `ErrEndpointCapacityExceeded` | | `DeadlineExceeded` | `ErrEndpointRequestTimeout` | | `Unauthenticated`, `PermissionDenied` | `ErrEndpointUnauthorized` | | `NotFound`, `OutOfRange` | `ErrEndpointMissingData` | | `Internal`, `Unknown`, `Unavailable`, others | `ErrEndpointServerSideException` | ### Best practices - Set `grpcEnabled: true` and omit `grpcPortV4` to share the HTTP port — one port means simpler firewall rules and load-balancer config. Use a separate port only when you need different TLS termination or routing rules. - Use `grpcs://` scheme (not port 443) to explicitly enable TLS on non-443 BDS upstreams. Port-based TLS detection only fires at exactly port 443; port 8443 with `grpc://` stays plaintext. - Keep failsafe policy timeouts **above 20 seconds** if you want the BDS hard cap (`bdsHardCallTimeout`) to be the outer bound. Policy timeouts shorter than 20s also feed the watchdog via the shared `ErrDynamicTimeoutExceeded` sentinel. - Alert on `erpc_grpc_bds_hard_timeout_total` going non-zero — it means your BDS upstream is producing wedged H2 streams. If `erpc_grpc_bds_conn_replacements_total` is also rising, the watchdog is actively cycling connections; investigate the upstream. - Never rely on `X-ERPC-*` per-call directives over gRPC — they are silently ignored. Use [network-level `directiveDefaults`](/config/projects.llms.txt) for cache bypass or upstream pinning on the gRPC path. - Use lowercase keys in `upstreams[].grpc.headers`. gRPC metadata keys are always lowercase on the wire; mixed-case keys may be rejected or silently dropped by intermediaries. - For `eth_getLogs` over gRPC, always resolve `latest`/`earliest`/`pending` to numeric block numbers before calling — the BDS client does not support block tags and returns an error immediately. ### Edge cases & gotchas 1. **`eth_getLogs` does not accept block tags.** `"latest"`, `"earliest"`, and `"pending"` in `fromBlock`/`toBlock` return an error. Only numeric hex strings work, or an EIP-234 `blockHash` alone (combined with `fromBlock`/`toBlock` it is an error); a hash the server does not hold answers `OUT_OF_RANGE`, a cache miss. [`clients/grpc_bds_client.go:L587-589`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L587-L589) 2. **Topic null-position collapsing silently returns wrong results.** A `null` wildcard in a topic filter (`[selector, null, toAddr]`) MUST preserve its position. Dropping the null shifts subsequent topic filters left, silently returning wrong matches. `buildTopicFilters` emits an empty `TopicFilter{Values: nil}` for null entries to preserve positions. [`clients/grpc_bds_client.go:L587-589`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L587-L589) 3. **Watchdog does NOT fire on caller-side timeouts.** Only eRPC's own `bdsHardCallTimeout` — identified via `errors.Is(context.Cause(ctx), ErrDynamicTimeoutExceeded)` — increments the stuck counter. A caller's 500ms deadline expiring on an otherwise healthy upstream does NOT trigger watchdog logic, preventing legitimate slow-path timeouts from churning the pool. [`clients/grpc_bds_client.go:L291-304`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L291-L304) 4. **Goroutine leak is intentional for wedged streams.** `callBoundedT` abandons in-flight gRPC goroutines when the context fires — the caller is unblocked immediately and grpc-go cleans up the goroutine eventually. [`util/bounded_call.go:L56-59`](https://github.com/erpc/erpc/blob/main/util/bounded_call.go#L56-L59) 5. **`waitForReady: true` can mask permanently unreachable upstreams.** RPCs queue indefinitely during reconnects instead of failing fast. The `bdsHardCallTimeout` (20s) caps the exposure window. [`clients/grpc_bds_resilience.go:L118-151`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L118-L151) 6. **`grpc+bds://` is an alias for `grpc://`.** Both schemes produce identical `GenericGrpcBdsClient` construction with no behavioral difference. [`clients/registry.go:L102`](https://github.com/erpc/erpc/blob/main/clients/registry.go#L102) 7. **TLS on port 443 only — not on arbitrary ports by port number.** Port 8443 with `grpc://` stays plaintext. Use `grpcs://` scheme to force TLS on non-443 ports. [`clients/grpc_bds_resilience.go:L279-281`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L279-L281) 8. **Port sharing bypasses HTTP timeout and gzip layers.** gRPC frames on the shared port are handled by the `*grpc.Server` directly; the HTTP `TimeoutHandler` and `gzipHandler` never run for gRPC traffic. [`erpc/http_server.go:L161-177`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L161-L177) 9. **Dual-replacement dedup prevents pool thrashing.** When many concurrent callers hit `bdsStuckCallThreshold` simultaneously, the 5s dedup guard ensures only the first watchdog replacement executes. [`clients/grpc_bds_resilience.go:L213-216`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L213-L216) 10. **Dial-fail leaves old connection in place.** If the watchdog cannot dial a replacement (DNS failure, etc.), the broken slot is kept so grpc-go can continue its own reconnect backoff. [`clients/grpc_bds_resilience.go:L218-227`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L218-L227) 11. **Standalone gRPC server failure exits with code 1002.** Port conflict, permission denied, or TLS cert failure all call `util.OsExit(ExitCodeHttpServerFailed)` = 1002. Same exit code as HTTP server failure — process supervisors should treat it as fatal. [`erpc/init.go:L125-136`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L125-L136) 12. **Failsafe policy timeout shorter than 20s also feeds the watchdog.** Both the BDS hard cap and failsafe timeout policy use the same `ErrDynamicTimeoutExceeded` sentinel. If the outer policy fires first, its cause matches the sentinel and the watchdog fires too. Set policy timeouts > 20s to keep the BDS hard cap as the outer bound. [`common/errors.go:L1981-1984`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1981-L1984) 13. **Do not revive `evm.ExtractGrpcError`.** A legacy dead copy at `architecture/evm/error_normalizer.go:L660-L876` has divergent semantics: BDS `TIMEOUT_ERROR` maps to `ErrEndpointServerSideException` (wrong), gRPC `DeadlineExceeded` maps to `ErrEndpointServerSideException` (wrong), and there is no `Canceled` branch. Use only `common.ExtractGrpcErrorFromGrpcStatus`. 14. **`trustedIPHeaders` values are lowercased at server init.** A YAML entry `X-Forwarded-For` is normalized to `x-forwarded-for`. gRPC metadata keys are always lowercase on the wire, so lookups via `firstMD` use the pre-lowercased value. [`erpc/grpc_server.go:L89-95`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L89-L95) 15. **JSON-RPC `eth_query*` gets one native page per call.** The executor reads the first page of the native stream and cancels it; the page's `cursorBlock` tells the client where the next call starts. gRPC callers get every page of the stream. [`erpc/query_pipe_through.go`](https://github.com/erpc/erpc/blob/main/erpc/query_pipe_through.go) 16. **`X-ERPC-*` HTTP request directives are silently ignored on the gRPC path.** `ProcessUnary` only calls `ApplyDirectiveDefaults`; `EnrichFromHttp` is never called. Metadata keys like `x-erpc-skip-cache-read`, `x-erpc-use-upstream`, or `x-erpc-retry-hint` have zero effect. No error or warning is emitted. Only network-level `directiveDefaults` config applies. [`erpc/request_processor.go:L64`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go#L64) 17. **EIP-1898 `blockHash` param silently re-routes to `GetBlockByHash`.** If `eth_getBlockByNumber` receives an object with a `blockHash` field, `handleGetBlockByNumber` extracts the hash bytes and routes to `GetBlockByHash` instead. This is transparent to the caller. [`clients/grpc_bds_client.go:L341-407`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L341-L407) 18. **Unsupported methods return `ErrEndpointUnsupported` before consuming a connection.** Any method not in the BDS dispatch switch returns this error immediately, permanently disqualifying the upstream for that method type via upstream scoring. [`clients/grpc_bds_client.go:L270-275`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L270-L275) 19. **Nil upstream is nil-safe at BDS client construction.** `NewGrpcBdsClient` accepts a nil `upstream` (used in tests and early bootstrap). Header loading and error classification are nil-safe; `upstream.Id()` returns `"n/a"` in error and metric labels. [`clients/grpc_bds_client.go:L62-87`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L62-L87) 20. **`healthCheckService` names a service the server must register.** With it set, an address reporting `SERVICE_UNKNOWN` or `NOT_SERVING` gets no requests; while every resolved address is in that state, `waitForReady` queues calls on that connection. Only set it for servers that publish that name (a reader behind a gateway that proxies health would expose one reader's state for the whole gateway). [`clients/grpc_bds_client.go:L1636-1663`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L1636-L1663) 21. **A URL path mounts every call, and was ignored before.** `grpc://host/boost` now calls `/boost/bds.evm.RPCQueryService/...`; earlier releases dropped the path and called the root. An endpoint that kept a stray path must drop it, or its server must serve under that path. [`clients/grpc_bds_resilience.go:L527-566`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L527-L566) 22. **`healthCheckService` is refused on an endpoint with a URL path.** grpc-go opens the health `Watch` stream past every client interceptor, so it always calls the root `/grpc.health.v1.Health/Watch`, never the mount. Config validation rejects the pair instead of probing the wrong service. [`common/validation.go:L566-582`](https://github.com/erpc/erpc/blob/main/common/validation.go#L566-L582) 23. **A connection with no servable address is re-dialed.** When a pooled connection's channel reaches `TRANSIENT_FAILURE` (every address refuses connections, or reports `NOT_SERVING` under `healthCheckService`), the pool dials a replacement into its slot, at most once per `bdsReplacementDedupWindow`. grpc-go re-resolves a name only after a connection breaks, and a health failure breaks none; the fresh dial resolves the name again, so a DNS name that now points at a replacement server is followed at once, and opens new connections, so a load balancer routes them to a backend still serving. Calls already queued on the old connection keep waiting there; it closes after `bdsAgeRecycleLinger`. [`clients/grpc_bds_resilience.go:L375-412`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L375-L412) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_grpc_bds_hard_timeout_total` | counter | `project`, `upstream`, `method` | Each time `SendRequest` detects `bdsHardCallTimeout` fired (`context.Cause == ErrDynamicTimeoutExceeded`). Non-zero rate means wedged H2 streams are occurring. Source: [`telemetry/metrics.go:L393-397`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L393-L397) | | `erpc_grpc_bds_conn_replacements_total` | counter | `project`, `upstream` | Each successful watchdog-driven connection replacement (dial succeeded, slot swapped). Source: [`telemetry/metrics.go:L401-405`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L401-L405) | OTel gRPC instrumentation (`otelgrpc.NewServerHandler()` / `otelgrpc.NewClientHandler()`) emits standard gRPC spans on both server and client sides. When `common.IsTracingDetailed` is true, `grpcResponseMetadataInterceptor` adds `grpc.response.metadata.*` attributes to client spans. **Key trace spans:** - `GrpcBdsClient.SendRequest` — root client span; attributes `network.id`, `upstream.id`, `request.method`, `request.id` (detail-only) - `GrpcBdsClient.GetBlockByNumber` / `GetBlockByHash` — detail span; attributes `block_number`, `is_block_tag`, `original_param`, `response_has_block`, `response_block_number`, `response_block_hash` - `GrpcBdsClient.GetLogs` — detail span; attributes `from_block`, `to_block` - `GrpcBdsClient.QueryBlocks` / `QueryTransactions` / `QueryLogs` / `QueryTraces` / `QueryTransfers` — detail spans (no extra attributes currently) - `QueryStream.Handle` — server-side root span; attributes `query.method`, `project.id`, `network.id` **Key log messages:** - `"starting gRPC server"` — INFO at startup, carries `addr` ([`erpc/grpc_server.go:L125-125`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L125-L125)) - `"gRPC unary panic"` / `"gRPC stream panic"` — ERROR with `panic` and `stack` fields ([`erpc/grpc_server.go:L455-467`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L455-L467)) - `"created gRPC BDS client"` — DEBUG; carries `target`, `pool_size`, `hard_call_timeout` ([`clients/grpc_bds_client.go:L138-143`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L138-L143)) - `"BDS bounded-wait timeout fired"` — WARN; carries `err`, `network.id`, `upstream.id`, `method`, `request.id`, `our_hardcap` ([`clients/grpc_bds_client.go:L293-304`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L293-L304)) - `"BDS watchdog: replacing wedged connection"` — WARN; carries `target`, `upstream.id`, `slot` ([`clients/grpc_bds_resilience.go:L231-235`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L231-L235)) - `"BDS watchdog: failed to dial replacement; old conn left in place for grpc-go to reconnect"` — ERROR ([`clients/grpc_bds_resilience.go:L225-225`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L225-L225)) - `"BDS maintainer: recycled pool connection"` — INFO; carries `target`, `upstream.id`, `slot`, `reason` (`age`, `unservable`, `chainid_mismatch`, `closed`) ([`clients/grpc_bds_resilience.go:L310-345`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L310-L345)) - `"processing query stream request"` — INFO per streaming call; carries `component`, `projectId`, `networkId`, `method`, `clientIP` ([`erpc/request_processor.go:L102-102`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go#L102-L102)) - `"query stream completed with error"` / `"query stream completed successfully"` — INFO; carries `durationMs` ([`erpc/request_processor.go:L140-144`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go#L140-L144)) - `"invalid CIDR in trusted forwarders; ignoring"` / `"invalid IP in trusted forwarders; ignoring"` — WARN at server construction when a `trustedIPForwarders` entry cannot be parsed ([`erpc/grpc_server.go:L79-85`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L79-L85)) ### Source code entry points - [`erpc/grpc_server.go:L42-L53`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L42-L53) — `grpcSharesHttpV4`: h2c port-sharing detection and mux wiring - [`erpc/grpc_server.go:L114-L158`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L114-L158) — service registration, `extractRequestInput`, required-metadata validation - [`erpc/grpc_server.go:L451-L473`](https://github.com/erpc/erpc/blob/main/erpc/grpc_server.go#L451-L473) — panic recovery interceptors for unary and streaming - [`erpc/request_processor.go:L56-L136`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go#L56-L136) — `ProcessUnary` and `ProcessQueryStream` - [`erpc/grpc_json_rpc_bridge.go:L13-L21`](https://github.com/erpc/erpc/blob/main/erpc/grpc_json_rpc_bridge.go#L13-L21) — `buildJSONRPCRequest`: synthetic JSON-RPC request factory - [`clients/grpc_bds_client.go:L62-L275`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_client.go#L62-L275) — `GenericGrpcBdsClient` construction, `SendRequest` bounded-wait + method dispatch - [`clients/grpc_bds_resilience.go:L29-L285`](https://github.com/erpc/erpc/blob/main/clients/grpc_bds_resilience.go#L29-L285) — `bdsPool`, resilience tunables, `Pick`, `OnBoundedTimeout`, `recordStuck`, `replaceConn`, `pickTargetForBDS` - [`util/bounded_call.go:L27-L60`](https://github.com/erpc/erpc/blob/main/util/bounded_call.go#L27-L60) — `BoundedCallT`: context-race goroutine wrapper, foundation of wedged-stream defense - [`common/grpc_errors.go:L12-L225`](https://github.com/erpc/erpc/blob/main/common/grpc_errors.go#L12-L225) — `ExtractGrpcErrorFromGrpcStatus`: BDS error-code priority path + gRPC code fallback - [`auth/grpc.go:L12-L54`](https://github.com/erpc/erpc/blob/main/auth/grpc.go#L12-L54) — `NewPayloadFromGrpc`: metadata → `AuthPayload` mapping - [`common/defaults.go:L669-L693`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L669-L693) — gRPC server config defaults - [`common/errors.go:L1981-L1984`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1981-L1984) — `ErrDynamicTimeoutExceeded` sentinel definition - [`common/config.go:L1096-L1118`](https://github.com/erpc/erpc/blob/main/common/config.go#L1096-L1118) — `GrpcUpstreamConfig` struct definition - [`util/exit.go:L8-L9`](https://github.com/erpc/erpc/blob/main/util/exit.go#L8-L9) — `ExitCodeERPCStartFailed` (1001) and `ExitCodeHttpServerFailed` (1002) constants - [`architecture/evm/error_normalizer.go:L660-L876`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L660-L876) — dead legacy `evm.ExtractGrpcError`; do not revive (diverges from live path) ### Related pages - [Auth](/config/auth.llms.txt) — same `AuthPayload` and trusted-forwarder logic applies to gRPC calls. - [Rate limiters](/config/rate-limiters.llms.txt) — streaming methods acquire a permit before executing; configure limits here. - [Failsafe — Timeout](/config/failsafe/timeout.llms.txt) — set > 20s to keep the BDS hard cap as the outer bound. - [Failsafe — Retry](/config/failsafe/retry.llms.txt) — retry policies wrap BDS calls the same way as HTTP upstream calls. - [Metrics reference](/reference/metrics.llms.txt) — all `erpc_grpc_bds_*` metrics documented with full label sets. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — BDS upstreams participate in the same failover routing as HTTP upstreams. --- --- # HTTP Client & Proxy Pools > Source: https://docs.erpc.cloud/reference/http-client > eRPC keeps a single pre-warmed, high-throughput connection to every upstream — and can rotate traffic across a fleet of SOCKS5 or HTTP proxies with zero extra latency. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # HTTP Client & Proxy Pools Every upstream you configure gets its own persistent, pre-warmed connection — 256 idle connections per host, unlimited active, and TCP keepalives that kill wedged flows in ~45 seconds instead of two hours. Add a named proxy pool and eRPC rotates requests round-robin across any number of SOCKS5 or HTTP proxies on every call — useful for IP diversity, egress compliance, or budget isolation. **What you get:** - One connection pool per upstream, created once and reused forever - Transparent gzip in both directions, pooled to avoid allocation pressure - SOCKS5 / HTTP proxy rotation via lock-free round-robin - OTel `traceparent` injected on every outbound call automatically ## Quick taste Illustrative, not a tuned production config — enable gzip and route one upstream through a proxy pool: **Config path:** `proxyPools + projects[].upstreams[].jsonRpc` **YAML — `erpc.yaml`:** ```yaml # route this upstream's requests through the named proxy pool proxyPools: - id: my-proxies urls: - socks5://proxy1.example.com:1080 - http://proxy2.example.com:3128 projects: - id: main upstreams: - endpoint: https://mainnet.infura.io/v3/KEY jsonRpc: # reference the pool by id — eRPC rotates requests round-robin proxyPool: my-proxies # compress request bodies; responses are always decompressed enableGzip: true ``` **TypeScript — `erpc.ts`:** ```typescript // route this upstream's requests through the named proxy pool proxyPools: [{ id: "my-proxies", urls: [ "socks5://proxy1.example.com:1080", "http://proxy2.example.com:3128", ], }], projects: [{ id: "main", upstreams: [{ endpoint: "https://mainnet.infura.io/v3/KEY", jsonRpc: { // reference the pool by id — eRPC rotates requests round-robin proxyPool: "my-proxies", // compress request bodies; responses are always decompressed enableGzip: true, }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: configure proxy rotation for IP-diverse egress** ```text I want to route eRPC upstream requests through a pool of SOCKS5 proxies to spread the source IP fingerprint across providers that rate-limit by IP. Set up a proxyPool in my config and wire it to the right upstreams. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/reference/http-client.llms.txt ``` **Prompt Example #2: enable batch aggregation for a high-QPS indexer** ```text My indexer fires hundreds of eth_getTransactionReceipt calls per second and I want to coalesce them into batches to reduce HTTP round-trips. Enable supportsBatch with sane batchMaxSize and batchMaxWait values on my upstream(s) — and warn me about the footguns (batchMaxSize: 0, batchMaxWait: 0, forwarded-header loss). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/reference/http-client.llms.txt ``` **Prompt Example #3: debug unexpected upstream errors or timeout behavior** ```text My eRPC instance is returning ErrUpstreamMalformedResponse and occasional ErrEndpointRequestTimeout errors I don't understand. Explain the HTTP client error classification table, check my eRPC config for misconfigured batchMaxSize/batchMaxWait or missing timeout settings, and suggest what to look for in the upstream request logs. Reference: https://docs.erpc.cloud/reference/http-client.llms.txt ``` **Prompt Example #4: apply shared JSON-RPC client defaults across all upstreams** ```text I want gzip compression and batch settings applied to every upstream without repeating config. Show me how to use upstreamDefaults.jsonRpc in my eRPC config, and explain the all-or-nothing inheritance footgun so I don't accidentally drop settings on upstreams that already have a jsonRpc block. Reference: https://docs.erpc.cloud/reference/http-client.llms.txt ``` --- ### HTTP Client & Proxy Pools — full agent reference ### How it works **Client lifecycle.** `ClientRegistry.GetOrCreateClient` (`clients/registry.go:L47-L53`) uses a `sync.Map` keyed on `common.UniqueUpstreamKey(ups)`. The first call creates the client; all subsequent calls for the same upstream return the cached instance. Creation is guarded by `sync.Once`. The registry also holds a reference to a `ProxyPoolRegistry`, resolving the proxy pool by ID at creation time. **Scheme dispatch.** `CreateClient` inspects `parsedUrl.Scheme`. `http`/`https` → `NewGenericHttpJsonRpcClient`. `grpc`/`grpc+bds` → `GrpcBdsClient`. `ws`/`wss` → error (not yet implemented). Any other scheme → error (`clients/registry.go:L84-L117`). **Transport construction.** Each `GenericHttpJsonRpcClient` owns its own `http.Transport`: - `DialContext` via `util.DefaultOutboundDialer()`: `net.Dialer{Timeout: 10s, KeepAlive: 15s}`. The 15-second probe interval means wedged TCP flows die in ~45 seconds (3 probes), versus the Linux kernel default of ~7200 seconds. - `MaxConnsPerHost: 0` (unlimited) is intentional. The prior default of 2 capped throughput at ~5 req/s per host with 400ms upstream latency; removing the cap makes the OS TCP stack the only limit. Validated in `clients/http_connection_test.go`. - Overall `http.Client.Timeout` is 60 seconds (includes body read). **Request preparation.** Every outbound call gets: `Content-Type: application/json`, `Accept-Encoding: gzip`, `User-Agent: erpc (/; Project/)`. Custom `headers` from `jsonRpc.headers` are applied via `Header.Set` after those defaults — they can override `Content-Type` or `User-Agent`. OTel W3C `traceparent`/`baggage` injection runs last and cannot be overridden. **Gzip.** The client always sends `Accept-Encoding: gzip` and decompresses any gzip response regardless of `enableGzip`. When `enableGzip: true`, request bodies are also compressed using pooled `gzip.Writer` instances. Both reader and writer are pooled via `sync.Pool` to avoid allocation pressure. **Forwarded headers.** Inbound headers matching `project.forwardHeaders` patterns are forwarded to the upstream only on single (non-batch) requests — the batch path aggregates multiple caller contexts into one outbound call. **Batch aggregation.** When `supportsBatch: true`, `SendRequest` queues calls into a map keyed by JSON-RPC ID. A `time.AfterFunc(batchMaxWait, ...)` fires `processBatch` when the timer elapses; the batch also fires immediately when the queue reaches `batchMaxSize`. The batch context deadline is set to the earliest deadline among queued requests. Responses are matched back to callers by JSON-RPC `id`. A single-object response (e.g. a rate-limit error with `"id": null`) is broadcast to all queued callers. Duplicate IDs within a window flush the pending batch immediately and start fresh. **Proxy pool.** `createProxyPool` builds one `http.Client` per proxy URL, with identical transport settings to the direct path plus `Proxy: http.ProxyURL(proxyURL)`. On every outbound call, `GetClient()` selects the next client via `atomic.AddUint64(&counter, 1) % len(clients)` — a lock-free round-robin. Counter wraps naturally at `uint64` overflow; it is never reset. On error (empty pool), the client falls back to the direct transport and logs an error. **Proxy URL validation** uses a case-insensitive prefix check, not `url.Parse`: only `http://`, `https://`, and `socks5://` are accepted. `socks4://`, `ws://`, and any other scheme fail at startup. **Shutdown.** A goroutine watches `appCtx.Done()` and drains the in-flight batch. Already-canceled contexts in the queue are dropped silently. **Test mode.** When `util.IsTest()` is true, the client substitutes `http.DefaultTransport` to allow gock mock interceptors. ### Config schema #### `proxyPools[]` — top-level array ([`common/config.go:L48`](https://github.com/erpc/erpc/blob/main/common/config.go#L48)) | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `proxyPools[].id` | `string` | required | Pool name referenced by `upstream.jsonRpc.proxyPool`. Must be unique. Non-existent ID referenced by an upstream fails at startup. Source: [`clients/proxy_pool_registry.go:L58`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L58) | | `proxyPools[].urls` | `[]string` | required, min 1 | Proxy URLs. Empty list fails with `"proxyPool.*.urls is required..."`. Each URL is lowercased then checked via `strings.HasPrefix` against `"http://"`, `"https://"`, or `"socks5://"` — not `url.Parse`. `socks4://` and all other schemes fail validation and prevent eRPC from starting. Each valid URL gets its own `http.Client` with identical transport settings. Source: [`common/validation.go:L230-247`](https://github.com/erpc/erpc/blob/main/common/validation.go#L230-L247) | #### `upstreams[].jsonRpc.*` (also `upstreamDefaults.jsonRpc.*`) All fields are optional. `JsonRpcUpstreamConfig.SetDefaults()` is a no-op; pointer-zero fields retain Go zero values. **Important:** when an upstream has no `jsonRpc:` block at all, the full `upstreamDefaults.jsonRpc` struct is shallow-copied. But if any `jsonRpc:` block is present (even `jsonRpc: {}`), field-level defaults are not merged — inheritance is all-or-nothing. | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `supportsBatch` | `*bool` | `nil` (false) | Enables batch aggregation. `nil` or `false` → every request is a direct single HTTP call. Source: [`clients/http_json_rpc_client.go:L132-137`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L132-L137) | | `batchMaxSize` | `int` | `0` | Max requests per batch; batch fires immediately when reached. **Footgun:** `0` with `supportsBatch: true` evaluates as `1 >= 0` (always true) and fires on the first queued request, disabling coalescing. Use `≥ 2`. Source: [`clients/http_json_rpc_client.go:L294-300`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L294-L300) | | `batchMaxWait` | `Duration` | zero (instant) | How long to wait before flushing. `time.AfterFunc(0, fn)` schedules immediately. **Footgun:** zero disables coalescing. Set `"10ms"` or similar for meaningful batching. Source: [`clients/http_json_rpc_client.go:L289-291`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L289-L291) | | `enableGzip` | `*bool` | `nil` (false) | Compresses outbound request body with a pooled `gzip.Writer`; adds `Content-Encoding: gzip`. Decompression of responses is always active regardless. Independent of `server.enableGzip`. Source: [`clients/http_json_rpc_client.go:L139-142`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L139-L142) | | `headers` | `map[string]string` | `nil` | Static headers on every outbound request. Applied via `Header.Set` (overwrites). Runs after built-in defaults but before OTel injection — `traceparent` cannot be overridden. Source: [`clients/http_json_rpc_client.go:L838-847`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L838-L847) | | `proxyPool` | `string` | `""` (direct) | ID of a `proxyPools[]` entry. Resolved at client creation; non-existent ID fails at startup. Empty string → direct transport. Source: [`clients/proxy_pool_registry.go:L107-111`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L107-L111) | #### Fixed transport parameters (not user-configurable) Same values apply to both direct and proxy transports (source: [`clients/http_json_rpc_client.go:L109-128`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L109-L128), [`clients/proxy_pool_registry.go:L82-98`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L82-L98)). | Parameter | Value | Purpose | |---|---|---| | `DialContext` | `net.Dialer{Timeout: 10s, KeepAlive: 15s}` | Dial timeout + TCP keepalive probe interval | | `MaxIdleConns` | `1024` | Global idle connection pool | | `MaxIdleConnsPerHost` | `256` | Per-host idle connection limit | | `MaxConnsPerHost` | `0` (unlimited) | Prevents connection queuing under high RPS / high latency | | `IdleConnTimeout` | `90s` | Idle connection closure | | `ResponseHeaderTimeout` | `30s` | Time to first response header byte | | `TLSHandshakeTimeout` | `10s` | TLS negotiation deadline | | `ExpectContinueTimeout` | `1s` | 100-continue wait | | `http.Client.Timeout` | `60s` | End-to-end timeout including body read | ### Worked examples **1. SOCKS5 proxy rotation for IP-diverse egress.** Multiple providers rate-limit by source IP. Routing requests through a pool of residential or datacenter proxies distributes the source IP fingerprint and avoids per-IP throttles: **Config path:** `proxyPools` **YAML — `erpc.yaml`:** ```yaml proxyPools: - id: egress-proxies urls: - socks5://proxy1.example.com:1080 - socks5://proxy2.example.com:1080 - socks5://proxy3.example.com:1080 projects: - id: main upstreams: - endpoint: https://mainnet.infura.io/v3/KEY jsonRpc: proxyPool: egress-proxies ``` **TypeScript — `erpc.ts`:** ```typescript proxyPools: [{ id: "egress-proxies", urls: [ "socks5://proxy1.example.com:1080", "socks5://proxy2.example.com:1080", "socks5://proxy3.example.com:1080", ], }] ``` **2. Batch aggregation for high-QPS read workloads.** An indexer fires hundreds of `eth_getTransactionReceipt` calls per second. Batching coalesces them into fewer HTTP round-trips, reducing latency and upstream connection overhead. Set `batchMaxSize` and `batchMaxWait` together so batches fill before the timer fires: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - endpoint: https://mainnet.infura.io/v3/KEY jsonRpc: supportsBatch: true batchMaxSize: 50 batchMaxWait: 10ms ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ endpoint: "https://mainnet.infura.io/v3/KEY", jsonRpc: { supportsBatch: true, batchMaxSize: 50, batchMaxWait: "10ms", }, }] ``` **3. Gzip + custom API-key header.** Enable request compression and inject a bearer token on every upstream call. The token is sent via `Header.Set` after the built-in defaults, so it cannot accidentally stomp `traceparent`: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - endpoint: https://rpc.example.com jsonRpc: enableGzip: true headers: Authorization: "Bearer my-secret-key" ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [{ endpoint: "https://rpc.example.com", jsonRpc: { enableGzip: true, headers: { Authorization: "Bearer my-secret-key" }, }, }] ``` **4. Shared defaults across all upstreams.** Use `upstreamDefaults.jsonRpc` to apply batch + gzip to every upstream without repeating config. Note: any upstream that defines its own `jsonRpc:` block (even empty) does not inherit from `upstreamDefaults.jsonRpc`: **Config path:** `projects[].upstreamDefaults` **YAML — `erpc.yaml`:** ```yaml projects: - id: main upstreamDefaults: jsonRpc: supportsBatch: true batchMaxSize: 20 batchMaxWait: 5ms enableGzip: true upstreams: - endpoint: https://rpc-a.example.com - endpoint: https://rpc-b.example.com ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", upstreamDefaults: { jsonRpc: { supportsBatch: true, batchMaxSize: 20, batchMaxWait: "5ms", enableGzip: true, }, }, upstreams: [ { endpoint: "https://rpc-a.example.com" }, { endpoint: "https://rpc-b.example.com" }, ], }] ``` ### Request/response behavior **Outbound HTTP request shape (single):** ``` POST Content-Type: application/json Accept-Encoding: gzip User-Agent: erpc (/; Project/) [Content-Encoding: gzip] — only when enableGzip=true [] — from jsonRpc.headers, via Header.Set [traceparent: ...] — OTel W3C trace context (injected last) [baggage: ...] [] — only on single requests, from project.forwardHeaders Body: {"jsonrpc":"2.0","method":"...","params":[...],"id":...} ``` **Outbound HTTP request shape (batch):** Same headers except forwarded headers (absent). Body is a JSON array of `JsonRpcRequest` objects. **Batch response matching:** - Array response: each element's `id` is looked up in the queued request map; matched response returned to caller. Unmatched IDs produce `"no response received for request ID: N"` (logged as ERROR with full body). - Single-object response: broadcast to ALL callers. Handles rate-limit errors returned as `{"error":{...},"id":null}` for the whole batch. - Non-JSON response: parsed as JSON-RPC error and broadcast; if that fails, all callers receive the parse error. **Error type mapping:** | Condition | Error type | |---|---| | Transport-level failure | `ErrEndpointTransportFailure` | | `context.DeadlineExceeded` / `ErrDynamicTimeoutExceeded` | `ErrEndpointRequestTimeout` | | `context.Canceled` | `ErrEndpointRequestCanceled` | | JSON-RPC error message containing `"context canceled"` | `ErrEndpointRequestCanceled` (reclassified) | | JSON-RPC error message containing `"context deadline exceeded"` | `ErrEndpointRequestTimeout` (reclassified) | | Unparseable JSON body | `ErrJsonRpcExceptionInternal/ParseException` | | Upstream `error` field in response | `ErrJsonRpcExceptionInternal/ServerSideException` (after extractor) | | Batch response body is not array or object | `ErrUpstreamMalformedResponse` (retryable) | | Pre-request creation error (e.g. failed to build `http.Request`) | `ErrHttp` (BaseError) | **Behavioral invariants:** - `ClientRegistry.GetOrCreateClient` uses `sync.Map` + `sync.Once`; all callers for the same upstream share exactly one client instance. [[`clients/registry.go:L47-125`](https://github.com/erpc/erpc/blob/main/clients/registry.go#L47-L125)] - OTel `traceparent` + `baggage` are injected on every request, including retried and batched calls. [[`clients/http_json_rpc_client.go:L845-847`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L845-L847)] - Both single and batch paths decompress gzip responses whenever `Content-Encoding: gzip` is present. [[`clients/http_json_rpc_client.go:L852-867`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L852-L867)] - At shutdown, `appCtx.Done()` triggers `processBatch(true)` to drain in-flight batches; already-canceled contexts in the queue are dropped silently. [[`clients/http_json_rpc_client.go:L211-217`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L211-L217)] - **Pre-queue cancellation check.** `queueRequest` inspects `req.ctx.Err()` before inserting into the batch map. Already-canceled requests are immediately failed with `ErrEndpointRequestTimeout` or `ErrEndpointRequestCanceled` without touching the network. [[`clients/http_json_rpc_client.go:L241-253`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L241-L253)] - **Post-queue pre-send cancellation drop.** Inside `processBatch`, a pass over the queued requests drops any entry whose `ctx.Err()` is non-nil before the HTTP call is made. [[`clients/http_json_rpc_client.go:L349-361`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L349-L361)] ### Best practices - **Set both `batchMaxSize` and `batchMaxWait` together.** Either alone produces degenerate behavior: `batchMaxSize: 0` fires on every first request (size check `1 >= 0`); `batchMaxWait: 0` fires before other requests can join. Use at minimum `batchMaxSize: 10` + `batchMaxWait: "10ms"` for meaningful coalescing. - **Do not use `supportsBatch: true` for upstreams receiving forwarded `Authorization` headers.** Forwarded headers are applied only on single requests; batch requests share one outbound call and carry no per-caller headers. - **Prefer `upstreamDefaults.jsonRpc` to avoid repetition — but know it is all-or-nothing.** Any upstream with an explicit `jsonRpc:` block (even `jsonRpc: {}`) does not inherit defaults field-by-field. Either use defaults everywhere or configure each upstream fully. - **`enableGzip: true` is worth enabling for most RPC endpoints.** JSON-RPC responses (especially `eth_getLogs`, `debug_traceTransaction`) compress well. The reader and writer are pooled, so CPU overhead is minimal. - **Add at least 3 proxy URLs per pool.** With a single-URL pool the round-robin is meaningless (always index 0); with 2 the distribution is uneven under any non-even request count. Three or more gives meaningful rotation. - **Proxy scheme validation is strict at startup.** Test proxy URLs locally before deploying — `socks4://` and other schemes will prevent eRPC from starting with no graceful fallback. - **There is no per-upstream TLS configuration.** Custom CA bundles, client certs, and `InsecureSkipVerify` are not supported. If an upstream requires mutual TLS or a private CA, the connection must be proxied through a sidecar or gateway that handles TLS termination. ### Edge cases & gotchas 1. **`batchMaxSize: 0` with `supportsBatch: true` fires instantly.** The request is added to the queue before the size check (`len >= batchMaxSize`), so the check evaluates as `1 >= 0` (always true). Use `batchMaxSize: 2` or higher. Source: [`clients/http_json_rpc_client.go:L294`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L294) 2. **`batchMaxWait: 0` (default) fires instantly.** `time.AfterFunc(0, fn)` schedules in a new goroutine immediately. Set a non-zero duration to enable coalescing. Source: [`clients/http_json_rpc_client.go:L291`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L291) 3. **Duplicate JSON-RPC IDs within a batch window flush the pending batch.** The in-flight batch fires immediately and the duplicate starts a fresh batch. Clients that reuse IDs will see reduced batch efficiency. Source: [`clients/http_json_rpc_client.go:L255-261`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L255-L261) 4. **Custom `headers` overwrite built-in defaults.** `Header.Set` replaces any existing value. A `headers: {Content-Type: text/plain}` will overwrite `application/json`. OTel headers are injected after and cannot be overridden. Source: [`clients/http_json_rpc_client.go:L838-847`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L838-L847) 5. **Forwarded headers are absent on batch requests.** Callers relying on `Authorization` or custom headers forwarded to upstreams must not enable `supportsBatch` for those upstreams. Source: [`clients/http_json_rpc_client.go:L736-742`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L736-L742) 6. **`upstreamDefaults.jsonRpc` is all-or-nothing.** If an upstream has any `jsonRpc:` block (even empty `jsonRpc: {}`), defaults are not merged field-by-field. Source: [`common/defaults.go:L1550-1558`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1550-L1558) 7. **Proxy URL scheme check is a `strings.HasPrefix` after `strings.ToLower`, not `url.Parse`.** `socks4://`, `ws://`, `ftp://`, and other schemes fail at startup regardless of syntactic validity. Only `http://`, `https://`, `socks5://` are accepted. Source: [`common/validation.go:L238-244`](https://github.com/erpc/erpc/blob/main/common/validation.go#L238-L244) 8. **Empty proxy pool falls back to direct transport.** If `GetClient` returns an error (pool created with zero URLs), the client logs an error and uses the direct transport. Startup validation should prevent this in production. Source: [`clients/proxy_pool_registry.go:L69-71`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L69-L71) 9. **`MaxConnsPerHost: 0` is deliberate.** Go's prior default of 2 capped throughput at ~5 req/s per host with 400ms latency. Unlimited removes the queue; the OS TCP stack becomes the only cap. Source: [`clients/http_connection_test.go:L141-414`](https://github.com/erpc/erpc/blob/main/clients/http_connection_test.go#L141-L414) 10. **No per-upstream TLS configuration.** Custom CA bundles, client certificates, and `InsecureSkipVerify` are not supported for HTTP upstreams. Go uses the system CA bundle. Source: [`clients/http_json_rpc_client.go:L109-118`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L109-L118) 11. **HTTP/2 is not explicitly enabled.** `ForceAttemptHTTP2` is not set. HTTP/2 may negotiate via ALPN on `https://` upstreams that offer it, but this is unverified. Proxy transports are HTTP/1.1 tunnels. Source: [`clients/http_json_rpc_client.go:L109-118`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L109-L118) 12. **Batch single-object response broadcasts to all callers.** When an upstream returns `{"jsonrpc":"2.0","error":{...},"id":null}`, every pending request in the batch receives the same response — intended for upstream-wide rate-limit errors. Source: [`clients/http_json_rpc_client.go:L606-636`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L606-L636) 13. **Partial batch response leaves unmatched callers with an error.** If the array is shorter than queued requests, absent IDs receive `"no response received for request ID: N"`, logged as ERROR with the full response body. Source: [`clients/http_json_rpc_client.go:L597-605`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L597-L605) 14. **5ms race-fix window for timeout sentinels in batch.** When `batchCtx` expires with `DeadlineExceeded`, the per-request context `Cause` may lag by a few microseconds. The client waits up to 5ms for the cause to stabilize so `ErrDynamicTimeoutExceeded` sentinels are preserved for the upstream classifier. Source: [`clients/http_json_rpc_client.go:L471-479`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L471-L479) 15. **`ErrUpstreamMalformedResponse` is retryable.** Raised when a batch response body is neither a JSON array nor object. Not in the non-retryable allowlist — eRPC will try another upstream. If all upstreams return malformed responses, the request ends as `ErrUpstreamsExhausted`. Source: [`common/errors.go:L835-858`](https://github.com/erpc/erpc/blob/main/common/errors.go#L835-L858) 16. **`ErrEndpointServerSideException.originalStatusCode` zero-value fallback is 500.** When `originalStatusCode == 0` (e.g. synthetic gRPC status), `ErrorStatusCode()` returns 500. A 500 from eRPC does not necessarily mean the upstream returned 500. Source: [`common/errors.go:L1974-1979`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1974-L1979) 17. **`JsonRpcErrorExtractor` is wired once at startup.** The EVM extractor is injected at `UpstreamsRegistry` construction and cannot be changed at runtime. Non-EVM architectures require a code change to swap extractors. Source: [`upstream/registry.go:L79`](https://github.com/erpc/erpc/blob/main/upstream/registry.go#L79) 18. **`ErrUpstreamMalformedResponse` method-level 400 vs wire-level 200 discrepancy.** `ErrorStatusCode()` returns 400, which appears in eRPC logs and metrics labels. However, the HTTP response to the calling client is sent with wire-level HTTP 200 (standard JSON-RPC transport), and the 400 appears only inside the JSON-RPC error envelope's metadata. The 400 is not visible in the HTTP response line seen by callers — only in logs and `erpc_upstream_request_errors_total`. Source: [`common/errors.go:L856-858`](https://github.com/erpc/erpc/blob/main/common/errors.go#L856-L858) 19. **`ErrEndpointServerSideException` is retryable toward both upstream and network.** The error code is not in the non-retryable allowlist in `IsRetryableTowardsUpstream`, so eRPC will attempt another upstream. A 500 fallback (when `originalStatusCode == 0`) does not mean the error is deterministic. Source: [`common/errors.go:L1951-1979`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1951-L1979) 20. **`proxyPool` is set twice when `jsonRpcCfg != nil`.** `NewGenericHttpJsonRpcClient` assigns `client.proxyPool = proxyPool` in the struct literal and then again unconditionally inside the `if jsonRpcCfg != nil` block. The net effect is always the passed value — harmless but worth noting when reading the code. Source: [`clients/http_json_rpc_client.go:L91-148`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L91-L148) ### Observability The HTTP client layer emits no Prometheus metrics directly. All upstream-level metrics are recorded by `upstream/upstream.go` and `health/tracker.go` which wrap the client calls. Errors originating in the HTTP client surface under these metrics: | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_total` | counter | project, network, upstream, category, method | Every upstream attempt including batched calls | | `erpc_upstream_request_errors_total` | counter | project, network, upstream, category, error_type | Transport failures, timeouts, malformed responses; `error_type=ErrUpstreamMalformedResponse` visible here | | `erpc_upstream_request_duration_seconds` | histogram | project, network, upstream, category | End-to-end duration per upstream call | **Trace spans.** Single requests produce an `HttpJsonRpcClient.sendSingleRequest` span with `network.id`, `upstream.id`, and (at detailed tracing level) `request.id` and `request.method` attributes. Batch requests do not create per-call spans; they run under the propagated caller context. **Log messages (key entries):** - `DEBUG` `"sending json rpc POST request (single|batch)"` — host, raw request body, headers - `DEBUG` `"queuing request ... for batch (current batch size: N)"` - `DEBUG` `"processing batch with N requests"` - `TRACE` `"using client from proxy pool"` — pool ID, transport pointer, resolved proxy URL - `TRACE` `"starting batch timer"`, `"setting batch deadline to earliest request deadline"`, `"committing batch to process total of N requests"` - `TRACE` response body (first 20 KiB + last 20 KiB when response body is oversized) - `ERROR` `"failed to get client from proxy pool"` — when `ProxyPool.GetClient` returns error (empty pool) - `WARN` `"unexpected response received without ID"` — batch response element has no `id` field - `WARN` `"unexpected response received with ID: "` — batch response ID not in pending request map - `ERROR` `"some requests did not receive a response (matching ID)"` — with full response body ### Source code entry points - [`clients/http_json_rpc_client.go:L89-L148`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L89-L148) — `NewGenericHttpJsonRpcClient`: transport construction, field initialization, gzip and batch config - [`clients/http_json_rpc_client.go:L786-L951`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L786-L951) — `prepareRequest`, `sendSingleRequest`, `normalizeJsonRpcError`: request shape, OTel injection, error classification - [`clients/http_json_rpc_client.go:L241-L479`](https://github.com/erpc/erpc/blob/main/clients/http_json_rpc_client.go#L241-L479) — `queueRequest`, `processBatch`: batch aggregation, deadline propagation, context pre-checks - [`clients/registry.go:L47-L125`](https://github.com/erpc/erpc/blob/main/clients/registry.go#L47-L125) — `ClientRegistry.GetOrCreateClient` / `CreateClient`: sync.Map cache, scheme dispatch, proxy pool resolution - [`clients/proxy_pool_registry.go:L23-L98`](https://github.com/erpc/erpc/blob/main/clients/proxy_pool_registry.go#L23-L98) — `ProxyPool.GetClient` (round-robin), `createProxyPool`, proxy transport construction - [`util/http_dialer.go:L8-L24`](https://github.com/erpc/erpc/blob/main/util/http_dialer.go#L8-L24) — `DefaultOutboundDialer`: `net.Dialer{Timeout: 10s, KeepAlive: 15s}` - [`common/validation.go:L230-L247`](https://github.com/erpc/erpc/blob/main/common/validation.go#L230-L247) — `ProxyPoolConfig.Validate`: ID required, URLs non-empty, prefix scheme check - [`common/error_extractor.go:L10-L21`](https://github.com/erpc/erpc/blob/main/common/error_extractor.go#L10-L21) — `JsonRpcErrorExtractor` interface + `JsonRpcErrorExtractorFunc` adapter - [`common/errors.go:L835-L858`](https://github.com/erpc/erpc/blob/main/common/errors.go#L835-L858) — `ErrUpstreamMalformedResponse`: meaning, `ErrorStatusCode` returns 400, retryable - [`common/errors.go:L1951-L1979`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1951-L1979) — `ErrEndpointServerSideException`: `originalStatusCode` field, 500 fallback - [`clients/http_connection_test.go`](https://github.com/erpc/erpc/blob/main/clients/http_connection_test.go) — behavior-locking tests validating `MaxConnsPerHost: 0` fix under load - [`common/config.go:L1072-L1079`](https://github.com/erpc/erpc/blob/main/common/config.go#L1072-L1079) — `JsonRpcUpstreamConfig` struct definition - [`common/config.go:L1985-L1988`](https://github.com/erpc/erpc/blob/main/common/config.go#L1985-L1988) — `ProxyPoolConfig` struct definition - [`common/defaults.go:L1700-L1704`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L1700-L1704) — unconditional `u.JsonRpc = &JsonRpcUpstreamConfig{}` if nil before `SetDefaults()` ### Related pages - [Retry](/config/failsafe/retry.llms.txt) — retry policy wrapping upstream calls; transport errors flow through here. - [Timeout](/config/failsafe/timeout.llms.txt) — per-request timeout bounds that feed `ErrDynamicTimeoutExceeded` into the batch deadline path. - [Rate limiters](/config/rate-limiters.llms.txt) — cap outbound RPS per upstream or proxy pool to stay within provider budgets. - [Upstreams](/config/projects/upstreams.llms.txt) — full upstream config including `endpoint`, `jsonRpc`, and `upstreamDefaults`. - [Selection policies](/config/projects/selection-policies.llms.txt) — how eRPC chooses which upstream (and which proxy-pool-backed client) receives each request. --- --- # Lanes & concurrency > Source: https://docs.erpc.cloud/reference/lanes > Route a class of requests to a specific provider group and eRPC computes that group's own block tip — eliminating "block not found" churn caused by cross-provider tip pollution. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Lanes & concurrency Different provider classes see different blocks at different times. When you route flashblock RPCs to one provider group and archive calls to another, eRPC automatically tracks a separate block tip for each group. The right tip reaches the right upstreams — no cross-provider contamination, no spurious `block not found` errors. What you get: - Per-group served tip decided among that group's upstreams only - Deterministic lane names on your Prometheus dashboards (`flashblocks`, `systx`, …) - Zero config — lanes emerge automatically from your `use-upstream` selectors ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: pin all traffic on a network to flashblocks upstreams** ```text I want all requests on my Ethereum mainnet network to route exclusively to flashblocks providers so the block tip is always flashblocks-accurate. Set directivesDefaults.useUpstream at the network level in my eRPC config, and explain when a selector qualifies for a named lane versus getting no lane gauges. Reference: https://docs.erpc.cloud/reference/lanes.llms.txt ``` **Prompt Example #2: route archive calls to a dedicated upstream group** ```text I have archive-depth upstreams tagged family:archive and I want heavy getLogs / debug trace calls to route to them while fast reads go to my premium upstreams. Configure use-upstream selectors and explain how eRPC derives a stable lane name for Prometheus dashboards. Work with my existing eRPC config. Reference: https://docs.erpc.cloud/reference/lanes.llms.txt ``` **Prompt Example #3: debug missing lane metrics in Prometheus** ```text My Prometheus shows erpc_network_served_tip_block_number with lane=all but never a named lane label even though I'm sending X-ERPC-Use-Upstream headers. Explain the conditions that prevent a lane from forming (complex selector, fewer than 2 upstreams matched, all upstreams matched, 16-lane cap reached) and check my eRPC config for the likely cause. Reference: https://docs.erpc.cloud/reference/lanes.llms.txt ``` --- ### Lanes & concurrency — full agent reference ### How it works A **lane** is not a config object. It is an emergent artifact: when a request carries a `use-upstream` selector (via `X-ERPC-Use-Upstream` header, `?use-upstream=` query parameter, or `directivesDefaults.useUpstream` in config), eRPC resolves which upstreams match. If the matched set is a proper subset of at least two upstreams — and the selector is "simple" (see below) — eRPC derives a stable key by SHA-256-hashing the sorted upstream IDs, then lazily creates a `servedTipLane` for that key (`servedTipLaneFor`). A lane holds no pick state: only its label and, per axis, an in-process anchor for the advance-age gauge, the regression guard's memory and, on `finalized`, the [finalized floor](/reference/evm/block-tracking.llms.txt#finalized-floor). The network-wide pick is the lane `servedTipAll`, labelled `"all"`. The tip itself is the [served-tip rule](/reference/evm/block-tracking.llms.txt#served-tip) over the matched subset, computed fresh for every selector, lane or not. Only the network-wide lane's finalized floor is shared across pods. Source: [`erpc/networks.go:L113-132`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L113-L132), [`erpc/networks.go:L628-655`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L628-L655) **LaneName algorithm.** `LaneName(ids)` sorts the upstream IDs alphabetically, then builds a set of non-empty hyphen-split tokens for each ID (empty strings from consecutive hyphens are discarded). It walks the tokens of the first sorted ID and returns the first token that appears in every other ID's token set. If no universally shared token exists, it falls back to a concatenation of the first two characters of each ID (up to five IDs). The result is deterministic and order-independent — every pod reaches the same name from the same upstream topology. Source: [`common/lane.go:L25`](https://github.com/erpc/erpc/blob/main/common/lane.go#L25) **What counts as a "simple" selector.** `isSimpleGroupSelector` rejects selectors that contain whitespace, `|`, `&`, `(`, `)`, or `,` (no boolean combinators), or more than one `!` not at position 0, or length > 128 characters. Qualifying examples: `flashblocks*`, `!flashblocks*`, `family:systx`, `alchemy-*`. Non-qualifying: `alchemy | quicknode`, `(a | b)`. **Lane lifecycle and cap.** Lanes are stored in a `sync.Map` keyed by `"grp:"` (the first 8 bytes of the SHA-256 digest encoded as 16 hex characters). On the fast path, `sync.Map.Load` returns an existing lane with no locking. On the slow path, an `atomic.Int32` counter is checked against `maxServedTipLanes = 16`; if at the cap, the request gets the same subset pick with no lane. Because the check-and-create is not atomic, up to `16 + goroutine-concurrency` lanes can transiently exist — `LoadOrStore` guarantees exactly one lane wins per key. The lane key is derived from the **matched upstream set**, not the selector text. `flashblocks*` and `fl*` targeting the same three upstreams produce the same key and share one lane. Cardinality is bounded by the actual upstream topology, not selector diversity. **Method subsets.** Only upstreams that serve the request's method (`ignoreMethods`/`allowMethods`) vote on its [served tip](/reference/evm/block-tracking.llms.txt#served-tip). A request whose method every upstream serves, or none does, uses its selector's lane. One whose method only some upstreams serve forms no lane of its own: it reads its selector lane's view capped at the block `servedTip.quorum` of the serving upstreams hold, with the stateless pick (no guard, no finalized floor, no gauges). Each method's voter set is built on its first request and rebuilt when the network's upstreams or an upstream's method filter change; a request reads it with one lookup. Only method names the config or the built-in tables define exactly are cached; a casing variant (`ETH_CALL`) or an unknown name is resolved per request. **No lane.** When a selector is complex, matches fewer than two upstreams, matches all upstreams, or arrives past the cap, `laneFor` returns nil. The subset pick still applies, with no regression guard, no anchor and no gauge write, so a subset value never overwrites the `lane="all"` gauge. **UseUpstream directive precedence** (highest to lowest): 1. `X-ERPC-Use-Upstream` header on the request. 2. `?use-upstream=` query parameter. 3. `networks[*].directivesDefaults.useUpstream` config default. The selector is used in two places: to narrow the served-tip ballot (and resolve its lane), and inside the upstream selection loop (`UpstreamMatchesSelector`) to filter which upstreams receive the request. Tag-based matching is supported — `family:flashblocks` matches any upstream whose tags include that key — but negated selectors (prefix `!`) never match by tag, only by upstream ID. ### Config schema | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[*].directivesDefaults.useUpstream` | `*string` | `nil` (no default selector) | Sets the `use-upstream` selector for all requests on this network when the client sends none. Identical semantics to the `X-ERPC-Use-Upstream` header. **Footgun:** a selector matching all upstreams forms no lane: its pick runs over the same upstreams as the network-wide one, but without the regression guard or any gauge. Sources: [`common/config.go:L2109`](https://github.com/erpc/erpc/blob/main/common/config.go#L2109), [`common/request.go:L589-590`](https://github.com/erpc/erpc/blob/main/common/request.go#L589-L590) | Lanes themselves are not directly configured — they emerge from runtime request selectors and the upstream topology. They need no `servedTip` block; `servedTip.quorum` applies inside each lane as it does network-wide. ### Worked examples **1. Pin all network traffic to flashblocks upstreams.** Set `directivesDefaults.useUpstream` at the network level so every request on that chain automatically routes to flashblocks providers and gets a flashblocks-accurate tip: **Config path:** `projects[].networks[].directivesDefaults.useUpstream` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: { chainId: 1 } directivesDefaults: useUpstream: "flashblocks*" # all requests → flashblocks lane ``` **TypeScript — `erpc.ts`:** ```typescript import { createConfig } from "@erpc-cloud/config"; export default createConfig({ projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1 }, directivesDefaults: { useUpstream: "flashblocks*", }, }], }], }); ``` **2. Per-request lane selection via header.** Send `X-ERPC-Use-Upstream: systx*` on individual requests to route them to system-transaction-capable upstreams. eRPC derives the lane name, computes a `systx`-scoped tip, and serves block numbers visible to that provider class only. **3. Tag-based lane targeting.** If upstreams are tagged with `family:archive`, a selector `family:archive` is simple, qualifies for a lane, and routes archive-depth calls to archive nodes — `LaneName` derives a human-readable label from the matched upstream IDs for your dashboards. **4. Complex selector routing without lane tip tracking.** A selector like `alchemy | quicknode` routes to both providers correctly via `UpstreamMatchesSelector` in the forwarding loop — but it is not simple, so no lane is created and no `lane=...` gauge appears. The tip is still computed over the two providers; this is expected behavior for multi-provider round-robin. ### Best practices - Use simple glob selectors (`flashblocks*`, `family:archive`) rather than boolean expressions when you need per-group gauges or the regression guard; boolean selectors route and scope the tip correctly but never get a lane. - Set `directivesDefaults.useUpstream` at the network level rather than injecting headers per-request — it ensures every request (including retries and hedges) carries the selector without client cooperation. - Keep the total number of distinct upstream subsets below 16 per network; beyond that, additional groups get no gauges and no regression guard. - Do not rely on `LaneName` label values being unique — two different upstream sets can produce the same label. Use the lane key (internal) as the stable identifier; the label is for human readability only. - Negated selectors (`!alchemy-*`) match by upstream ID only, not by tag. If you need tag-based exclusion, restructure as an inclusion selector on the desired tag instead. ### Edge cases & gotchas 1. **A single matched upstream does not form a lane.** `partitionKeyFor` requires `len(matched) >= 2`; a single-upstream selector gets that upstream's head and emits no gauge. 2. **Matching ALL upstreams does not form a lane.** `len(matched) >= len(all)` also falls through, preventing a match-all selector from shadowing `lane="all"`. 3. **Boolean combinator selectors are never partitioned.** `alchemy | quicknode` contains `|`; it routes and scopes the tip correctly but never gets a lane. 4. **The 16-lane cap is a soft guard.** Concurrent goroutines can transiently exceed 16. Beyond the cap, new groups get no lane. 5. **Lane key = hash of matched upstream set, not selector text.** `flashblocks*` and `fl*` matching the same upstreams share one lane. Cardinality is bounded by topology, not by selector diversity. 6. **`LaneName` is not guaranteed unique.** Two different upstream sets could produce the same name if both share the same common token. The lane key is the stable identifier; the name is decorative for dashboards. 7. **Negated selectors match by ID only, never by tag.** A pattern containing `!` skips tag evaluation entirely. `!alchemy-*` excludes by ID but will not rescue non-matching IDs via tags. 8. **`LaneName` sort is alphabetical.** For `(quicknode-systx, systx-quicknode)`, sorted order puts `quicknode-systx` first; `LaneName` returns `"quicknode"`, not `"systx"`. Source: `common/lane_test.go` (`order independent` test). 9. **Lane state is per process.** Anchors, regression-guard memory and finalized floors live in memory; a restarted pod rebuilds them from live heads. The network-wide lane's finalized floor is also shared across pods, so a restarted pod serves it again once one of its voters reports it. 10. **`LaneName` output is written to Prometheus labels as-is, without sanitization.** If upstream IDs contain unusual characters that cause `LaneName` to produce an unexpected string, that string becomes the label value verbatim. The label is never normalized or escaped beyond what `LaneName` itself produces. ### Observability Lanes are the `lane` label of the four `erpc_network_served_tip_*` series ([meanings](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking)): `lane="all"` is the network-wide pick (`servedTipAll`), `lane=` a group's own pick. A named lane's series exist only for networks that receive targeted `use-upstream` traffic; a request without a lane writes no series. Source: [`erpc/networks.go:L1647-1677`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1647-L1677) ### Source code entry points - [`common/lane.go`](https://github.com/erpc/erpc/blob/main/common/lane.go) — `LaneName(ids []string) string`: naming algorithm, pure function. - [`common/lane_test.go`](https://github.com/erpc/erpc/blob/main/common/lane_test.go) — unit tests for `LaneName`: shared-token precedence, order-independence, fallback combo, single-id, empty input, determinism. - [`erpc/networks.go:L117-L137`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L117-L137) — `maxServedTipLanes = 16`, `servedTipLane` struct. - [`erpc/networks.go:L640-L667`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L640-L667) — `servedTipLaneFor`: lazy lane materialization with cap and `sync.Map`. - [`erpc/networks.go:L669-L758`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L669-L758) — `partitionKeyFor`: selector → SHA-256 key; `EvmUpstreamGroupForSelector`; `isSimpleGroupSelector` filter. - [`erpc/networks.go:L883-L971`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L883-L971) — `servedTip`: guard, floors and gauges per lane. - [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) — `bindLaneGauges`, `servedTipGauges.observe`: gauges bound once per lane label. - [`common/matcher.go:L73-L112`](https://github.com/erpc/erpc/blob/main/common/matcher.go#L73-L112) — `MatchesSelector` + `UpstreamMatchesSelector`: ID + tag matching primitive. - [`common/request.go:L739-L741`](https://github.com/erpc/erpc/blob/main/common/request.go#L739-L741) — `X-ERPC-Use-Upstream` header extraction. - [`common/request.go:L811-L812`](https://github.com/erpc/erpc/blob/main/common/request.go#L811-L812) — `?use-upstream=` query-param extraction. - [`common/request.go:L1424-L1445`](https://github.com/erpc/erpc/blob/main/common/request.go#L1424-L1445) — `UpstreamMatchesSelector` call in the upstream selection loop; filters which upstreams receive the forwarded request. - [`erpc/networks.go:L630-L639`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L630-L639) — `requestSelector(ctx)`: reads `UseUpstream` directive from the bound request context for both served-tip and forwarding use. - [`common/config.go:L2109`](https://github.com/erpc/erpc/blob/main/common/config.go#L2109) — `DirectivesConfig.UseUpstream` field. - [`telemetry/metrics.go:L198-L250`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L198-L250) — metric definitions. ### Related pages - [Matcher](/config/matcher.llms.txt) — the `UpstreamMatchesSelector` and tag-matching primitives used to resolve which upstreams a selector targets. - [Tag-aware routing](/config/projects/selection-policies.llms.txt) — how `use-upstream` integrates with the upstream selection loop. - [Block tracking & served tip](/reference/evm/block-tracking.llms.txt) — the served-tip rule that lanes scope. - [Rate limiters](/config/rate-limiters.llms.txt) — per-upstream rate limits that interact with lane-scoped routing. --- --- # Metrics reference > Source: https://docs.erpc.cloud/reference/metrics > Every observable signal eRPC emits — 141 Prometheus metrics across upstreams, cache, rate limiting, consensus, hedging, and more — ready to wire into your dashboards and alerts. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Metrics reference eRPC exposes a Prometheus `/metrics` endpoint on port 4001. Every subsystem emits counters, gauges, and histograms — upstream health, cache efficiency, rate limiting, consensus, hedging, selection scoring, and more. Drop any scraper on port 4001 and the full picture of your RPC fleet is immediately visible. - 141 metric definitions under the `erpc_` namespace - One knob shapes the whole page: `metrics.customizations` drops families, projects labels, and overrides histogram buckets — a dropped family costs no series at all - High-cardinality labels (`user`, `agent_name`) are droppable fleet-wide and re-addable per metric - Stale series auto-evict every five minutes so cardinality stays bounded ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: wire up Grafana dashboards for my eRPC deployment** ```text I want to build Grafana dashboards for my eRPC deployment — upstream health, cache hit rate, request latency percentiles, and rate-limit events. Using the full metrics catalog, generate PromQL queries for each panel and point out any cardinality footguns I should avoid (like the block-range heatmap or CORS project label). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/reference/metrics.llms.txt ``` **Prompt Example #2: reduce Prometheus cardinality without losing signal** ```text My Prometheus is accumulating too many time series from eRPC histograms. Audit my my eRPC config metrics config and recommend which metrics.customizations entries to add — which labels to drop fleet-wide, which metrics to keep per-user latency on, and how to tune buckets for my sub-100ms upstream fleet. Reference: https://docs.erpc.cloud/reference/metrics.llms.txt ``` **Prompt Example #3: alert on upstream health and cordon events** ```text I need PagerDuty-ready alerts for upstream health in my eRPC setup: cordoned upstreams, circuit-breaker state changes, and BDS hard-timeout spikes. Write PromQL alert expressions referencing the correct metric names (watch out for stale names in the bundled alert.rules file). Work with my existing eRPC config. Reference: https://docs.erpc.cloud/reference/metrics.llms.txt ``` **Prompt Example #4: debug a missing or always-zero metric** ```text One of my eRPC metrics is always 0 and I can't tell if it's a config issue or a dormant metric. Check the metrics reference for known dormant metrics and required opt-in flags (like memory.emitMetrics), and tell me whether my eRPC config is missing any config that would make the metric meaningful. Reference: https://docs.erpc.cloud/reference/metrics.llms.txt ``` --- ### Metrics — full agent reference ### How it works **Initialization order.** Every metric family is *defined* at package init and *registered* later, by a single `telemetry.Configure` call from `erpc.Init`. Definitions go through the `Define*` factories in [`telemetry/manager.go`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go) — `DefineCounter`, `DefineGauge`, `DefineLabeledCounter`, `DefineLabeledHistogram` — which record the family (with its kind) in the manager's index and return a usable, unregistered collector. Call sites hold that pointer for the process lifetime and never check whether it is registered. `Configure` then, in order: compiles `metrics.customizations` and the deprecated label knobs into a single `MetricPolicy` (returning an error and registering nothing if an entry is malformed), resolves `histogramBuckets`, publishes the policy, and walks the definition index. For each family it skips the ones the policy drops, rebuilds the rest under the now-published policy — its label projection and, for a histogram, its per-family buckets — registers them with `prometheus.DefaultRegisterer`, and finally calls `ResetHandleCache` to invalidate handles pointing at the pre-rebuild Vecs. [[`telemetry/manager.go:L196-286`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go#L196-L286)] The define/register split is forced by Prometheus: a registry freezes a family's label-set hash the first time it is registered and keeps it for the registry's lifetime (`dimHashesByName` survives `Unregister`). Anything that changes a label set — a `labels` rule, the deprecated `histogramDropLabels`/`counterDropLabels` — therefore has to be applied *before* the first registration. Dropping a family needs the same window for a different reason: the only way to keep a family off `/metrics` entirely is to never register it. **The policy engine.** [`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go) owns every exposure, label and bucket decision, so there is exactly one precedence implementation. It compiles each customization into a rule carrying a compiled subject pattern (exact, `prefix*`, or `*`), an optional exposure action, its label rules and its buckets; the deprecated knobs desugar onto the same rule type with a kind mask (`counterDropLabels` becomes a counters-only `*` rule). Rules are sorted by specificity — exact beats prefix, longer prefix beats shorter, ties break to the later entry, and a desugared legacy knob sits below an equally specific customization so migrating a field takes effect. Lookups (`Exposed`, `labelIndices`, `BucketsFor`) walk the sorted rules and take the most specific match. **`SetHistogramBuckets`.** A narrower entry point that resolves the bucket string and registers the histogram families only. Two callers use it: config validation, which wants the parse error and nothing else, and test setup, which needs histograms scrapeable while leaving counter label sets still open. Production goes through `Configure`. **Label projection (`LabeledCounter`, `LabeledHistogram`).** Each wrapper stores the full canonical label schema alongside the projected subset the policy keeps for that family. Call sites always pass the full schema in schema order; the wrapper silently projects before forwarding to the underlying `prometheus.CounterVec`/`HistogramVec`. A length mismatch panics immediately. `ActiveLabelValues` returns the projected subset so handle-caches key on the effective (post-projection) labels, preventing duplicate series. Gauges are never projected — collapsing gauge series would report whichever writer wrote last rather than a coarser number. [[`telemetry/labeled_histogram.go:L117-130`](https://github.com/erpc/erpc/blob/main/telemetry/labeled_histogram.go#L117-L130)] **Handle caching.** `CounterHandle`, `GaugeHandle`, and `ObserverHandle` in `telemetry/handles.go` cache children in `sync.Map`s keyed by `{Vec pointer, '\x1f'-joined label values}`. This avoids per-observation map lookup and mutex contention inside the Prometheus library. [[`telemetry/handles.go:L59-105`](https://github.com/erpc/erpc/blob/main/telemetry/handles.go#L59-L105)] **Idle-series eviction.** The health tracker's `rotateMetricsLoop` fires a sweep every 10 rotation ticks (default 30 s/tick = every 5 minutes). The sweep deletes `upsMetrics` and `ntwMetrics` entries not accessed in the last 30 minutes (`DefaultIdleEvictionAfter`), then calls `DeleteLabelValues` on `erpc_upstream_request_duration_seconds` and `erpc_rate_limits_total`. Cordoned entries and wildcard (`"*"`) rollups are never evicted. All other high-cardinality series are NOT covered — cardinality is bounded only by distinct label tuples seen over the process lifetime. [[`health/tracker.go:L557-667`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L557-L667)] **Metrics HTTP server.** `erpc.Init` starts a minimal `http.Server` bound to `:%d` (port only, all interfaces) serving the Prometheus handler at the root path. This means every URL path on the metrics port returns identical Prometheus text output — `GET /`, `GET /metrics`, `GET /health` all work. No TLS, no auth, no gzip. Shutdown is graceful with a 5-second budget. The gatherer is wrapped by `telemetry.Gatherer`, which applies the policy's drop rules to families the manager does not register itself (the stock `go_*`/`process_*`/`promhttp_*` collectors); with no customizations configured it hands the default gatherer straight through. [[`erpc/init.go:L184-215`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L184-L215)] **`ERPC_NOMETRICS=1` env var.** When set before process start, `initflags.go:init()` replaces `prometheus.DefaultRegisterer` and `DefaultGatherer` with a fresh empty registry. All subsequent registrations succeed but produce no-ops. The default `go_*`/`process_*` collectors are also dropped. [[`cmd/erpc/initflags.go:L22-28`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go#L22-L28)] **`errorLabelMode` global.** `common.ErrorSummary` produces the `error` label value on every error-labeled metric. The in-code default before `erpc.Init` runs is `verbose`; `erpc.Init` flips it to `compact` (the config default). In `compact` mode it emits short stable codes: a plain `StandardError` → its `Base().Code` string (e.g. `"ErrEndpointCapacityExceeded"`); for `ErrFailsafeRetryExceeded`, `ErrUpstreamRequest`, or `ErrUpstreamRequestSkipped` it appends the cause code (e.g. `"ErrUpstreamRequest/ErrEndpointTransportFailure"`); for an `ErrJsonRpcExceptionInternal` cause it further appends the numeric code (e.g. `"ErrUpstreamRequest/ErrJsonRpcExceptionInternal/-32000"`). In `verbose` mode it passes the full message chain through `cleanUpMessage` (strips newlines and long hex strings), potentially including block numbers or IP addresses — each unique value creates a new Prometheus series. [[`common/errors.go:L17-114`](https://github.com/erpc/erpc/blob/main/common/errors.go#L17-L114)] **`networkAlias` resolver.** At startup, `erpc.Init` installs a `NetworkAliasResolver` callback mapping raw EVM chain IDs to human-readable aliases so components using numeric chain IDs (e.g. gRPC cache connector) emit matching `network` label values. [[`erpc/init.go:L95-110`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L95-L110)] --- ### Config schema All fields are under `metrics.` in the root YAML config. Source: [`common/config.go:L2899-3016`](https://github.com/erpc/erpc/blob/main/common/config.go#L2899-L3016) (struct), [`common/defaults.go:L908-931`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L908-L931) (defaults), [`common/validation.go:L139-171`](https://github.com/erpc/erpc/blob/main/common/validation.go#L139-L171) (validation). | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `metrics.enabled` | `*bool` | `true` in production; `nil` (disabled) under `go test` | Whether to start the `/metrics` HTTP server. Metrics are still registered and counted when false — they just are not scraped. Source: [`common/defaults.go:L909-911`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L909-L911) | | `metrics.port` | `*int` | `4001` | TCP port for the metrics server. Required when `enabled=true`; `erpc.Init` aborts if nil. Source: [`common/defaults.go:L918-920`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L918-L920) | | `metrics.hostV4` | `*string` | `"0.0.0.0"` | Defined and defaulted but **not used** — the server binds `":%d"` (all interfaces). Setting this to `127.0.0.1` does NOT restrict to loopback. Use firewall rules instead. Source: [`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189) | | `metrics.hostV6` | `*string` | `"[::]"` | Same caveat as `hostV4` — defined but not used in the bind address. Source: [`common/defaults.go:L915-917`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L915-L917) | | `metrics.listenV4` | `*bool` | `nil` | Defined in struct but never read in production code. Dead config field. | | `metrics.listenV6` | `*bool` | `nil` | Defined in struct but never read. Dead config field. | | `metrics.errorLabelMode` | `string` | `"compact"` | Controls the `error` label on all error-labeled metrics. `"compact"` → short stable codes (bounded cardinality, recommended). `"verbose"` → full human messages including block numbers and IP addresses (unbounded cardinality risk). Must be `""`, `"compact"`, or `"verbose"`. Source: [`common/defaults.go:L921-923`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L921-L923) | | `metrics.histogramBuckets` | `string` | `""` → `[0.05, 0.5, 5, 30]` | Comma-separated float64 bucket boundaries for every histogram that does not declare its own buckets. Empty → use defaults. Parsed and sorted by `ParseHistogramBuckets`. Invalid float → warning + fallback to defaults. Source: [`telemetry/metrics.go:L943-948`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L943-L948) | | `metrics.customizations` | `[]object` | `nil` (nothing customized) | The one knob for shaping `/metrics`. Each entry has a `subject`, an optional `action`, an optional `labels` list, and optional `buckets`. Startup-only — every field is resolved before the first registration, so a change needs a restart. Source: [`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go) | | `metrics.customizations[].subject` | `string` | required | Selects metric families: an exact name (`"upstream_request_total"`), a prefix ending in `*` (`"consensus_*"`), or `*` for every family. The `erpc_` prefix is optional. Stock collectors are named in full (`"go_goroutines"`, `"process_cpu_seconds_total"`, `"promhttp_metric_handler_requests_total"`) and obey the same rules, so `subject: "*"` with `action: drop` drops them too. `*` is only legal as the final character, and the same subject may not appear twice. | | `metrics.customizations[].action` | `"keep"` \| `"drop"` | none (exposure untouched) | `drop` removes the matched families from `/metrics`; `keep` spares them from a broader `drop`. Omit it to customize labels or buckets without touching exposure. A dropped eRPC family is never registered, so it costs no series, no collection time and no scrape bytes; a dropped stock collector is filtered out of the scrape response instead, which shrinks the page but not collection. | | `metrics.customizations[].labels` | `[]object` | `nil` (full label set) | A list of `{subject, action}` entries projecting the matched families' label sets, with the same precedence rules applied to label names — `agent_*: drop` then `agent_name: keep` drops the group and spares the one label. Counters and histograms are projected; gauges are not. | | `metrics.customizations[].buckets` | `[]float64` | `nil` | Replaces the bucket boundaries of the matched histograms, overriding both `metrics.histogramBuckets` and what the metric declares in code. Must be strictly increasing. Ignored (with a startup warning) if an exact subject names something that is not a histogram. | | `metrics.histogramDropLabels` | `[]string` | `nil` | **Deprecated** — use a `customizations` entry with `subject: "*"` and a `labels` list. Still honored: desugared into an every-histogram label drop on the same rule engine. Source: [`common/config.go:L2928-2944`](https://github.com/erpc/erpc/blob/main/common/config.go#L2928-L2944) | | `metrics.histogramLabelOverrides` | `map[string][]string` | `nil` | **Deprecated** — use a `customizations` entry with the exact `subject` and a `labels` list keeping what that metric needs. Source: [`common/config.go:L2928-2944`](https://github.com/erpc/erpc/blob/main/common/config.go#L2928-L2944) | | `metrics.counterDropLabels` | `[]string` | `nil` | **Deprecated** — same replacement as `histogramDropLabels`. Desugared into an every-counter label drop. | | `metrics.counterLabelOverrides` | `map[string][]string` | `nil` | **Deprecated** — same replacement as `histogramLabelOverrides`. | **Precedence.** Overlapping subjects resolve by *specificity*, not by list order: an exact family name beats a prefix, a longer prefix beats a shorter one, and two equally specific subjects break to the one written later. So `drop consensus_*` plus `keep consensus_duration_seconds` means the same thing whichever order it appears in, and appending a carve-out never requires reordering the list. The deprecated label knobs are desugared into the same rules but sit *below* an equally specific `customizations` entry, so migrating a field off them takes effect immediately. **Hardcoded server constants (not configurable):** - Bind address: `":%d"` — all interfaces, port only ([`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189)) - Handler: the Prometheus handler registered as root `/`, over a gatherer wrapped by `telemetry.Gatherer` — every path returns full metrics output - Protocol: plain HTTP only (no TLS, no auth, no gzip) - `ReadHeaderTimeout`: 10 seconds - Graceful shutdown budget: 5 seconds **Histograms affected by `metrics.histogramBuckets`:** `erpc_upstream_request_duration_seconds`, `erpc_network_request_duration_seconds`, `erpc_consensus_duration_seconds`, `erpc_cache_set_success_duration_seconds`, `erpc_cache_set_error_duration_seconds`, `erpc_cache_get_success_hit_duration_seconds`, `erpc_cache_get_success_miss_duration_seconds`, `erpc_cache_get_error_duration_seconds`. **Histograms NOT affected by `metrics.histogramBuckets`:** all remaining histograms declare dedicated inline bucket arrays, and the global list deliberately leaves those alone. They are still reachable via a `customizations` entry with `buckets`, which overrides the compiled-in array. --- ### Worked examples **1. Drop `user` globally but keep it on one histogram for user-level latency analysis.** Useful when you need per-user latency breakdowns on `network_request_duration_seconds` but want to limit cardinality everywhere else: ```yaml metrics: customizations: # Fleet-wide: no per-user, no per-agent dimensions. - subject: "*" labels: - subject: user action: drop - subject: agent_name action: drop # …except on this one histogram, which a latency dashboard reads per user. - subject: network_request_duration_seconds labels: - subject: user action: keep ``` **2. Tighter histogram buckets for a low-latency deployment (sub-100ms upstreams).** The default `[0.05, 0.5, 5, 30]` buckets produce poor p95/p99 resolution when upstreams respond in under 50ms. Replacing them gives useful percentile data at real latencies: ```yaml metrics: histogramBuckets: "0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,3" ``` **3. Disabling metrics during integration tests.** `erpc.Init` defaults `metrics.enabled` to `nil` (disabled) under `go test`, but if you call `Init` with a partial config that doesn't go through `SetDefaults`, the server may try to start. Explicit override: ```yaml metrics: enabled: false ``` **4. Keeping only the families a dashboard actually reads.** The strongest cardinality lever available: a dropped family is never registered, so it costs no series, no collection time, and no scrape bytes. An allowlist is written explicitly — drop everything, then keep what you want — so nothing depends on which other keys are present. `subject: "*"` also covers the stock `go_*`/`process_*` collectors, so name them if you want to keep them: ```yaml metrics: customizations: - subject: "*" action: drop - subject: upstream_request_total action: keep - subject: upstream_request_errors_total action: keep - subject: network_request_duration_seconds action: keep - subject: "go_*" action: keep - subject: "process_*" action: keep ``` **5. Keeping a subsystem but dropping its noisiest family.** The exact subject is more specific than the prefix, so the carve-out does not require enumerating everything else — and the order of the two entries does not matter: ```yaml metrics: customizations: - subject: "consensus_*" action: keep - subject: consensus_responses_collected action: drop ``` **6. Per-metric histogram buckets.** `metrics.histogramBuckets` is one global list, which is the wrong resolution when two histograms measure different things. `buckets` on a customization overrides it — and the metric's own compiled-in buckets — for just the families the subject matches: ```yaml metrics: histogramBuckets: "0.05,0.5,5,30" customizations: # Sub-100ms upstreams need resolution the global list does not have. - subject: upstream_request_duration_seconds buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 1] # This one counts blocks, not seconds. - subject: network_evm_get_logs_range_requested buckets: [10, 100, 1000, 10000, 100000] ``` **7. Switching to verbose error labels for a debugging session.** When you need to trace a specific block-number error pattern in Grafana and short codes aren't enough — but remember to revert after, as each unique block number creates a new Prometheus series: ```yaml metrics: errorLabelMode: verbose ``` --- ### Behavioral invariants - No metric family is registered at package init. Every family — counters, gauges, histograms — becomes scrapeable only once `telemetry.Configure` runs from `erpc.Init`. A process that never calls `Init` (or calls it with a config whose `metrics` section is absent) exposes the histogram families only. [[`telemetry/manager.go`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go)] - Exposure is a startup decision. A family dropped by a customization is never registered, so it cannot be turned back on without a restart — and a family that *was* registered cannot be removed by a later `Configure`, because Prometheus keeps the frozen label-set hash for the registry's lifetime. - Metrics still count when `metrics.enabled` is false: `enabled` only controls whether the HTTP server starts. A `drop` customization is what actually prevents a family from existing. - A customization with no `action` never affects exposure. It customizes labels or buckets only, and it does not turn on the scrape-path filter that hides stock collectors. - A repeat `Configure` on the same registry leaves already-registered families untouched — their label sets are frozen, and accumulated values are preserved. Changing `customizations` or `histogramBuckets` requires a restart. - `ERPC_NOMETRICS=1` swaps `prometheus.DefaultRegisterer`/`DefaultGatherer` for a fresh empty registry before `Configure` runs — all subsequent registrations succeed but produce no-ops; the stock `go_*`/`process_*` collectors are also dropped. [[`cmd/erpc/initflags.go:L22-28`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go#L22-L28)] - Idle sweep runs every 5 minutes (default); series not accessed in 30 minutes are evicted from `upstream_request_duration_seconds` and `rate_limits_total` via `DeleteLabelValues`. [[`health/tracker.go:L557-667`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L557-L667)] - The `error` label value is produced by `common.ErrorSummary`. Compact mode yields a bounded set of code-path identifiers; verbose mode can produce one series per unique block number or IP. [[`common/errors.go:L46-66`](https://github.com/erpc/erpc/blob/main/common/errors.go#L46-L66)] - `erpc_rate_limiter_budget_decision_total` is registered but has zero production call sites — always zero. [[`telemetry/metrics.go:L515-519`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L515-L519)] - `erpc_network_hedge_delay_seconds` is registered but never observed in production — always empty. [[`telemetry/metrics.go:L813`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L813)] --- ### Best practices - Use `errorLabelMode: compact` (the default) in production. Verbose mode can create one Prometheus series per unique block number or IP address in error messages — this is an unbounded cardinality hazard. - Drop `user` and `agent_name` with a `subject: "*"` customization when serving untrusted callers or managing many API keys. These labels are the leading cardinality source across the projected families. Re-add them with an exact subject on the one or two metrics a dashboard or billing pipeline actually reads. - Do not rely on `hostV4`/`hostV6` to restrict scrape access — the server binds all interfaces regardless of those fields. Use firewall rules or network policy to limit who can reach port 4001. - Alert on `erpc_network_failed_request_total{severity="critical"}` and page on `severity="warning"`. Severity is already classified by `common.ClassifySeverity` — no need to build your own error-code regexes. - Use `erpc_rate_limits_total` for rate-limit alerting. The bundled alert rule referencing `erpc_upstream_request_self_rate_limited_total` uses a stale metric name that no longer exists. - Monitor `erpc_upstream_cordoned` as an early-warning signal for upstream health. A non-zero value means eRPC has autonomously excluded that upstream; combine with `erpc_upstream_cordon_event_total` to track how often it happens. - For `erpc_network_evm_block_range_requested_total`, be aware the `bucket` label is unbounded. Consider a Prometheus `metric_relabel_configs` drop rule for the `bucket` label if long-running chains accumulate too many series. --- ### Edge cases & gotchas 1. **`hostV4`/`hostV6` are defined but unused.** The bind address is always `":%d"` (all interfaces). Firewall rules are the only way to restrict access to the metrics port. ([`erpc/init.go:L189`](https://github.com/erpc/erpc/blob/main/erpc/init.go#L189)) 2. **`metrics.enabled` is `nil` (disabled) under `go test`.** Integration tests that call `erpc.Init` will not spin up a metrics server unless `Enabled: true` is set explicitly. ([`common/defaults.go:L909-911`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L909-L911)) 3. **Changing `errorLabelMode` does not retroactively relabel existing series.** Counter Vec children are created lazily on first `WithLabelValues`. Any series created before `erpc.Init` sets the mode carry verbose labels; subsequent series carry compact labels. Both sets coexist in Prometheus until the verbose series naturally expire. 4. **Label-set, bucket and exposure changes need a restart.** Prometheus keeps a family's label-set hash for the registry's lifetime, so a second `Configure` leaves already-registered families exactly as they are — a changed `customizations` list or `histogramBuckets` is silently not applied to them. ([`telemetry/manager.go`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go)) 5. **A `subject` that matches nothing is only a warning.** A typo'd family name is not a validation error — `Init` logs the unmatched subjects, quoting the text you wrote, and starts anyway. Check the startup log for `subjects match no known metric family` after editing the list. Subjects naming a stock collector are excluded from the check, since those are registered outside the manager and are never in `KnownFamilies`. 6. **A rule aimed at a family that cannot honor it is also only a warning.** `buckets` on a counter, or `labels` on a plain counter or gauge whose label set is fixed in code, is silently ignored; `Init` warns only when an *exact* subject names such a family, so a sweeping `subject: "*"` does not produce one warning per family. Look for `rules do not apply to the family they name`. 7. **Third-party collectors outside `go_*`/`process_*`/`promhttp_*` cannot be addressed.** Any other name is normalized by prepending `erpc_`, so a collector registered by a dependency under some other prefix is unreachable from `customizations` — `subject: "*", action: drop` still removes it (via the scrape filter), but no `keep` can name it back. ([`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go)) 8. **Idle sweep evicts only `upstream_request_duration_seconds` and `rate_limits_total`.** All other high-cardinality histograms and counters (`network_request_duration_seconds`, `upstream_request_total`, etc.) are never `DeleteLabelValues`'d — they grow monotonically. For method-flood scenarios drop `user` and `agent_name` with a `subject: "*"` customization. 9. **`erpc_cors_requests_total` `project` label receives `r.URL.Path`, not the project ID.** Series will have values like `/myproject/evm/1`. Dashboard queries on CORS metrics must match the path-style value, not a bare project ID. ([`erpc/http_server.go:L1020`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1020)) 10. **`erpc_ristretto_cache_current_cost` requires `memory.emitMetrics: true`.** Without this flag the gauge is registered and appears in `/metrics` but always returns 0. It is the only metric in the system requiring an explicit opt-in to be meaningful. ([`data/memory.go:L71`](https://github.com/erpc/erpc/blob/main/data/memory.go#L71)) 11. **`erpc_upstream_cordoned` `category` label is the cordon scope (method string or `"*"`), not a request-category label.** Do not join this `category` with `category` from request-accounting metrics. ([`health/tracker.go:L458-465`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L458-L465)) 12. **`erpc_upstream_cordoned` `vendor` label is `"n/a"` when no vendor is configured.** Dashboard JOINs between cordon metrics and upstream request metrics must handle the `"n/a"` value for unvendored upstreams. ([`upstream/upstream.go:L275-286`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L275-L286)) 13. **`erpc_auth_failed_total` increments when `ErrAuthUnauthorized` is sent to the client.** Closed `reason` per strategy via `NewErrAuthUnauthorized`; intermediate multi-strategy rejects are not counted. `agent_name` is always `"unknown"`. ([`auth/auth_metrics.go`](https://github.com/erpc/erpc/blob/main/auth/auth_metrics.go)) 14. **`erpc_upstream_attempt_outcome_total` `is_hedge`/`is_retry` are literal `"true"`/`"false"` strings.** Use `{is_hedge="true"}` in PromQL, not `{is_hedge="1"}`. ([`upstream/upstream.go:L80-85`](https://github.com/erpc/erpc/blob/main/upstream/upstream.go#L80-L85)) 15. **`erpc_network_evm_block_range_requested_total` `bucket` label is unbounded.** When tip is known, `ComputeBlockHeatmapBucket` produces human-readable relative labels (`"TIP"`, `"L100k"`, `"100k-200k"`, etc.). This counter is not covered by the idle sweep — cardinality grows permanently. ([`erpc/block_heatmap.go:L87-175`](https://github.com/erpc/erpc/blob/main/erpc/block_heatmap.go#L87-L175)) 16. **`erpc_selection_*` metrics carry a `method` label.** Untrusted callers injecting hundreds of distinct method names create unbounded selection-gauge series. Consider a Prometheus relabeling drop rule for the `method` label in untrusted deployments. 17. **`erpc_upstream_block_head_large_rollback` is silent for rollbacks ≤ 1024 blocks, and sticky above them.** `DefaultToleratedBlockHeadRollback = 1024` is the threshold. The gauge is `Set` to the rollback *size* and is never reset, so `> 0` means "this process saw a rollback at some point", not "a rollback is happening now", and `rate()`/`increase()` are meaningless on it. Alert on `changes(...[window])`, split by the `finality` label. ([`architecture/evm/evm_state_poller.go:L27`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L27)) 18. **Cordoned upstreams are never swept.** A cordoned tracker entry persists in memory — and the `erpc_upstream_cordoned{...} = 1` gauge persists in `/metrics` — until the upstream is uncordoned and subsequently goes idle for `idleEvictionAfter`. ([`health/tracker.go:L603-608`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L603-L608)) 19. **`erpc_network_dynamic_block_time_milliseconds` is bounded 10ms–120s.** Fast chains (block time below 10ms) or stuck chains (no blocks for over 2 minutes) report the floor or ceiling value, not the true EMA. ([`health/tracker.go:L1456`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L1456)) 20. **Two bundled alert rules reference stale metric names.** `erpc_upstream_request_self_rate_limited_total` and `erpc_network_request_self_rate_limited_total` no longer exist — use `erpc_rate_limits_total` as the replacement. ([`monitoring/prometheus/alert.rules:L1`](https://github.com/erpc/erpc/blob/main/monitoring/prometheus/alert.rules#L1)) 21. **The bundled Prometheus scrape target includes `REPLACE_SERVICE_ENDPOINT_HERE` and `REPLACE_SERVICE_PORT_HERE` placeholders.** These are Railway deployment stubs that cause a parse error in strict Prometheus configs. Remove or replace both before using `monitoring/prometheus/prometheus.yml` in production. 22. **`ParseHistogramBuckets` silently sorts the input.** If `metrics.histogramBuckets` is provided out of order (e.g. `"5,0.5,0.05,30"`) the values are sorted automatically and no warning is emitted. The resulting bucket set is valid, but operators relying on a specific insertion order will not get what they typed. [[`telemetry/metrics.go:L1133-1151`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L1133-L1151)] 23. **`erpc_upstream_response_size_bytes` is intentionally tight-cardinality.** Its label set is `project, network, category, finality` — no `user` or `upstream` — because per-user response-size breakdown is not operationally actionable. If you need per-user latency analysis, retain `user` on `erpc_upstream_request_duration_seconds` with an exact-subject `labels: [{subject: user, action: keep}]` customization instead of not dropping it globally. [[`telemetry/metrics.go:L1125-1130`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L1125-L1130)] 24. **`erpc_upstream_request_duration_seconds` has two high-cardinality labels: `user` and `composite`.** The `composite` label carries the composite-request type (e.g. `"logs-split-on-error"`, `"query-logs-shim"`) and, combined with `user`, can produce many series in high-traffic deployments. Both are candidates for a `labels: [{subject: ..., action: drop}]` customization; the idle sweep (`DefaultIdleEvictionAfter = 30 min`) provides a safety valve. [[`health/tracker.go:L333-358`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L333-L358)] 25. **`ErrEndpointServerSideException` HTTP status code is not exposed as a Prometheus label.** When an upstream returns an HTTP 5xx that does not match a known pattern, eRPC wraps it in `ErrEndpointServerSideException` and echoes the upstream's status code back to the caller via `ErrorStatusCode()`. The raw numeric code surfaces in `erpc_upstream_request_errors_total{error="ErrEndpointServerSideException"}` in compact mode (no code number) or in the full message in verbose mode, but no label carries it. For debugging, use OTel traces: `SetTraceSpanError` attaches `attribute.String("error.code", stdErr.CodeChain())` and the serialised `StandardError` JSON to the span — though `originalStatusCode` is a private field and is not in the JSON output. The only way to retrieve the exact upstream HTTP status is from structured logs (logged at DEBUG level before wrapping). [[`common/errors.go:L1951-1979`](https://github.com/erpc/erpc/blob/main/common/errors.go#L1951-L1979)] --- ### Full metrics catalog All metric names carry the `erpc_` prefix. Full definitions: [`telemetry/metrics.go:L11-1131`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go#L11-L1131). #### Area 1: Upstream request accounting | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_request_total` | counter | project, vendor, network, upstream, category, attempt, composite, finality, user, agent_name | Each actual attempt sent to an upstream. `composite` ∈ `"none"`, `"logs-split-on-error"`, `"trace-filter-split-on-error"`, `"trace-filter-split-proactive"`, `"query-blocks-shim"`, `"query-transactions-shim"`, `"query-logs-shim"`, `"query-traces-shim"`, `"query-transfers-shim"`. | | `erpc_upstream_request_errors_total` | counter | project, vendor, network, upstream, category, error, severity, composite, finality, user, agent_name | Upstream attempt returned an error. `severity` ∈ `"critical"`, `"warning"`, `"info"` via `common.ClassifySeverity`. Also incremented with severity=info for block-availability-gated skips. | | `erpc_upstream_request_skipped_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream pre-forward checks decided to skip. | | `erpc_upstream_request_missing_data_error_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned missing-data / not-synced error. | | `erpc_upstream_request_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned an emptyish response. | | `erpc_upstream_wrong_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned empty while consensus determined others had data. | | `erpc_upstream_selection_total` | counter | project, network, upstream, category, reason, finality | Upstream picked for an attempt. `reason` ∈ `"primary"`, `"retry"`, `"hedge"`, `"consensus_slot"`, `"sweep"`. `"sweep"` = the upstream was picked as part of `runUpstreamSweep` — the try-all-upstreams iteration used in the non-consensus path when the primary fails and retries loop through remaining upstreams in sequence. | | `erpc_upstream_credit_units_total` | counter | project, network, upstream, vendor, category, finality | Vendor credit units accrued by upstream attempts (Alchemy CUs, QuickNode credits, dRPC CUs). Summed across retries/hedges/consensus slots; cache hits and never-dialed attempts cost 0. Values are each vendor's own units — not money, not comparable across vendors. **No `user` label** (cardinality); per-user cost is in the `X-ERPC-Credits` response header and traces. Vendorless upstreams are excluded. | | `erpc_upstream_attempt_outcome_total` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | Terminal attempt outcome. `outcome` ∈ `"success"`, `"empty"`, `"transport_error"`, `"server_error"`, `"client_error"`, `"rate_limited"`, `"missing_data"`, `"exec_revert"`, `"block_unavailable"`, `"breaker_open"`, `"cancelled"`, `"timeout"`, `"skipped"`. `is_hedge`/`is_retry` are literal `"true"`/`"false"`. | | `erpc_upstream_request_duration_seconds` | LabeledHistogram | project, vendor, network, upstream, category, composite, finality, user | Duration of each upstream attempt. Idle series swept every ~30 min. `user` is a cardinality candidate for a label `drop` customization. | | `erpc_upstream_response_size_bytes` | LabeledHistogram | project, network, category, finality | Decoded post-gzip result-body byte count. Tight label set by design (no `user`). Buckets: 4096, 65536, 1048576, 16777216, 104857600. | #### Area 2: Network request accounting | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_request_received_total` | counter | project, network, category, finality, user, agent_name | Request received for a network. | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, error, severity, finality, user, agent_name | Request failed at network/project level. `severity` ∈ `"critical"`, `"warning"`, `"info"`. Page on critical, ticket on warning, ignore info. | | `erpc_network_successful_request_total` | counter | project, network, vendor, upstream, category, attempt, finality, emptyish, user, agent_name | Request succeeded. `emptyish` ∈ `"true"`/`"false"` — true means the response was empty-ish (null, empty array). | | `erpc_network_multiplexed_request_total` | counter | project, network, category, finality, user, agent_name | Request de-duplicated into an identical in-flight request. | | `erpc_network_fallback_escape_total` | counter | project, network, category | The per-request fallback escape (`failover.onDefaultsExhausted`) retried a request on `tier:fallback` upstreams. Expected zero in steady state. | | `erpc_upstream_websocket_connected` | gauge | project, vendor, network, upstream | `1` while the upstream's WebSocket connection is established, `0` while it reconnects. | | `erpc_upstream_websocket_heads_stall_reconnects_total` | counter | project, network, upstream | Reconnects forced because the upstream's newHeads subscription went silent while its polled head kept advancing. Any increase means a node dropped a live subscription without closing it. | | `erpc_websocket_connections_active` | gauge | project | Open client WebSocket connections. | | `erpc_taps` | gauge | project, network, transport, kind | Open taps: client consumers (ws `newHeads` / `logs` subscriptions, gRPC `StreamBlocks` streams, the integrity follow tap) reading the chain feed from their own cursor. `transport` ∈ `"ws"`, `"grpc"`, `"integrity"`. | | `erpc_tap_end_total` | counter | project, network, transport, kind, reason, detail | Taps ended by the server. `reason="out_of_range"`: the cursor left the feed; `detail` ∈ `"below_window"`, `"fork_left_window"`, `"cursor_unknown"`, `"receipts_timeout"`, `"reorg_depth"`; ws closes such a connection with `1013`, gRPC ends the stream with `OUT_OF_RANGE`. `reason="lagging"`, `detail="lag"`: the client read slower than the transport's wait bound. | | `erpc_tap_delivery_seconds` | histogram | transport, kind | Seconds from a block's ready stamp (confirmed head; logs head for a logs tap) to the end of a tap's write of it. | | `erpc_websocket_notifications_sent_total` | counter | project, network, kind | Subscription notifications written to clients. | | `erpc_websocket_notification_bytes_total` | counter | project, network, kind | JSON bytes of those notifications, without cost frame headers. | | `erpc_upstream_subscriptions_active` | gauge | project, network, upstream, kind | `eth_subscribe` subscriptions live on upstream WebSocket connections: `newHeads` on each subscription source, plus `newPendingTransactions` while a client subscribes to it. | | `erpc_upstream_subscription_events_total` | counter | project, network, upstream, kind | Subscription notifications received from upstreams, before dedup. | | `erpc_upstream_subscription_event_bytes_total` | counter | project, network, upstream, kind | Bytes of those notifications. | | `erpc_subscription_dedup_dropped_total` | counter | project, network, kind | `newPendingTransactions` events dropped as duplicates of one already delivered from another upstream. | | `erpc_subscription_dedup_entries` | gauge | project, network | Keys held by the network's `newPendingTransactions` dedup window. | | `erpc_network_subscription_last_head_timestamp_seconds` | gauge | project, network | Unix time the network-wide chain tracker's confirmed head last changed. Alert on `time() - this` well past the block time: heads have stopped. | | `erpc_websocket_rejected_total` | counter | project, reason | Client WebSocket connection or subscription refused by an instance-wide cap or during shutdown. `reason` ∈ `"conn_global"` (`server.webSocket.maxConnections`), `"conn_per_ip"` (`maxConnectionsPerIP`), `"sub_global"` (`maxSubscriptions`), `"shutting_down"` (upgrade during shutdown). | | `erpc_network_static_response_served_total` | counter | project, network, category | Served from a configured static response; no upstream touched. | | `erpc_network_timeout_fired_total` | counter | project, network, category, finality, scope | Timeout policy killed a request. `scope` ∈ `"network"`, `"upstream"`. Suppressed when retry-exhausted error wins. | | `erpc_network_retry_attempt_total` | counter | project, network, category, reason, finality | Network-scope retry. `reason` ∈ `"empty_result"`, `"pending_tx"`, `"retryable_error"`, `"block_unavailable"`, `"missing_data"`. | | `erpc_network_request_duration_seconds` | LabeledHistogram | project, network, vendor, upstream, category, finality, user | End-to-end network request duration. `vendor`/`upstream` = `""` on failure. | | `erpc_network_data_unavailable_wait_seconds` | LabeledHistogram | project, network, category, reason, finality | Wall-clock catch-up delay before data-not-yet-available retry. Buckets: 0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64 s. | | `erpc_network_timeout_duration_seconds` | LabeledHistogram | project, network, category, finality | Computed dynamic timeout per request. Buckets: 0.05, 0.1, 0.3, 0.5, 1, 3, 5, 10, 30 s. | #### Area 2b: Chain tracker One chain tracker per network follows the canonical chain from source headers and polls; see [WebSocket subscriptions](/operation/websocket.llms.txt) for the model. | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_chain_tracker_source_heads_total` | counter | project, network, upstream, outcome | Source headers handled by network intake. `outcome` ∈ `"voted"`, `"duplicate"`, `"malformed"`, `"gated_identity"`, `"gated_integrity"`, `"gated_voter"`. | | `erpc_chain_tracker_head` | gauge | project, network, group | Head (highest pinned block) of a chain tracker. | | `erpc_chain_tracker_lag` | gauge | project, network, group | Blocks between the network's served tip and a chain tracker's head. | | `erpc_chain_tracker_confirm_lag_blocks` | gauge | project, network | Pins head − confirmed head of the network-wide tracker. | | `erpc_chain_tracker_reorg_depth` | histogram | project, network, group | Pinned blocks reverted by each reorg a tracker followed. | | `erpc_chain_tracker_reanchor_total` | counter | project, network | Times the pins moved to another tree of held headers. | | `erpc_chain_tracker_reset_total` | counter | project, network | Tracker resets to empty after 3 panics of one message kind with no clean one between them. | | `erpc_chain_tracker_header_proof_total` | counter | project, network, proof, reason | Headers the network-wide chain tracker held, by what their hash proves under the registered header formats. `proof` ∈ `"verified"` (a registered format reproduces the hash: served at 1 holder), `"mismatch"` (after a header of the network verified, the format it verified with encodes this one to another hash: needs the quorum's holders), `"unverified"` (any other: served at 1 holder); `reason` ∈ `"unencodable"` (the network's format, or before one verified every format, cannot encode the header: it lacks keys the format needs or carries keys it does not know), `"hash_differs"`. Only `"unverified"` on a network: its header format is not registered. `"unencodable"` beside `"verified"`: a source serves headers with keys dropped or added. | | `erpc_chain_tracker_settle_total` | counter | project, network, reason, outcome | Settle rounds: `latest` asked again to decide a tie or a fork. `reason` ∈ `"tie"`, `"fork"` (the refresh of a vote off the pins), `"recheck"` (a client's re-check of a pin); `outcome` ∈ `"decided"`, `"undecided"`. | | `erpc_chain_tracker_fetch_total` | counter | project, network, kind, class, outcome | Tracker fetches. `kind` ∈ `"header"`, `"receipts"`, `"logs"`, `"logs_hash"` (the logs gate's one header lookup of a `blockHash` the tracker does not hold), `"bloom_trust"` (a block's receipts fetched to earn or keep the bloom trust the logs gate's verdicts need: at most 8 to earn it, then at most one a minute while the gate relies on it); `outcome` ∈ `"ok"`, `"error"`, `"capacity"` (every upstream tried refused for capacity). | | `erpc_chain_tracker_fetch_slots` | gauge | project, network, class | Current share of the fetch scheduler's slots per class. | | `erpc_chain_tracker_invariant_violations_total` | counter | project, network, invariant | `invariant` ∈ `"sent_above_head"`, `"tap_gap"`, `"removed_unsent"`, `"pins_unlinked"`, `"final_hash_changed"`, `"latest_regressed"`. Must stay 0, except `final_hash_changed`: a followed majority branch reverted a finalized block, also logged as an error. `latest_regressed` counts a lane's view `Head` falling while its pin still stands: only a pins move may lower it, so a rewind of every upstream counts none. | | `erpc_head_refusal_total` | counter | project, network, rule | Requests naming a block, by the refusal rule's outcome: `"served"`, `"retried_found"`, `"retried_missing"` (a block above `Latest`, at most the highest upstream head, still empty or missing after the retry: a vendor head no node serves yet; expected at a low rate where clients read ahead), `"served_missing"` (`eth_getBlockByNumber` of a block with `Latest` − `reorgWindow` < N ≤ `Latest` answered `null` or a missing-data error after the retry: a block this instance promised was not found; must stay 0. Other methods are not counted, since their `null` or missing-data answer can be legit: a transaction or uncle index past the block's count, a state read on a pruned node. Older blocks are not counted either: that is block availability), `"future"`, `"future_after_wait"` (a block at most W of chain above every upstream's head waits up to W for one to reach it; still above after W). | | `erpc_head_ask_total` | counter | project, network, reason, outcome | Head Asks. `reason` ∈ `"clock"` (the block clock), `"poll"` (full polls' latest part), `"refusal"`, `"settle"`; `outcome` ∈ `"fetched"`, `"shared_fresh"`, `"inflight"`, `"backoff"`, `"pushed"` (a head the upstream pushed met its poll). | | `erpc_head_clock_total` | counter | project, network, lane, kind, outcome | Block clock fetches, one per answer. `kind` ∈ `"rung"` (a ladder rung before the last), `"probe"` (the last rung, or the block's one fetch), `"retry"` (a tail rung), `"vote"` (a voter's turn sent at the block's sight; where the cache's poll brought the block, once the voter most likely holds it), `"catch_up"`, `"guarantee"`, `"holder"`, `"edge"`, `"cold"`, `"held"` (a block a by-hash answer showed above `latest`, fetched by number from the upstream that answered), `"ahead"` (the one fetch every read waiting for a block above `latest` shares: that block by number); `outcome` ∈ `"new"`, `"early"` (for `"ahead"`: answered null), `"behind"`, `"same"`, `"failed"`, `"dropped"`, `"joined"` (another fetch met the Ask: no fetch), `"skipped_push"` (a last rung a push or another local fetch made needless: no fetch). Every outcome but `"joined"` and `"skipped_push"` is a fetch; less `"held"` and `"ahead"`, block fetches that are no head Ask, their sum equals `erpc_head_ask_total{reason="clock",outcome="fetched"}`. | | `erpc_served_tip_voters` | gauge | project, network, lane, rank | Upstreams on a lane's `latest` ballot per rank (`"live"`, `"live_benched"`, `"capped"`, `"capped_benched"`); only the best rank votes. | | `erpc_served_tip_quorum` | gauge | project, network, lane | Effective quorum of the lane's `latest` pick: the configured quorum capped at its voters. | | `erpc_upstream_report_age_seconds` | gauge | project, network, upstream, evidence | How long the lag reference has stood above the upstream's newest report. `evidence` ∈ `"number"`, `"hash"`. | | `erpc_upstream_tag_state_stale` | gauge | project, network, upstream | `1` while the upstream's `latest` state is stale against the network-wide `Latest`. The tag-state gate judges each tag request against its own `Latest`. | | `erpc_upstream_tag_state_all_stale_total` | counter | project, network, outcome | Tag requests whose every routed upstream had stale `latest` state. `outcome` ∈ `"routed"`, `"refused"`. | | `erpc_source_resubscribe_total` | counter | project, network, upstream, topic | Pending-transaction topics a push source subscribed again after 60s without a message while heads carried transactions. | | `erpc_shared_counter_remote_rejected_total` | counter | reason | Remote shared-counter states this instance rejected. `reason` ∈ `"non_positive"`, `"small_rollback"`, `"held_rollback"`, `"stale_timestamp"`, `"malformed"`. | | `erpc_integrity_check_suspended_total` | counter | project, network, check | Integrity checks suspended for a network: no answer passed them at heights in a row, from vendors that meet the evidence quorum. | #### Area 3: Block number and tip tracking > **On SVM networks these carry slots, not block heights.** The names were coined for EVM and are reused verbatim by the SVM state poller, so `erpc_upstream_latest_block_number` is the upstream's *processed slot*, `erpc_upstream_finalized_block_number` its *finalized (rooted) slot*, and the `*_lag` gauges count slots. That distinction is not cosmetic: a skipped Solana slot advances the slot counter but not the block height, so slot and height are different counters. The rollback threshold on SVM is `DefaultToleratedSlotRollback` = 1024 slots. `erpc_upstream_stale_latest_block_total` fires when a `getSlot` answer is corrected to the highest known slot for its commitment. The poller emits no `*_polled_total`, no served-tip gauges, and no metric for shred-insert (ingestion) lag. `erpc_network_dynamic_block_time_milliseconds` **does** populate for SVM once the tracker has ≥3 samples of wall-clock Δ / accepted slot gap (no on-chain slot timestamp) — see [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) and [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt). | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_latest_block_number` | gauge | project, vendor, network, upstream | Upstream's latest block advanced. | | `erpc_upstream_finalized_block_number` | gauge | project, vendor, network, upstream | Upstream's finalized block advanced. | | `erpc_upstream_block_head_lag` | gauge | project, vendor, network, upstream | Blocks behind the corroborated network head (second-highest non-benched upstream). | | `erpc_upstream_finalization_lag` | gauge | project, vendor, network, upstream | Finalized blocks behind the corroborated network finalized head. | | `erpc_upstream_block_head_large_rollback` | gauge | project, vendor, network, upstream, finality | Block head rolled back by more than `DefaultToleratedBlockHeadRollback` = 1024 blocks. Gauge value = absolute delta of the rollback. `finality` is the head axis that rolled back (`latest` or `finalized`), **not** a `DataFinalityState`. Sticky: never reset, so a non-zero value means "this process saw a rollback at some point", not "a rollback is happening now". | | `erpc_upstream_latest_block_polled_total` | counter | project, vendor, network, upstream | State poller proactively polled latest block. | | `erpc_upstream_finalized_block_polled_total` | counter | project, vendor, network, upstream | State poller proactively polled finalized block. | | `erpc_upstream_stale_latest_block_total` | counter | project, vendor, network, upstream, category | Upstream returned a stale latest block vs. others. | | `erpc_upstream_stale_upper_bound_total` | counter | project, vendor, network, upstream, category, confidence | Request skipped: upstream latest block < requested upper bound. `confidence` ∈ `"blockHead"`, `"finalizedBlock"`. | | `erpc_upstream_stale_lower_bound_total` | counter | project, vendor, network, upstream, category, confidence | Request skipped: requested lower bound below upstream's available range. Same `confidence` values. | | `erpc_network_latest_block_timestamp_distance_seconds` | gauge | project, network, origin | `now − latest block timestamp`. `origin` ∈ `"evm_state_poller"`, `"network_response"`. | | `erpc_network_dynamic_block_time_milliseconds` | gauge | project, network | EMA block/slot-time estimate (α=0.1, min 3 samples). Returns 0 until 3 samples. Bounded 10ms–120s. On SVM: wall-clock Δ / accepted slot gap (no on-chain slot timestamp). | | `erpc_network_served_tip_block_number` | gauge | project, network, lane, axis | The tip actually served per `axis` (`latest`/`finalized`): the [served-tip pick](/reference/evm/block-tracking.llms.txt#served-tip) after the regression guard, the guarantee floors and the [finalized floor](/reference/evm/block-tracking.llms.txt#finalized-floor) (`finalized` only). Set on every evaluation with a known tip, with or without a `servedTip` block. `lane="all"` = network-wide, evaluated at least every second; a named lane = a [use-upstream group](/reference/lanes.llms.txt), evaluated only by its requests; a request without a lane writes nothing. Keeps its last value while no upstream has a head. | | `erpc_network_served_tip_lag_blocks` | gauge | project, network, lane, axis | `Freshest − served`, clamped at 0. `Freshest` is the second-highest head on the ballot (the only one when one votes), so a lone far-ahead head never inflates it. `latest`: served is the view's Head, so it counts the blocks the view trails `Freshest`; 0 while the lane has no read demand (its block clock is stopped, and the next read fetches a fresh head). `finalized`: reads 0 at quorum ≤ 2 unless a guarantee floor sits below the pick, and 0 while the guard lifts the tip. Keeps its last value while no upstream has a head. | | `erpc_network_served_tip_advance_age_seconds` | gauge | project, network, lane, axis | Seconds since this process saw the served value change, written at each evaluation; absent until the first change. Keeps rising while no upstream has a head: the stuck-tip signal. | | `erpc_network_served_tip_regression_total` | counter | project, network, lane, axis, outcome | [Regression-guard](/reference/evm/block-tracking.llms.txt#regression-guard) transitions on the `finalized` axis, not evaluations. `outcome` ∈ `"held"` (serving the last corroborated pick), `"failed_open"` (the hold outlasted 1 minute). Any increase is alert-worthy. | | `erpc_upstream_head_benched_total` | counter | project, vendor, network, upstream | Times this process [benched](/reference/evm/block-tracking.llms.txt#benching) the upstream's head out of the served-tip ballots and the lag reference: it stayed behind peers that kept advancing for its stall window. | #### Area 4: Cache connector freshness | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cache_connector_earliest_block_number` | gauge | connector, network | gRPC cache connector availability poll — earliest available block. | | `erpc_cache_connector_latest_block_number` | gauge | connector, network | Same poll — latest block; on a network whose realtime `eth_getBlockByNumber` policy reads this connector, refreshed every eighth of a block or of the realtime TTL as well while the network has a reader ([cache head](/reference/evm/block-tracking.llms.txt#cache-head)). | | `erpc_cache_connector_finalized_block_number` | gauge | connector, network | Same poll — finalized block. | | `erpc_cache_connector_earliest_block_timestamp_seconds` | gauge | connector, network | Same poll — earliest block unix timestamp. | | `erpc_cache_connector_latest_block_timestamp_seconds` | gauge | connector, network | Same writers as the latest block number — latest block unix timestamp. | | `erpc_cache_connector_finalized_block_timestamp_seconds` | gauge | connector, network | Same poll — finalized block unix timestamp. | #### Area 5: Cache operations (JSON-RPC cache) | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cache_get_success_hit_total` | counter | project, network, category, connector, policy, ttl | Cache get hit. | | `erpc_cache_get_success_miss_total` | counter | project, network, category, connector, policy, ttl | Cache get miss. | | `erpc_cache_get_error_total` | counter | project, network, category, connector, policy, ttl, error | Cache get errored. | | `erpc_cache_get_skipped_total` | counter | project, network, category | Cache get skipped — no matching policy. | | `erpc_cache_get_age_guard_reject_total` | counter | project, network, method, connector, policy, ttl | Cached item rejected: block-timestamp age exceeded policy TTL. | | `erpc_cache_set_success_total` | counter | project, network, category, connector, policy, ttl | Cache set succeeded. | | `erpc_cache_set_error_total` | counter | project, network, category, connector, policy, ttl, error | Cache set errored. | | `erpc_cache_set_skipped_total` | counter | project, network, category, connector, policy, ttl | Cache set skipped by policy. | | `erpc_cache_set_original_bytes_total` | counter | project, network, category, connector, policy, ttl | Uncompressed bytes written on cache set. | | `erpc_cache_set_compressed_bytes_total` | counter | project, network, category, connector, policy, ttl | Compressed bytes written on cache set. | | `erpc_cache_get_success_hit_duration_seconds` | LabeledHistogram | project, network, category, connector, policy, ttl | Cache get hit duration. | | `erpc_cache_get_success_miss_duration_seconds` | LabeledHistogram | project, network, category, connector, policy, ttl | Cache get miss duration. | | `erpc_cache_get_error_duration_seconds` | LabeledHistogram | project, network, category, connector, policy, ttl, error | Cache get error duration. | | `erpc_cache_set_success_duration_seconds` | LabeledHistogram | project, network, category, connector, policy, ttl | Cache set success duration. | | `erpc_cache_set_error_duration_seconds` | LabeledHistogram | project, network, category, connector, policy, ttl, error | Cache set error duration. | | `erpc_ristretto_cache_current_cost` | gauge | connector | Ristretto (memory connector) current total cost. **Requires `memory.emitMetrics: true`** — always 0 otherwise. | | `erpc_ristretto_cache_sets_failed_total` | counter | connector | Ristretto set dropped / rejected. | #### Area 6: Rate limiting | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_rate_limits_total` | counter | project, network, vendor, upstream, category, finality, user, agent_name, budget, scope, auth, origin | Unified rate-limit event. `scope="remote", origin="upstream", budget=""` = upstream 429 passthrough. For local budget denials, `scope` = `ScopeString()` of the rule: a comma-joined set of enabled scope flags (e.g. `"user"`, `"network"`, `"ip"`, or combinations like `"user,network"`); `origin` = empty string. Idle series deleted by health-tracker sweep. | | `erpc_rate_limiter_budget_max_count` | gauge | budget, method, scope | Budget's allowed req/s, set on rule creation or auto-tuner update. `scope` = `ScopeString()` comma-joined flags (e.g. `"user,network"`). | | `erpc_rate_limiter_budget_decision_total` | counter | project, network, category, finality, user, agent_name, budget, method, scope, decision | **DEPRECATED / DORMANT** — registered but zero production call sites. Always 0. | | `erpc_rate_limiter_failopen_total` | counter | project, network, user, agent_name, budget, category, reason | Rate limiter failed open. `reason` ∈ `"admission_full"`, `"limit_timeout"`. | | `erpc_rate_limiter_remote_inflight` | gauge | budget | Concurrent in-flight remote (e.g. Redis) DoLimit calls per budget. | | `erpc_rate_limiter_remote_admission_shedded_total` | counter | budget | Remote check fail-opened because admission semaphore full (load shed). | | `erpc_rate_limiter_remote_duration_seconds` | LabeledHistogram | budget, result | Remote rate-limit check duration. `result` ∈ `"ok"`, `"over_limit"`, `"fail_open"`. Buckets: 0.001–5 s. | #### Area 7: Upstream health (cordon, circuit-breaker, probing) | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_upstream_cordoned` | gauge | project, vendor, network, upstream, category, reason | 1 on cordon, 0 on uncordon. `category` = method string or `"*"` (wholesale). NOT the standard request-category label. `vendor` = `"n/a"` when unvendored. | | `erpc_upstream_cordon_event_total` | counter | project, network, upstream, action | Admin cordon/uncordon. `action` ∈ `"cordon"`, `"uncordon"`. | | `erpc_upstream_cordon_duration_seconds` | histogram | project, network, upstream | Seconds spent cordoned, observed on each uncordon. Buckets: 1–86400 s. | | `erpc_upstream_breaker_state_change_total` | counter | project, upstream, transition | Circuit-breaker state transition. `transition` ∈ `"closed_to_open"`, `"half_open_to_open"`, `"half_open_to_closed"`, `"open_to_half_open"`. | | `erpc_selection_probe_requests_total` | counter | network, upstream, method | Probe-mirror request fired at an excluded upstream. | | `erpc_selection_probe_errors_total` | counter | network, upstream, method, reason | Probe request errored. `reason` ∈ `"timeout"`, `"throttled"`, `"auth"`, `"skipped"`, `"error"`. `"skipped"` = upstream intentionally rejected; `"error"` = other failures. | | `erpc_selection_probe_skipped_total` | counter | network, reason | Probe candidate skipped pre-fire. `reason` ∈ `"write_method"`, `"opt_out"`, `"sampled_out"`, `"max_concurrent"`, `"no_method"`. | | `erpc_selection_probe_dropped_total` | counter | network, reason | Probe-bus publish dropped — per-network feed channel full. | #### Area 8: Selection policy | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_selection_position` | gauge | project, network, method, upstream | Tick output: 0=primary, 1+=runner-up, −1=excluded. | | `erpc_selection_score` | gauge | project, network, method, upstream | Per-upstream `sortByScore` score (lower=better). Absent for upstreams that bypassed scoring. | | `erpc_selection_eligible_upstreams` | gauge | project, network, method | Count of upstreams returned by most recent tick. | | `erpc_selection_rejection_total` | counter | project, network, method, upstream, step | Tick rejected upstream at a std-lib step. | | `erpc_selection_exclusion_total` | counter | project, network, method, upstream, reason | Exclusion event. `reason` = leaf-predicate slug. | | `erpc_selection_shadow_exclusion_total` | counter | project, network, method, upstream, reason | `shadowExcludeIf` would-have-excluded; upstream stays in rotation. | | `erpc_selection_method_block_total` | counter | project, network, method, upstream, reason | `blockMethods` blocked the upstream for `method`; it stays in rotation for other methods. | | `erpc_selection_excluded_seconds` | gauge | project, network, method, upstream | Wall-clock seconds continuously excluded. 0 when in rotation. | | `erpc_selection_readmit_total` | counter | project, network, method, upstream | Excluded → in-list transition. | | `erpc_selection_primary_switch_total` | counter | project, network, method, from, to | Primary upstream changed between ticks. | | `erpc_selection_sticky_hold_total` | counter | project, network, method, upstream | `stickyPrimary` held a primary that would otherwise flip. | | `erpc_selection_eval_duration_seconds` | histogram | project, network, method | Per-tick selection-policy eval latency. Buckets: 0.0005–1 s. | | `erpc_selection_eval_errors_total` | counter | project, network, method, kind | Eval failure. `kind` ∈ `"timeout"`, `"throw"`, `"invalid_return"`, `"fallback_default"`. | | `erpc_selection_readmit_age_seconds` | histogram | project, network, method | `now − excludedSince` at readmit. Buckets: 1–3600 s. | #### Area 9: Consensus | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_consensus_total` | counter | project, network, category, outcome, finality, user, agent_name | Consensus round completed. `outcome` ∈ `"success"`, `"consensus_on_error"`, `"dispute"`, `"low_participants"`, `"generic_error"`, `"caller_abandoned"`. | | `erpc_consensus_misbehavior_detected_total` | counter | project, network, upstream, category, finality, response_type, larger_than_consensus, user, agent_name | Upstream returned different data than consensus. `response_type` ∈ `"NonEmpty"`, `"Empty"`, `"ConsensusError"`, `"InfrastructureError"`. | | `erpc_consensus_upstream_punished_total` | counter | project, network, upstream, user, agent_name | Upstream punished after misbehavior threshold. | | `erpc_consensus_short_circuit_total` | counter | project, network, category, reason, finality, user, agent_name | Round short-circuited. `reason` ∈ `"sendrawtx_first_success"`, `"consensus_error_threshold"`, `"unassailable_lead"`. | | `erpc_consensus_wait_capped_total` | counter | project, network, category, trigger, finality, user, agent_name | Round resolved early by `maxWaitOnResult`/`maxWaitOnEmpty`. `trigger` ∈ `"result"`, `"empty"`. | | `erpc_consensus_errors_total` | counter | project, network, category, error, finality, user, agent_name | Consensus-level error by type. | | `erpc_consensus_upstream_errors_total` | counter | project, network, upstream, category, finality, response_type, error_code, user, agent_name | Participant upstream errored during consensus. `response_type` same values as misbehavior_detected. | | `erpc_consensus_panics_total` | counter | project, network, category, finality, user, agent_name | Panic recovered inside consensus. | | `erpc_consensus_cancellations_total` | counter | project, network, category, phase, finality, user, agent_name | Context cancelled during consensus. `phase` ∈ `"before_execution"`, `"after_execution"`, `"caller_abandoned"`. | | `erpc_consensus_duration_seconds` | LabeledHistogram | project, network, category, outcome, finality, user, agent_name | Consensus round duration. | | `erpc_consensus_responses_collected` | LabeledHistogram | project, network, category, vendors, short_circuited, finality, user, agent_name | Responses collected before decision. `vendors` = comma-joined sorted vendor names. `short_circuited` ∈ `"true"`/`"false"`. Linear buckets 1–10. | | `erpc_consensus_agreement_count` | LabeledHistogram | project, network, category, finality, user, agent_name | Upstreams agreeing on most common result. Linear buckets 1–10. | #### Area 10: Hedging | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_hedged_request_total` | counter | project, network, upstream, category, attempt, finality, user, agent_name | Hedged request fired. | | `erpc_network_hedge_discards_total` | counter | project, network, upstream, category, attempt, hedge, finality, user, agent_name | Hedged request discarded (wasted work; losing leg cancelled). | | `erpc_network_hedge_winner_total` | counter | project, network, upstream, category, finality | Hedge race won by the upstream whose response was kept. | | `erpc_network_hedge_delay_seconds` | LabeledHistogram | project, network, category, finality | **DORMANT** — registered but no production observe site. | #### Area 11: EVM method-specific | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_evm_get_logs_split_success_total` | counter | project, network, user, agent_name | A split `eth_getLogs` sub-request succeeded. | | `erpc_network_evm_get_logs_split_failure_total` | counter | project, network, user, agent_name | A split `eth_getLogs` sub-request failed. | | `erpc_network_evm_get_logs_forced_splits_total` | counter | project, network, dimension, user, agent_name | `eth_getLogs` forcibly split. `dimension` ∈ `"block_range"`, `"addresses"`, `"topics0"` (topics[0] OR-array only). | | `erpc_network_evm_trace_filter_split_success_total` | counter | project, network, method, user, agent_name | Split `trace_filter`/`arbtrace_filter` sub-request succeeded. | | `erpc_network_evm_trace_filter_split_failure_total` | counter | project, network, method, user, agent_name | Split `trace_filter`/`arbtrace_filter` sub-request failed. | | `erpc_network_evm_trace_filter_forced_splits_total` | counter | project, network, method, dimension, user, agent_name | `trace_filter` split. `dimension` ∈ `"block_range"`, `"from_address"`, `"to_address"`. | | `erpc_network_evm_block_range_requested_total` | counter | project, network, vendor, upstream, category, user, finality, bucket, size | Block-range heatmap. `bucket` uses tip-relative labels (`"TIP"`, `"L100k"`, `"100k-200k"`, etc.) when tip is known; falls back to static 100000-block aligned labels otherwise. **Not covered by idle sweep — cardinality is unbounded.** | | `erpc_network_evm_get_logs_range_requested` | LabeledHistogram | project, network, category, user, finality | `eth_getLogs` requested block-range size (observed value = `toBlock − fromBlock`). Buckets: 1, 10, 100, 500, 1000, 5000, 10000, 30000. | | `erpc_network_evm_trace_filter_range_requested` | LabeledHistogram | project, network, method, user, finality | `trace_filter`/`arbtrace_filter` requested block-range size. Same buckets. | #### Area 12: gRPC BDS resilience | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_grpc_bds_hard_timeout_total` | counter | project, upstream, method | BDS gRPC call hit the bounded-wait hard timeout (20 s, hard-coded). Non-zero rate indicates H2 stream wedging; the watchdog then force-replaces the connection. | | `erpc_grpc_bds_conn_replacements_total` | counter | project, upstream | BDS pool connection force-closed by stuck-call watchdog. | #### Area 13: CORS | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_cors_requests_total` | counter | project, origin | Request carrying an `Origin` header. **Note:** `project` label = `r.URL.Path` (e.g. `/myproject/evm/1`), not the project ID. | | `erpc_cors_preflight_requests_total` | counter | project, origin | Allowed-origin OPTIONS preflight. Same `project` mislabeling. | | `erpc_cors_disallowed_origin_total` | counter | project, origin | Request from disallowed origin. Same `project` mislabeling. | #### Area 14: Shadow testing | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_shadow_response_identical_total` | counter | project, vendor, network, upstream, category | Shadow upstream response identical to expected. | | `erpc_shadow_response_mismatch_total` | counter | project, vendor, network, upstream, category, finality, emptyish, larger | Shadow response differs. `emptyish` ∈ `"true"`/`"false"` (shadow was empty-ish). `larger` ∈ `"true"`/`"false"` (shadow body larger than primary). | | `erpc_shadow_response_error_total` | counter | project, vendor, network, upstream, category, error | Shadow upstream request errored. | #### Area 15: Auth | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_auth_failed_total` | counter | project, network, strategy, reason, agent_name | Client-facing auth denial. Closed `reason` set; `agent_name` always `unknown`; no `user` label. | #### Area 16: Panics | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_unexpected_panic_total` | counter | scope, extra, error | Recovered panic. `scope` ∈ `"request-handler"`, `"final-error-writer"`, `"top-level-handler"`, `"timeout-handler"`, `"validate-pattern"`, `"redis-pubsub"`, `"shared-state-registry"`, `"matcher"`. | --- ### Histogram bucket sets | Bucket set | Values | Applies to | |---|---|---| | `DefaultHistogramBuckets` (overridable via `metrics.histogramBuckets`) | 0.05, 0.5, 5, 30 s | `upstream_request_duration_seconds`, `network_request_duration_seconds`, `consensus_duration_seconds`, all 5 cache duration histograms (8 total) | | `EvmGetLogsRangeHistogramBuckets` | 1, 10, 100, 500, 1000, 5000, 10000, 30000 blocks | `network_evm_get_logs_range_requested`, `network_evm_trace_filter_range_requested` | | `CatchUpWaitHistogramBuckets` | 0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64 s | `network_data_unavailable_wait_seconds` | | hedge delay (hard-coded) | 0.01, 0.03, 0.05, 0.2, 0.3, 0.5, 0.7, 1, 3 s | `network_hedge_delay_seconds` (dormant) | | timeout duration (hard-coded) | 0.05, 0.1, 0.3, 0.5, 1, 3, 5, 10, 30 s | `network_timeout_duration_seconds` | | selection eval (hard-coded) | 0.0005, 0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1 s | `selection_eval_duration_seconds` | | readmit age (hard-coded) | 1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600 s | `selection_readmit_age_seconds` | | cordon duration (hard-coded) | 1, 10, 60, 300, 900, 1800, 3600, 7200, 21600, 86400 s | `upstream_cordon_duration_seconds` | | rate-limiter remote (hard-coded) | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5 s | `rate_limiter_remote_duration_seconds` | | response size (hard-coded) | 4096, 65536, 1048576, 16777216, 104857600 bytes | `upstream_response_size_bytes` | | consensus counts (linear) | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 | `consensus_responses_collected`, `consensus_agreement_count` | Only `DefaultHistogramBuckets` are configurable at runtime. All other bucket sets require a recompile. --- ### Observability **The metrics endpoint:** `http://:/` (any path) — the Prometheus handler is mounted at the root, so every HTTP path on port 4001 returns the full Prometheus text exposition. Plain HTTP only, no auth, no path routing. Reference scrape config at [`monitoring/prometheus/prometheus.yml`](https://github.com/erpc/erpc/blob/main/monitoring/prometheus/prometheus.yml) (scrape interval 10 s, default target `host.docker.internal:4001`). **Stock collectors** (present unless `ERPC_NOMETRICS=1`): `go_*` — Go runtime stats; `process_*` — OS process stats; `promhttp_metric_handler_*` — handler self-scrape stats. **Bundled alerting rules** (`monitoring/prometheus/alert.rules`): | Alert | Expression | Threshold | |---|---|---| | HighErrorRate | `rate(erpc_upstream_request_errors_total[5m]) / rate(erpc_upstream_request_total[5m]) > 0.05` by upstream | 5% error rate for 5 min | | SlowRequests | `histogram_quantile(0.95, rate(erpc_upstream_request_duration_seconds_bucket[5m])) > 1` by upstream | p95 > 1 s for 5 min | | HighRateLimiting | references stale metric `erpc_upstream_request_self_rate_limited_total` — use `erpc_rate_limits_total` instead | — | | NetworkRateLimiting | references stale metric `erpc_network_request_self_rate_limited_total` — use `erpc_rate_limits_total` instead | — | | HighRequestRate | `rate(erpc_upstream_request_total[5m]) by (upstream) > 1000` | >1000 rps per upstream | | LowRequestRate | `rate(erpc_upstream_request_total[5m]) by (upstream) < 1` | <1 rps per upstream for 15 min | **Metrics server log lines** (all emitted by `erpc/init.go`): | Level | Message | |---|---| | Info | `"starting metrics server on port: %d"` | | Error | `"error starting metrics server: %s"` | | Info | `"shutting down metrics server..."` | | Error | `"metrics server forced to shutdown: %s"` | | Info | `"metrics server stopped"` | | Error | `"failed to apply metrics configuration; no metric families are registered"` — a malformed `metrics.customizations` entry. `telemetry.Configure` returns before registering anything, so `/metrics` serves only the stock `go_`/`process_` collectors. Alert on this. | | Warn | `"failed to apply metrics configuration; falling back to default histogram buckets"` — an unparseable `metrics.histogramBuckets` float. Every family is still registered; only the bucket boundaries are wrong. | | Info | `"metric customizations applied"` (with `customizations`/`exposed`/`total` counts; only when `metrics.customizations` is set) | | Warn | `"metrics.customizations subjects match no known metric family; check for typos"` | | Warn | `"some metrics.customizations rules do not apply to the family they name"` | Both `"failed to apply metrics configuration"` lines are only reachable when `erpc.Init` is called as a library: the CLI rejects a malformed customization and a bad bucket list in `MetricsConfig.Validate` before `Init` runs. The wrapped error names the offending field either way. --- ### Source code entry points - [`telemetry/manager.go`](https://github.com/erpc/erpc/blob/main/telemetry/manager.go) — the definition index; the `Define*` factories; `Configure`; `SetHistogramBuckets`; `KnownFamilies`; `Gatherer` - [`telemetry/policy.go`](https://github.com/erpc/erpc/blob/main/telemetry/policy.go) — `NormalizeMetricName`; `Customization`; `MetricPolicy` (subject/label precedence, per-family buckets, legacy desugaring) - [`telemetry/gather_filter.go`](https://github.com/erpc/erpc/blob/main/telemetry/gather_filter.go) — `FilteredGatherer`, which applies the policy's drop rules to collectors the manager does not own - [`telemetry/metrics.go`](https://github.com/erpc/erpc/blob/main/telemetry/metrics.go) — all 141 metric definitions; bucket constants; `DefaultHistogramBuckets`; `ParseHistogramBuckets` - [`telemetry/labeled_histogram.go:L16-L134`](https://github.com/erpc/erpc/blob/main/telemetry/labeled_histogram.go#L16-L134) — `LabeledHistogram` with `WithLabelValues`, `DeleteLabelValues`, `ActiveLabelValues`, `rebuildInPlace` - [`telemetry/handles.go:L59-L105`](https://github.com/erpc/erpc/blob/main/telemetry/handles.go#L59-L105) — `CounterHandle`/`GaugeHandle`/`ObserverHandle` caches; `ResetHandleCache` - [`telemetry/labeled_counter.go:L14-L122`](https://github.com/erpc/erpc/blob/main/telemetry/labeled_counter.go#L14-L122) — `LabeledCounter` with `WithLabelValues`, `DeleteLabelValues`, `ActiveLabelValues`, `rebuildInPlace` - [`erpc/init.go`](https://github.com/erpc/erpc/blob/main/erpc/init.go) — initialization sequence: `MetricsConfig.TelemetryOptions` → `telemetry.Configure` → unmatched/ignored-customization warnings → network alias resolver → metrics HTTP server lifecycle - [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go) — `MetricsConfig`, `MetricsCustomizationConfig` and `MetricLabelCustomizationConfig` structs; `TelemetryOptions` - [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) — `MetricsConfig.SetDefaults` - [`common/errors.go:L17-L114`](https://github.com/erpc/erpc/blob/main/common/errors.go#L17-L114) — `errorLabelMode` global; `SetErrorLabelMode`; `ErrorSummary` - [`health/tracker.go:L481-L667`](https://github.com/erpc/erpc/blob/main/health/tracker.go#L481-L667) — `DefaultIdleEvictionAfter`; `rotateMetricsLoop`; `sweepIdle`; `sweepIdleObservers` - [`cmd/erpc/initflags.go:L22-L28`](https://github.com/erpc/erpc/blob/main/cmd/erpc/initflags.go#L22-L28) — `ERPC_NOMETRICS=1` registry replacement - [`monitoring/catch-up-metrics.md`](https://github.com/erpc/erpc/blob/main/monitoring/catch-up-metrics.md) — operator guide for reading `erpc_network_retry_attempt_total` + `erpc_network_data_unavailable_wait_seconds` together; covers `CatchUpWaitHistogramBuckets` design rationale, finality-label split, Little's Law pressure interpretation, and tuning knobs ### Related pages - [Rate limiters](/config/rate-limiters.llms.txt) — the `erpc_rate_limits_total` counter tracks every budget decision. - [Failsafe: Hedge](/config/failsafe/hedge.llms.txt) — `erpc_network_hedged_request_total` and `erpc_network_hedge_winner_total` are the hedge observability surface. - [Failsafe: Retry](/config/failsafe/retry.llms.txt) — `erpc_network_retry_attempt_total` with its `reason` label tracks retry behavior. - [Selection policies](/config/projects/selection-policies.llms.txt) — the `erpc_selection_*` family tracks tick-by-tick upstream ranking. - [Cache](/config/database.llms.txt) — `erpc_cache_get_*` and `erpc_cache_set_*` families cover all cache connector activity. - [Auth](/config/auth.llms.txt) — `erpc_auth_failed_total` for all auth strategy failures. --- --- # Simulator > Source: https://docs.erpc.cloud/reference/simulator > A local browser playground that runs a real eRPC instance against synthetic upstreams — explore routing, failsafe, and selection-policy behavior in seconds, no credentials needed. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Simulator Reproduce production routing failures, develop selection policies, and watch failover dynamics unfold — all from a browser tab, with no provider credentials, no cloud account, and no live network. Every dot on screen is a real `Network.Forward()` call; only the upstream servers and the traffic generator are synthetic. `go run ./cmd/erpc-simulator`, open `http://127.0.0.1:8080`, and start breaking things. ![The eRPC simulator UI: live request dots flowing across synthetic upstreams, with per-upstream knobs for latency, errors, throttling, and block lag](./images/erpc-simulator.png) ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: reproduce a production failover chain locally before deploying** ```text I want to run the eRPC simulator to verify my retry and hedge config handles a provider outage correctly before I deploy to production — no provider credentials needed. Walk me through starting the simulator, applying my eRPC config, and using the vendor-region-outage scenario to check failover. Read the reference: https://docs.erpc.cloud/reference/simulator.llms.txt ``` **Prompt Example #2: develop and validate a new selection policy offline** ```text I want to write a new eRPC selection policy and iterate on it in the simulator without touching production. Explain how to paste my JS policy into the editor, use the gradual-degradation scenario (90s) to stress-test it, and read the policy-history drawer steps to confirm the degrading upstream loses rank within my target window. Reference: https://docs.erpc.cloud/reference/simulator.llms.txt ``` **Prompt Example #3: capture a forensic dump for offline analysis** ```text I want to capture a JSONL forensic log of a tricky routing edge case in the eRPC simulator so I can slice it with jq later without re-running the scenario. Show me the -dump-file flag usage, the companion AGENTS.md queries, and the jq recipes to filter failed requests and per-attempt errors. Reference: https://docs.erpc.cloud/reference/simulator.llms.txt ``` **Prompt Example #4: tune synthetic upstream knobs to match my production error profile** ```text My production upstreams have specific error rates, latency distributions, and block lag values that I want to replicate in the simulator so my policy tests are realistic. Explain the UpstreamKnobs schema (base latency, jitter, errorRate, timeoutRate, throttleRate, blockLag, dataAvailability) and how to set them via the UI or set-knob WebSocket messages. Reference: https://docs.erpc.cloud/reference/simulator.llms.txt ``` --- ### Simulator — full agent reference ### How it works **Architecture overview.** The simulator is a single Go binary (`cmd/erpc-simulator/main.go`) embedding all browser assets via `//go:embed all:web`. It binds one HTTP server on `127.0.0.1:8080` (configurable via `-addr`) serving static assets at `/` and a WebSocket endpoint at `/ws`. Behind the WebSocket lives an `Orchestrator` that owns the real `*erpc.ERPC` instance, a synthetic `UpstreamHub` HTTP server (on a random loopback port), and rolling stats counters. [[`internal/simulator/orchestrator.go:L51-95`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L51-L95)] **Traffic generation.** Traffic generation is browser-side. The JavaScript runtime ticks at the configured RPS and for each tick builds a `send-batch` WebSocket frame. The backend's `Session.execute` goroutine calls `Orchestrator.Execute(ctx, method, params)` for each item, which calls `net.Forward(rctx, req)` — eRPC's real network handler. The full request path runs: selection policy → failsafe (retry/timeout/hedge/consensus) → HTTP transport to the fake upstream → response parsing. After `Forward` returns, `Execute` reads `req.ExecState().UpstreamAttemptLog()`, builds a `TraceEvent`, and queues it for the 50ms `traces` WebSocket push. [[`internal/simulator/orchestrator.go:L597-708`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L597-L708)] **UpstreamHub.** A single `http.Server` multiplexed across N synthetic upstreams at paths `/sim/`. Per request: (1) looks up `UpstreamKnobs` under RLock; (2) if `Available=false`, immediately returns HTTP 503; (3) rolls three thresholds in order — throttle rate (fast 429, no sleep), timeout rate (hang 30s after sleep), error rate (HTTP 500/502/503 or JSON-RPC -32000/-32603 in a 5-way split); (4) on success, calls `synthResult` to produce a plausible method-specific JSON-RPC response. Latency is sampled as `max(1ms, base + |gaussian()| × jitter × 0.6)`. [[`internal/simulator/upstream_sim.go:L401-468`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L401-L468)] **Block model.** Each upstream maintains an independent `atomic.Int64` head, advanced by a single hub-wide goroutine ticking every 250ms. Per-upstream `BlockTimeMs` (default 12,000ms) controls step size. `BlockLag` is subtracted from head at response time. A hub-level `hubHead` tracks the maximum across all upstreams; new upstreams seed at `22_000_000` (plausible mainnet). Block timestamps use `simGenesisUnix + block × 12s` so the health tracker's block-time EMA converges correctly. [[`internal/simulator/upstream_sim.go:L135-177`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L135-L177)] **Data availability model.** For sparse-data methods (`eth_getTransactionReceipt`, `eth_getBlockByHash`, `eth_getLogs`, `eth_getTransactionByHash`), a deterministic FNV-like hash of `(upstreamID, method, params)` determines whether the upstream "has" the data. Per-method baselines: receipt/tx 80%, block-by-hash 90%, getLogs 85%. The `DataAvailability` knob (0–1) multiplies the baseline; at exactly 1.0 it always returns data (bypasses baseline); at 0 it always misses. [[`internal/simulator/upstream_sim.go:L613-648`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L613-L648)] **Seed configuration.** On first boot the orchestrator uses `SeedYAML` — eight upstreams (alc-eth-1, alc-eth-2, drpc-eth-1, quik-eth-1, chainstack-eth-1, conduit-eth-1, self-eth-1, public-eth-1) on network `evm:1`. `scoreMetricsWindowSize: 10s` and `selectionPolicy.evalInterval: 1s` are deliberately tighter than production so health dynamics are visible in seconds, not minutes. The browser's "↺ default" button restores this YAML. [[`internal/simulator/config.go:L12-22`](https://github.com/erpc/erpc/blob/main/internal/simulator/config.go#L12-L22)] **Config apply flow.** When the browser sends `apply-config`, the YAML must have the `{SELECTION_POLICY_FUNC}` placeholder already substituted by the frontend. The backend: (1) `DecodeConfigYAML` — YAML decode + legacy migration, `KnownFields(true)` (typos are hard errors); (2) `RewriteEndpoints` — overwrites every upstream endpoint to `http:///sim/`, forces vendor type to `evm`; (3) `FinalizeConfig` — `SetDefaults` + `Validate`; (4) `syncUpstreamKnobs` — creates/refreshes/orphan-drops knob entries; (5) creates a fresh `erpc.ERPC`, bootstraps it, enables policy step log; (6) re-applies pause state. Previous eRPC instance is replaced atomically; in-flight requests against the old pointer complete normally. [[`internal/simulator/orchestrator.go:L251-298`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L251-L298)] **Selection policy live edit.** `apply-policy` compiles the JS source via `common.CompileProgram` (sobek), injects the source into the stored YAML via `injectPolicyIntoYAML`, and re-boots. `validate-policy` compiles only — no apply. The frontend sends `validate-policy` on every debounced keystroke and `apply-policy` on explicit "Apply." The policy step log is always enabled (`net.SetPolicyStepLogEnabled(true)`) so the policy-history drawer shows the full per-step chain trail on every eval tick. [[`internal/simulator/orchestrator.go:L396-421`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L396-L421)] **Scenarios.** Six built-in scripted scenarios automate upstream degradation without manual slider work, advancing via a 250ms `scenarioLoop` ticker: - `gradual-degradation` (90s) — raises `alc-eth-1` error rate 5% → 70% - `vendor-region-outage` (60s) — makes Alchemy us-east region unavailable, then restores - `traffic-spike` (60s) — degrades all upstream latency and error rates, then recovers - `hedge-saturator` (60s) — increases jitter, then pins specific upstreams to high latency - `policy-exclude-cascade` (50s) — pushes distinct failure modes onto three upstreams - `slow-network` (60s) — triples latency and doubles jitter on all upstreams Each scenario step calls the same `Orchestrator.UpdateUpstream` code path as manual slider changes. [[`internal/simulator/scenarios.go:L114-145`](https://github.com/erpc/erpc/blob/main/internal/simulator/scenarios.go#L114-L145)] **Knob live tuning.** Every synthetic upstream exposes `UpstreamKnobs` — latency, error rate, timeout rate, throttle rate, block lag, data availability, and a hard on/off toggle — changeable live via `set-knob` WebSocket messages without reloading the config. Default knob values are biased by tags: `premium` starts at `base=35ms, error=0.003`; `tier:fallback` starts at `base=180ms, error=0.080, blockLag=4`. The "inject 60s failure" button forces `errorRate ≥ 0.9, timeoutRate ≥ 0.3` for 60 seconds via `InjectFailureUntilMs`. **Pause.** `SetPaused(true)` stops `Execute` from forwarding requests (returns nil) AND pauses the policy engine's eval ticker via `net.SetPolicyEnginePaused(true)`. This keeps position/score pills in the upstream panel stable while paused. Both flags re-sync when a config or policy apply lands mid-pause — the new engine starts un-paused and is immediately re-paused. [[`internal/simulator/orchestrator.go:L219-234`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L219-L234)] [[`internal/simulator/orchestrator.go:L289-296`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L289-L296)] **Dump file.** Pass `-dump-file path/to/run.jsonl` to capture a JSONL forensic log. Every observable event is recorded: `boot`, `config.snapshot`, `config.apply`, `policy.apply`, `knob.change`, `knob.inject`, `scenario.start`, `scenario.stop`, `scenario.event`, `paused`, `request`, `stats`. The `request` event carries the full `TraceEvent` (per-attempt log, selection trail, outcome) plus raw params and JSON body. A companion `*.AGENTS.md` is written at open with field descriptions and idiomatic `jq` queries. Buffer is 64KB, flushed every 1s; a crash loses at most ~1s of trailing events. [[`internal/simulator/dump.go`](https://github.com/erpc/erpc/blob/main/internal/simulator/dump.go)] **Rolling stats and WebSocket cadence.** `stats` frames are sent every 200ms; `traces` are batched every 50ms with a cap of 256 items per flush. The session's outbound channel holds 256 frames; when full, frames are dropped silently — the UI is lossy by design. A 1-second bucket rolls every second; `Stats()` returns the previous second's completed bucket for the RPS display. Per-upstream latency percentiles (p50/p70/p90/p95) keep the last 300 samples. Policy scores and health tracker metrics are read live from the engine and tracker on every `Stats()` call — the simulator has no parallel bookkeeping for these. [[`internal/simulator/orchestrator.go:L804-970`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L804-L970)] [[`internal/simulator/ws.go:L19-64`](https://github.com/erpc/erpc/blob/main/internal/simulator/ws.go#L19-L64)] ### Config schema The simulator accepts four CLI flags. Configuration of the eRPC instance is done through the browser YAML editor or `apply-config` WebSocket messages — there is no separate simulator config file. | Flag | Type | Default | Behavior / footguns | |---|---|---|---| | `-addr` | `string` | `"127.0.0.1:8080"` | Bind address for the HTTP server and `/ws` WebSocket endpoint. Source: [`cmd/erpc-simulator/main.go:L83`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L83) | | `-log-level` | `string` | `"warn"` | zerolog level for the in-process eRPC instance. Valid values: `trace`, `debug`, `info`, `warn`, `error`. Source: [`cmd/erpc-simulator/main.go:L84`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L84) | | `-web-dir` | `string` | `""` (embedded assets) | When non-empty, serve UI assets from this directory instead of the embedded filesystem. Enables hot-reload of JSX/CSS without Go rebuilds. Source: [`cmd/erpc-simulator/main.go:L86-91`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L86-L91) | | `-dump-file` | `string` | `""` (disabled) | JSONL forensic log path. A companion `*.AGENTS.md` is written once at open. Append-only: restarts accumulate multiple `boot` events. Source: [`cmd/erpc-simulator/main.go:L93-99`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L93-L99) | #### UpstreamKnobs schema All fields are live-tunable via `set-knob` WebSocket messages (`UpstreamKnobPatch`; pointer fields, nil = unchanged). Struct at [`internal/simulator/types.go:L47-77`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L47-L77). | Field | JSON key | Type | Default (standard) | Default (premium tag) | Default (fallback tag) | Behavior / footguns | |---|---|---|---|---|---|---| | `ID` | `id` | string | (from YAML) | — | — | Upstream identity key. Immutable after boot. | | `Vendor` | `vendor` | string | (from YAML vendorName) | — | — | Display name in the upstream panel. | | `Tags` | `tags` | `[]string` | (from YAML) | — | — | Propagated to health tracker and policy stdlib `u.tags`. | | `Endpoint` | `endpoint` | string | `http:///sim/` | — | — | Loopback URL rewritten by `RewriteEndpoints` at every config apply. Source: [`internal/simulator/types.go:L50`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L50) | | `BaseLatencyMs` | `base` | `float64` | `50` | `35` | `180` | Mean latency in ms. Latency model: `max(1, base + \|gaussian()\| × jitter × 0.6)`. Source: [`internal/simulator/defaults.go:L14`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L14) | | `JitterMs` | `jitter` | `float64` | `20` | `12` | `110` | Gaussian sigma multiplier for latency variance. Source: [`internal/simulator/defaults.go:L15`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L15) | | `ErrorRate` | `error` | `float64` | `0.01` | `0.003` | `0.080` | Probability [0..1] of an error response. Mix: HTTP 500, 502, 503, JSON-RPC -32000, -32603. Source: [`internal/simulator/defaults.go:L16`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L16) | | `TimeoutRate` | `timeoutRate` | `float64` | `0.002` | `0.002` | `0.020` | Probability [0..1] of hanging 30s. Evaluated after the throttle check. Source: [`internal/simulator/defaults.go:L17`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L17) | | `ThrottleRate` | `throttleRate` | `float64` | `0.002` | `0.002` | `0.040` | Probability [0..1] of HTTP 429 (fast reject, no sleep). First check in outcome model. Source: [`internal/simulator/defaults.go:L18`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L18) | | `BlockLag` | `blockLag` | `int` | `0` | `0` | `4` | Blocks behind hub head reported in `eth_blockNumber` responses. Source: [`internal/simulator/defaults.go:L19`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L19) | | `BlockTimeMs` | `blockTimeMs` | `int` | `12000` | `12000` | `12000` | Milliseconds between block advances. Zero or negative treated as 12000. Source: [`internal/simulator/defaults.go:L20`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L20) | | `Available` | `available` | `bool` | `true` | `true` | `true` | If false, upstream immediately returns HTTP 503 without any outcome roll. Source: [`internal/simulator/defaults.go:L21`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L21) | | `DataAvailability` | `dataAvailability` | `float64` | `1.0` | `1.0` | `1.0` | Multiplier [0..1] on per-method sparse-data baselines. 1.0 = always has data (bypasses baseline). 0 = always misses. Source: [`internal/simulator/defaults.go:L22-23`](https://github.com/erpc/erpc/blob/main/internal/simulator/defaults.go#L22-L23) | | `InjectFailureUntilMs` | `injectFailureUntilMs` | `int64` | `0` (disabled) | — | — | Unix-ms deadline for injected failure override: forces `errorRate ≥ 0.9, timeoutRate ≥ 0.3`. Source: [`internal/simulator/types.go:L69-77`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L69-L77) | **Default bias rules** (`internal/simulator/defaults.go`): - Tag `premium`: `base=35`, `jitter=12`, `error=0.003` - Tag `dedicated`: `base=45`, `jitter=18`, `error=0.005` - Tag `tier:fallback`: `base=180`, `jitter=110`, `error=0.080`, `timeoutRate=0.020`, `throttleRate=0.040`, `blockLag=4` - Vendor `self-hosted`: `base=28`, `jitter=12`, `error=0.02` - Vendor `public` (no fallback tag): `error=0.08`, `base=180`, `jitter=110`, `blockLag=4` ### Worked examples **1. Reproduce a production failover chain offline.** You want to confirm that when your primary drops, the retry/hedge combo still routes cleanly without thundering-herd. Set `alc-eth-1` to `available=false` in the knob panel and watch the traces drawer. When you see `selReason: "retry"` or `outcome: "hedge-win"` for all requests, failover is working. Then start `vendor-region-outage` to let the scenario automate the degradation/restore cycle and verify score recovery: ``` start-scenario: vendor-region-outage # watch policy-history frames: excluded[] should clear within ~10s of restore ``` **2. Tune selection policy against bimodal data availability.** You have premium and fallback upstreams with different data fill rates; you want your policy to prefer upstreams that actually have the data. Set `dataAvailability=0.3` on fallback upstreams and `dataAvailability=1.0` on premium. Run `eth_getTransactionReceipt` traffic and watch the `traces` frame — `selReason: "sweep"` on the first attempt means the policy fell back for a data miss. Adjust your policy's `missRate` weight until sweeps disappear from primary attempts. **3. Validate a new selection policy before deploying.** Paste your policy JS into the policy editor, click Validate to compile-check, then Apply. Run the `gradual-degradation` scenario (90s) while watching the policy-history drawer — the `steps[]` chain shows exactly which upstream attribute triggered each position change. Compare score trajectories before and after to confirm the degrading upstream loses rank within your target latency window. **4. Offline forensic replay with `-dump-file`.** Run a session that exercises a tricky edge case, then exit: ```bash go run ./cmd/erpc-simulator -dump-file run.jsonl # ... reproduce the issue ... # Ctrl-C jq 'select(.kind=="request" and .body.outcome=="fail")' run.jsonl | head -20 jq 'select(.kind=="request") | .body.attempts[] | select(.error != null)' run.jsonl ``` The `*.AGENTS.md` companion lists every queryable field and idiomatic `jq` recipes for slicing by outcome, upstream, and method. ### Request/response behavior **WebSocket protocol — client → server frames:** ```json {"kind":"hello"} {"kind":"send-batch","items":[{"id":123,"method":"eth_blockNumber","params":[]}]} {"kind":"send-one","req":{"id":123,"method":"eth_blockNumber","params":[]}} {"kind":"set-knob","id":"alc-eth-1","patch":{"error":0.1,"base":200}} {"kind":"apply-policy","src":""} {"kind":"validate-policy","src":""} {"kind":"apply-config","yaml":""} {"kind":"validate-config","yaml":""} {"kind":"set-paused","paused":true} {"kind":"start-scenario","name":"gradual-degradation"} {"kind":"stop-scenario"} ``` **WebSocket protocol — server → client frames:** ```json {"kind":"snapshot","body":{"yaml":"...","defaultYaml":"...","upstreams":[...],"policy":"...","defaultPolicy":"...","paused":false,"serverTimeMs":1234567890}} {"kind":"stats","body":{"tick":...,"actualRps":...,"lastSecondTotal":...,"lastSecondSucc":...,"lastSecondErr":...,"lastSecondCache":...,"lastSecondRetryOk":...,"lastSecondHedge":...,"lastSecondMiss":...,"perUpstreamLastS":{...},"upstreams":{...},"policyLastSwitchMs":...,"scenario":...}} {"kind":"traces","body":{"items":[...]}} {"kind":"policy-history","body":{"items":[...]}} {"kind":"policy-result","body":{"ok":true,"compiledAt":1234567890}} {"kind":"policy-validate-result","body":{"ok":false,"error":"ReferenceError: x is not defined"}} {"kind":"config-result","body":{"ok":true,"appliedAt":1234567890}} {"kind":"config-validate-result","body":{"ok":false,"error":"yaml decode: ..."}} {"kind":"knob-changed","body":{}} {"kind":"error","body":{"msg":"unknown kind: foo"}} ``` `TraceEvent.outcome` values: `"ok"`, `"retry-ok"`, `"hedge-win"`, `"fail"`, `"cache-hit"`. Source: [`internal/simulator/types.go:L107`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L107) `TraceAttempt.selReason` values: `"primary"`, `"retry"`, `"hedge"`, `"consensus_slot"`, `"sweep"`. Source: [`internal/simulator/types.go:L165`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L165) `StatsFrame.upstreams` map values (`UpstreamStatsRow`): `errorRate`, `throttleRate`, `misbehaviorRate` from the health tracker; `p50`, `p70`, `p90`, `p95` in ms; `blockHeadLag`, `finalizationLag` in blocks; `blockHeadLagSeconds`, `finalizationLagSeconds` (block count × tracker's EMA block-time in seconds); `cordoned`, `cordonedReason`; `score` from `Engine.GetScores("*")`; `position` (0 = primary, 1..N = fallback, -1 = excluded); `selectionsLast` (count in previous 1-second bucket). `PolicyDecisionFrame` (in `policy-history`): `id` (slug formatted as `//`), `steps[]` (stdlib step chain — always populated in simulator, disabled in production), `metrics` (per-upstream metric snapshot the eval saw at that tick), `perUpstreamScore` (JS-produced scores from that tick), `excluded[]` (excluded upstreams with step and reason). **Outcome roll order** (per request, first match wins). Source: [`internal/simulator/upstream_sim.go:L401-465`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L401-L465) 1. `roll < throttleRate` → HTTP 429 (no sleep) 2. Sleep `max(1ms, base + |gaussian()| × jitter × 0.6)` 3. `(roll - throttleRate) < timeoutRate` → hang 30s (simulates eRPC timeout) 4. `(roll - throttleRate - timeoutRate) < errorRate` → error (5-way mix: HTTP 500, 502, 503, JSON-RPC -32000, -32603) 5. Otherwise → success + `synthResult` **InjectedFailure override** — active when `InjectFailureUntilMs > 0` AND `now.UnixMilli() < InjectFailureUntilMs`. While active: `errRate = max(errRate, 0.9)`, `timeoutRate = max(timeoutRate, 0.3)`. Source: [`internal/simulator/types.go:L75-77`](https://github.com/erpc/erpc/blob/main/internal/simulator/types.go#L75-L77) **synthResult method coverage** — the fake upstream returns plausible responses for: - `eth_blockNumber` — hex(head - blockLag) - `eth_chainId` — always `"0x1"` (see edge cases) - `net_version` — `"1"` - `eth_syncing` — `false` - `eth_getBalance` — deterministic non-zero from params hash - `eth_getCode` — synthetic non-empty bytecode - `eth_call` — synthetic non-empty result - `eth_estimateGas` — `"0x5208"` (21000) - `eth_gasPrice` — `"0x3b9aca00"` (1 gwei) - `eth_getTransactionCount` — deterministic 0–999 nonce - `eth_getBlockByNumber` — block object with number/hash/parentHash/timestamp; null for blocks above head - `eth_getBlockByHash` — 90% data availability baseline (scaled by knob) - `eth_getTransactionReceipt` — 80% baseline (scaled by knob) - `eth_getTransactionByHash` — 80% baseline (scaled by knob) - `eth_getLogs` — 85% baseline; one synthetic log entry on hit, empty array on miss - `eth_feeHistory` — minimal stub - all others — `"0x0"` Source: [`internal/simulator/upstream_sim.go:L481-608`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L481-L608) ### Best practices - **Set `scoreMetricsWindowSize` and `evalInterval` back to production values** before drawing conclusions about routing timing. The SeedYAML defaults (`10s`/`1s`) are deliberately fast for visibility — production typically uses `60s`/`5s`. - **Use `DataAvailability=1.0` on all upstreams** when you only want to test routing/failsafe mechanics, not data-replication behavior. At 1.0, `synthResult` always returns data for every sparse method, eliminating sweep retries that would otherwise add noise. - **Pair `-dump-file` with every experiment** where you intend to iterate offline. The JSONL log lets you replay and slice the attempt chain (`jq '.body.attempts[]'`) without having to reproduce the exact scenario timing again. - **Override `AttemptErrorDetailMaxLen=0`** is already set by default in the simulator binary — don't re-add it. In production builds it is limited to prevent large error payloads; the simulator intentionally removes that cap to show the full chain. - **Use `-log-level debug`** when a scenario produces unexpected outcomes not explained by the traces drawer — the in-process eRPC instance logs upstream selection and failsafe decisions at debug level. - **`-web-dir` accelerates policy development.** Point it at `cmd/erpc-simulator/web/` and save your JSX changes — the browser hard-reload picks them up instantly without a Go rebuild, making the edit–apply–observe loop faster. - **Run the simulator's `seed_boot_test.go`** after modifying the SeedYAML or default policy — it verifies the init() expansion, the absence of the placeholder literal, and that the full eRPC stack bootstraps cleanly. ### Edge cases & gotchas 1. **`{SELECTION_POLICY_FUNC}` must be substituted by the browser before `apply-config`.** The backend has a safety net (`expandPolicyPlaceholder`) that substitutes the default policy if the placeholder leaks through a direct API call, but the browser is the authoritative substitution site. Source: [`internal/simulator/config.go:L148-153`](https://github.com/erpc/erpc/blob/main/internal/simulator/config.go#L148-L153), [`internal/simulator/orchestrator.go:L153`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L153) 2. **`eth_chainId` always returns `"0x1"` regardless of configured chainId.** This is a known simplification; the SeedYAML uses `chainId: 1` (Ethereum mainnet) to match. Source: [`internal/simulator/upstream_sim.go:L489`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L489) 3. **Batch upstream request: first transport error aborts the whole batch.** A 429 or 5xx on one item fails the entire batch transport — matching real HTTP behavior. Source: [`internal/simulator/upstream_sim.go:L358-364`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L358-L364) 4. **Orphan knob cleanup on `apply-config`.** When an upstream is removed from the YAML, its knob and rolling stats entry are permanently dropped. Manually-tuned values for that upstream are lost on config reload. Source: [`internal/simulator/orchestrator.go:L333-341`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L333-L341) 5. **`-dump-file` is append-only.** Restarts accumulate multiple `boot` events. Use `jq 'select(.kind=="boot")'` to find session boundaries, then bound queries with the most recent `boot` timestamp. 6. **`DataAvailability = 1.0` bypasses per-method baselines.** At exactly 1.0, `scaleAvailability` returns 100 regardless of the method's natural miss rate. Source: [`internal/simulator/upstream_sim.go:L635-638`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L635-L638) 7. **All cached assets are `no-store`.** Every page load re-fetches all JSX/CSS. This prevents stale-asset bugs during development but adds ~100ms to initial load time. Source: [`cmd/erpc-simulator/main.go:L188-193`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L188-L193) 8. **Per-request context timeout is 30s** — a hard cap in `Execute` independent of eRPC's failsafe timeout config. Source: [`internal/simulator/orchestrator.go:L617`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L617) 9. **Response body preview cap is 8KB** with truncation markers `"\n…[truncated]…\n"` when exceeded. Source: [`internal/simulator/orchestrator.go:L713-729`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L713-L729) 10. **`scoreMetricsWindowSize: 10s` and `evalInterval: 1s`** in SeedYAML are intentionally tighter than production defaults — they make health score dynamics visible in seconds. Override them in your YAML if you need production-realistic timing. Source: [`internal/simulator/config.go:L43-196`](https://github.com/erpc/erpc/blob/main/internal/simulator/config.go#L43-L196) 11. **Legacy config migration is wired** — the simulator accepts old-style YAML without errors, the same as the production binary. Source: [`cmd/erpc-simulator/main.go:L73`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L73) 12. **`AttemptErrorDetailMaxLen` is set to 0 (unlimited)** so the lifecycle drawer shows the full per-attempt error chain. Production binaries truncate this. Source: [`cmd/erpc-simulator/main.go:L79`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L79) 13. **Step log overhead.** `net.SetPolicyStepLogEnabled(true)` is called at every boot. Production has this off by default; the always-on step trail makes policy evals in the simulator slightly heavier than production. Source: [`internal/simulator/orchestrator.go:L287`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L287) 14. **Static delay `min`/`max` are ignored.** If you paste a hedge config with `quantile=0` (static mode) and also set `min`/`max`, those bounds are silently ignored — `Resolve` returns `base` unchanged. 15. **`DecodeConfigYAML` uses `KnownFields(true)`.** Any unrecognized YAML key is a hard decode error — typos in the YAML editor fail immediately rather than being silently ignored. Source: [`internal/simulator/config.go:L208`](https://github.com/erpc/erpc/blob/main/internal/simulator/config.go#L208) 16. **`upstream_sim.go` uses `math/rand`, not `crypto/rand`, for all simulation randomness** (throttle/timeout/error dispatch, Box-Muller sampling). This is intentional for statistical sampling; `#nosec G404` annotations in the source acknowledge the deliberate choice. Source: [`internal/simulator/upstream_sim.go:L415`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L415) 17. **Policy engine pause state re-applied after every config/policy apply.** Because a fresh `*erpc.Network` is created each time, the new engine starts running by default. Without re-applying pause, the UI would show drifting policy decisions while the simulator is paused. Source: [`internal/simulator/orchestrator.go:L289-296`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L289-L296) 18. **`SeedYAML` const retains `{SELECTION_POLICY_FUNC}` placeholder by design.** This is what the `snapshot` frame returns as `defaultYaml` for the browser's "↺ default" button (the frontend shows the templated view). Only `SeedYAMLExpanded` has the placeholder substituted; this is validated in `seed_boot_test.go:TestSeedYAMLExpanded_IsValid`. 19. **WebSocket read limit is 8MB per message.** Messages larger than 8MB are rejected. Source: [`internal/simulator/ws.go:L53`](https://github.com/erpc/erpc/blob/main/internal/simulator/ws.go#L53) ### Observability The simulator does NOT export Prometheus metrics. Observability surfaces are: | Surface | Cadence | Content | |---|---|---| | WebSocket `stats` frame | 200ms | Aggregate RPS, per-upstream health (error/throttle/misbehavior rates), p50–p95 latency, block lag, policy positions and scores | | WebSocket `traces` frame | 50ms (up to 256 items) | Per-request `TraceEvent`: outcome, per-attempt log with upstream ID, latency, error, selection reason, response preview (8KB cap) | | WebSocket `policy-history` frame | Piggybacked on `stats` | Last 16 policy eval decisions: step chain, per-upstream metric snapshot, scores, exclusions | | `-dump-file` JSONL | Per-event, 1s flush | All event types including full `TraceEvent`; `*.AGENTS.md` with `jq` investigation guide | | stderr | Real-time | zerolog at `-log-level` (default `warn`); dumper flush warnings | ### Source code entry points - [`cmd/erpc-simulator/main.go:L73-L99`](https://github.com/erpc/erpc/blob/main/cmd/erpc-simulator/main.go#L73-L99) — entry point: CLI flags, legacy migration wiring, `AttemptErrorDetailMaxLen`, HTTP server setup, 5s shutdown grace - [`internal/simulator/orchestrator.go:L51-L95`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L51-L95) — `Orchestrator` struct: owns `*erpc.ERPC`, `UpstreamHub`, rolling stats counters - [`internal/simulator/orchestrator.go:L251-L298`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L251-L298) — `ApplyConfig`: decode → rewrite endpoints → finalize → sync knobs → bootstrap fresh ERPC → re-apply pause - [`internal/simulator/orchestrator.go:L597-L708`](https://github.com/erpc/erpc/blob/main/internal/simulator/orchestrator.go#L597-L708) — `Execute`: calls `net.Forward`, reads `UpstreamAttemptLog`, builds `TraceEvent` - [`internal/simulator/upstream_sim.go:L401-L468`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L401-L468) — outcome roll: throttle → sleep → timeout → error → success + `synthResult` - [`internal/simulator/upstream_sim.go:L481-L608`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L481-L608) — `synthResult`: method-specific response generation for all supported EVM methods - [`internal/simulator/upstream_sim.go:L135-L177`](https://github.com/erpc/erpc/blob/main/internal/simulator/upstream_sim.go#L135-L177) — block advancement ticker: 250ms hub loop, per-upstream `BlockTimeMs` - [`internal/simulator/ws.go:L19-L64`](https://github.com/erpc/erpc/blob/main/internal/simulator/ws.go#L19-L64) — `Session` WebSocket handler: stats/trace/policy-history tickers, outbound channel - [`internal/simulator/config.go:L12-L22`](https://github.com/erpc/erpc/blob/main/internal/simulator/config.go#L12-L22) — `SeedYAML` const and `init()` expansion to `SeedYAMLExpanded` - [`internal/simulator/scenarios.go:L114-L145`](https://github.com/erpc/erpc/blob/main/internal/simulator/scenarios.go#L114-L145) — scenario `advanceScenario`: 250ms ticker, at-or-after step dispatch - [`internal/simulator/dump.go`](https://github.com/erpc/erpc/blob/main/internal/simulator/dump.go) — `Dumper`: JSONL event recorder, 64KB buffer, 1s flush loop, `*.AGENTS.md` companion template - [`internal/simulator/yaml_patch.go`](https://github.com/erpc/erpc/blob/main/internal/simulator/yaml_patch.go) — `injectPolicyIntoYAML`, `expandPolicyPlaceholder` - [`internal/simulator/seed_boot_test.go`](https://github.com/erpc/erpc/blob/main/internal/simulator/seed_boot_test.go) — `TestSeedYAMLExpanded_IsValid`: verifies `init()` expansion, placeholder absent, default policy body present, comments survive ### Related pages - [Selection policies](/config/projects/selection-policies.llms.txt) — the primary thing you develop and iterate on in the simulator. - [Retry](/config/failsafe/retry.llms.txt) — failsafe behavior visible in `selReason: "retry"` trace attempts. - [Hedge](/config/failsafe/hedge.llms.txt) — failsafe behavior visible in `outcome: "hedge-win"` trace events. - [Timeout](/config/failsafe/timeout.llms.txt) — failsafe behavior; a 30s simulated hang triggers this in the simulator. - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the production scenario the simulator lets you rehearse. --- --- # Commitment & finality > Source: https://docs.erpc.cloud/reference/svm/commitment > Pin one Solana commitment level across every upstream so the cache and consensus key on identical data — eRPC injects it shape-aware per method, clamps it where a method refuses it, and never rewrites what your client asked for. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Commitment & finality Two Solana upstreams with different server-side commitment defaults return subtly different data for the identical request — poisoning the cache and turning consensus into a permanent dispute. eRPC fixes this by stamping one network-level commitment onto every outgoing request whose params omit it, at the exact param position each method expects, and by classifying finality from the commitment that *actually reaches the upstream*. **What you get** - One commitment level observed by every upstream, regardless of vendor defaults - Shape-aware injection per method — the options object goes where Solana expects it, never where it corrupts a valid request - Automatic clamping for methods that refuse `processed`, instead of a `-32602` from the upstream - A caller-supplied `commitment` is never rewritten ## Quick taste Illustrative, not a tuned production config — pin `confirmed` across every SVM network in the project: **Config path:** `projects[].networkDefaults.svm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: svm: # every upstream now observes the same commitment; cache keys and # consensus votes compare like-for-like commitment: confirmed networks: - architecture: svm svm: cluster: mainnet-beta ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { svm: { // every upstream now observes the same commitment; cache keys and // consensus votes compare like-for-like commitment: "confirmed", }, }, networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta" } }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: pin one commitment level across all Solana upstreams** ```text My eRPC Solana upstreams return inconsistent data for identical requests because each vendor has a different server-side commitment default. Set a network-level default commitment so every upstream observes the same level, and explain what it does to cache finality classification. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/reference/svm/commitment.llms.txt ``` **Prompt Example #2: debug a -32602 'does not support commitment below confirmed'** ```text My eRPC deployment has svm.commitment: processed and some getBlock calls fail with -32602 "Method does not support commitment below confirmed". Explain eRPC's clamping behavior, which methods are affected, and whether the error is coming from my own explicit commitment param or from the injected default. Reference: https://docs.erpc.cloud/reference/svm/commitment.llms.txt ``` **Prompt Example #3: explain why my finalized getBalance is not cached permanently** ```text I pass commitment: finalized on getAccountInfo through eRPC and expected permanent caching, but every request goes to an upstream. Explain how eRPC classifies SVM finality versus commitment, and what cache policies I actually need. Reference: https://docs.erpc.cloud/reference/svm/commitment.llms.txt ``` --- ### Commitment & finality — full agent reference ### How it works **Commitment vs finality are two different questions.** Conflating them is the trap this design exists to avoid: | Question | Answered by | `getBalance` at `commitment: finalized` | |---|---|---| | "Which slot does the node evaluate this at?" | `IsFinalizedCommitment` — used for **routing** and upstream selection | `finalized` | | "Is this response immutable enough to cache?" | `GetFinality` — used for **cacheability** | `realtime` | Two predicates answer them, and they differ in exactly one case — a request that pins **no** commitment: | Predicate | Question | Unpinned request | |---|---|---| | `effectiveCommitment` | Which level will the **node** apply? | `finalized` — Solana's documented default (`CommitmentConfig::default()`) | | `resolveCommitment` | Which level does **eRPC pin**? | `""` — nothing is injected | `effectiveCommitment` drives every **serving** decision: the `getBlock` availability guard, the `getSlot` tip eRPC advertises, which slot counter the routing filters compare (`IsFinalizedCommitment`), and which view a harvested `context.slot` feeds. Reading the unpinned case as "unknown" is what left implicit-commitment `getBlock` traffic bounded by the indexed frontier alone — forwarded into the ~60-slot band above the finalized root that every upstream answers `-32004` for. `resolveCommitment` drives injection and **cacheability** (`GetFinality`), which stays deliberately stricter: `finality: finalized` is the zero value an unset-TTL policy matches, so a wrong promotion pins a value forever while a wrong demotion costs one re-fetch. An unpinned slot-addressed read therefore classifies `unfinalized`; set `svm.commitment` to have it cached as final. Use `IsFinalizedCommitment` semantics when reasoning about which upstream can serve a request; use `GetFinality` semantics when reasoning about cache policies. **Why `finalized` does not mean immutable.** Solana's `finalized` commitment is the state at the latest **rooted** slot, and the rooted slot advances roughly every 400 ms. It is a moving head, exactly like EVM's `latest` tag — not a finality horizon like EVM's `finalized` block. Only a response pinned to an explicit slot or transaction signature is immutable once that slot is rooted. The full classification table is on the [SVM cache page](/config/database/svm-json-rpc-cache.llms.txt). **`resolveCommitment` decides from request shape plus config, never from mutation state.** It returns the pinned commitment (`""` when nothing is pinned — the node applies its own default, which `effectiveCommitment` reports as `finalized`), the action injection should take, and the param index. Because it never inspects whether injection already ran, it returns the same answer called before or after injection: | Request shape | Result | |---|---| | explicit `commitment` already present in params | that value, **never rewritten** | | method not in the injection table, or no valid network default | `""`, injection skipped | | options slot holds an object | inject into it | | options slot is the next free position | append a new options object | | options slot holds a non-object (legacy `getBlock(slot, "base64")` encoding form) | `""`, injection skipped — a valid request shape is never corrupted | | required positional args missing (including `getBlocks` with no start slot) | `""`, injection skipped | **Config-less reads get `{}` when nothing is pinned.** Some providers treat the optional config object of `getBlock`, `getTransaction` and `getProgramAccounts` as required, and answer a request without it with `-32602` "Invalid params" (`missing value for required argument 1`). With no network default, eRPC appends `{}` to such a request (e.g. `getBlock [slot]` becomes `[slot, {}]`). Agave's config for these methods has only optional fields, so `{}` means exactly agave's defaults, and `[slot]` and `[slot, {}]` share one cache key. Methods whose config is a bare commitment object (`getTokenSupply`, `getInflationGovernor`, …) never get `{}`: agave answers it with `-32602` "missing field `commitment`". **Injection runs at the project layer, before the cache read.** Despite the hook's name it is invoked from `HandleProjectPreForward`, ahead of the network-layer cache lookup, and it invalidates the memoized `CacheHash` so the cache keys on the rewritten body. Running it after the cache read would key every request on its pre-injection params and produce a permanent cache miss. **Options-index table.** Solana puts the config object at a different param position per method, so injection is table-driven: | Options position | Methods | |---|---| | index `0` (first/only param) | `getBlockHeight`, `getBlockProduction`, `getEpochInfo`, `getInflationGovernor`, `getLargestAccounts`, `getLatestBlockhash`, `getSlot`, `getSlotLeader`, `getStakeMinimumDelegation`, `getSupply`, `getTransactionCount`, `getVoteAccounts` | | index `1` (one positional arg first) | `getAccountInfo`, `getBalance`, `getMinimumBalanceForRentExemption`, `getBlock`, `getMultipleAccounts`, `getProgramAccounts`, `getSignaturesForAddress`, `getStakeActivation`, `getTokenAccountBalance`, `getTokenLargestAccounts`, `getTokenSupply`, `getTransaction`, `isBlockhashValid` | | index `2` (two positional args first) | `getBlocksWithLimit`, `getTokenAccountsByDelegate`, `getTokenAccountsByOwner` | | trailing object, ≥1 positional arg required | `getBlocks` (`[start]` \| `[start, end]`) | | trailing object, no positional arg required | `getLeaderSchedule` (`[]` \| `[{cfg}]` \| `[slot]` \| `[slot, {cfg}]`) | Deliberately excluded: **write/effectful methods** (they use a method-specific field, see below); **no-parameter methods** (`getGenesisHash`, `getVersion`, `getHealth`, `getIdentity`, `getInflationRate`, `getBlockTime`, …) where appending an options object yields `-32602` "No parameters were expected"; and **methods whose config carries no commitment field** (`getSignatureStatuses`, whose only option is `searchTransactionHistory`). **Clamping, not skipping.** Five methods reject `commitment: processed` outright — agave answers `-32602` "Method does not support commitment below `confirmed`", because a processed slot can sit on a minority fork that is later abandoned: ``` atLeastConfirmedMethods = getBlock, getBlocks, getBlocksWithLimit, getSignaturesForAddress, getTransaction ``` When the configured default is `processed` and the target method is in that set, eRPC injects `confirmed` instead. Clamping rather than skipping is deliberate: skipping would leave each upstream on its own server-side default — precisely the divergence injection exists to eliminate — and would make `resolveCommitment` report `""`, so finality classification and the cache key would lose the commitment too. **Clamping applies only to the injected default.** A caller-supplied commitment is classified explicit and never rewritten. If a client explicitly asks `getBlock` for `processed`, the upstream's `-32602` is the honest answer; silently upgrading it would hand back data the client did not ask for. **Write-path commitment.** Write and effectful methods express commitment through a method-specific field, so this is *not* a blanket `preflightCommitment`: | Method | Config param index | Field | |---|---|---| | `sendTransaction` | 1 | `preflightCommitment` (governs the preflight simulation; ignored when `skipPreflight` is true) | | `simulateTransaction` | 1 | `commitment` | | `requestAirdrop` | 2 | `commitment` | `sendRawTransaction` is intentionally absent — it is a non-spec alias carrying a raw transaction string with no config object to normalize. These methods are never cached, so the driver here is cross-upstream consistency, not cache-key stability. The write path honors a caller-supplied value, skips when no valid network default is set, clamps, and never corrupts a legacy non-object slot or fabricates missing positional args. **`minContextSlot` is a node-freshness floor, not a history bound.** Per the Solana RPC reference it is the minimum bank slot at which a request may be **evaluated**. It is *not* a lower bound on returned history and never restricts how far back a query may look — `getBalance(pubkey, {minContextSlot: 1})` still answers at the current head. Consequently: - It is **not** a finality-promotion signal. A `minContextSlot` on a moving-head read does not make the response immutable. - It **is** used to pre-filter upstreams: a request carrying `minContextSlot` skips upstreams whose tracked slot (at the request's commitment) is known to be behind it, avoiding a guaranteed `-32016` round-trip. The comparison slot matches the commitment — a finalized-commitment request needs the node's *finalized* slot at `minContextSlot`, anything weaker needs only the processed tip. - It **is** the SVM cache's partition dimension (`:`). The upstream pre-filter is defensive: unknown state (no poller, zero slot, non-SVM upstream) never excludes, and if every upstream would be excluded the original list is returned so the `-32016` failover path reports the truth rather than an empty pool. **`getGenesisHash` short-circuit.** Cluster genesis hashes are immutable, so `getGenesisHash` is answered from a hardcoded table with no upstream round-trip — mirroring EVM's `eth_chainId` short-circuit. ### Config schema | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[*].svm.commitment` | string | `""` — **no default** | One of `finalized`, `confirmed`, `processed`. When unset, nothing is injected and each node applies its own default (Solana's is `finalized`), so a vendor that deviates can disagree with the pool. Serving and routing assume that documented default; **cacheability does not** — unpinned slot-addressed reads classify `unfinalized`. Setting it pins one level across the pool and makes finality classification track it. | | `networkDefaults.svm.commitment` | string | `""` | Inherited by any network whose own `svm.commitment` is empty. The normal place to set it. | `svm.commitment` is deliberately **not** defaulted by `SetDefaults` — the injection hook is a no-op when it is empty, which is the correct behavior when an operator has not opted in. ### Worked examples **1. Pin `finalized` for a settlement-grade reader.** Every upstream evaluates at the rooted head, and the two slot-pinned reads become permanently cacheable: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: svm svm: cluster: mainnet-beta # finalized: every upstream evaluates at its rooted head. getBlock and # getTransaction become cache-finalized; state reads stay realtime # because the rooted head still moves every ~400ms. commitment: finalized ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta", // finalized: every upstream evaluates at its rooted head. getBlock and // getTransaction become cache-finalized; state reads stay realtime // because the rooted head still moves every ~400ms. commitment: "finalized", }, }] ``` **2. Pin `processed` for a latency-sensitive frontend, and understand the clamp.** `processed` is the freshest level, but `getBlock`/`getTransaction`/`getBlocks`/`getBlocksWithLimit`/`getSignaturesForAddress` refuse it, so those five silently receive `confirmed` — which is what you want, and is why no `-32602` appears: **Config path:** `projects[].networkDefaults.svm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: svm: # processed = freshest. The five atLeastConfirmed methods are clamped to # confirmed automatically rather than erroring with -32602. commitment: processed networks: - architecture: svm svm: { cluster: mainnet-beta } ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { svm: { // processed = freshest. The five atLeastConfirmed methods are clamped to // confirmed automatically rather than erroring with -32602. commitment: "processed", }, }, networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta" } }], }] ``` **3. Consensus on finalized reads only.** A consensus policy that matches `finalized` activates for exactly the requests where honest nodes must agree. Combine with a pinned commitment so all upstreams are answering the same question: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: svm svm: cluster: mainnet-beta commitment: finalized failsafe: - matchMethod: "getBlock|getTransaction" # Only the slot-pinned reads at finalized commitment are classified # finalized, so this policy activates for exactly those. matchFinality: ["finalized"] consensus: maxParticipants: 3 agreementThreshold: 2 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta", commitment: "finalized" }, failsafe: [{ matchMethod: "getBlock|getTransaction", // Only the slot-pinned reads at finalized commitment are classified // finalized, so this policy activates for exactly those. matchFinality: ["finalized"], consensus: { maxParticipants: 3, agreementThreshold: 2 }, }], }] ``` ### Request/response behavior - Injection **mutates outgoing params** and invalidates the memoized cache hash. The request your upstream receives may carry a `commitment` your client did not send. - Injection is **non-short-circuiting** — it never answers a request itself, only rewrites params. - An explicit caller `commitment` is passed through byte-for-byte, including a level the method will reject. - `context.slot` is harvested opportunistically from responses whose result shape is Solana's `RpcResponse` envelope, and is routed by the request's **effective** commitment: a finalized-commitment response feeds the finalized slot view as well as the latest view; weaker commitments feed only the latest view. See [slot tracking](/reference/svm/slot-tracking.llms.txt). ### Best practices - **Set `commitment` on `networkDefaults.svm`, not per network.** Cluster is network identity and must stay per-network; commitment is policy and is almost always uniform. - **Pin a commitment before enabling a consensus policy.** Without it, upstreams answer at their own defaults and consensus disputes are guaranteed rather than diagnostic. - **Prefer `confirmed` as the general default.** `finalized` costs ~13 s of head lag; `processed` can sit on a fork that is later abandoned. `confirmed` is the level most Solana applications already assume. - **Do not reach for `commitment: finalized` as a caching lever.** It promotes only `getBlock` and `getTransaction`. State reads stay realtime whatever you set, by design. - **Leave `commitment` unset only if you deliberately want each upstream's own default.** That is a valid choice for a single-upstream deployment and a liability for a pool. ### Edge cases & gotchas 1. **`svm.commitment` has no default.** An SVM network with no `commitment` injects nothing, and two upstreams can return different data for one request. This is the documented behavior, not an oversight — but it is rarely what an operator wants for a multi-upstream pool. 2. **`processed` is silently clamped to `confirmed` for five methods.** No warning is logged. If you need to know which level actually reached the upstream, that is the value the cache key and finality classification used. 3. **A caller's explicit `processed` on `getBlock` is *not* clamped** and will surface the upstream's `-32602`. That asymmetry is deliberate: eRPC will not hand back data the client did not ask for. 4. **The legacy encoding-string form blocks injection.** `getBlock(slot, "base64")` and `getTransaction(sig, "json")` put a string where the config object would go; injection skips rather than corrupt the shape, and the response is classified `unfinalized` rather than trusting the network default. 5. **The options-index table is hand-maintained.** New Solana or vendor-specific methods are not commitment-injected until added. Safe by default (unknown methods are skipped) but requires upkeep. 6. **`getInflationRate` takes no params** and is excluded — injecting an options object into it produced `-32602` before the table was made shape-aware. 7. **`minContextSlot` does not bound history.** Reading it as a "from this slot onward" filter is the common mistake; it only gates whether a node is fresh enough to answer at all. 8. **No commitment-downgrade detection.** If a non-conforming upstream silently answers at a weaker commitment than requested, eRPC trusts the request's commitment for finality classification — it does not re-derive finality from the response. ### Observability Commitment injection emits no metrics of its own — it is a params rewrite. Its effects are visible through: | Signal | Where | |---|---| | `finality` label on `erpc_network_*` / `erpc_upstream_*` / `erpc_cache_*` metrics | Reflects `GetFinality`, so a mispinned commitment shows up as an unexpected finality mix | | `erpc_upstream_request_skipped_total` | Includes upstreams skipped by the `minContextSlot` pre-filter | | `-32016` in `erpc_upstream_request_errors_total` | `MinContextSlotNotReached` — the pre-filter did not have fresh enough state to avoid the round-trip | ### Source code entry points - [`architecture/svm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/hooks.go) — `resolveCommitment`, `effectiveCommitment`, `FailsafeCommitment` (the level failsafe `matchCommitment` compares), `solanaDefaultCommitment`, `commitmentOptionsIndex`, `atLeastConfirmedMethods`, `clampCommitmentForMethod`, `writeCommitmentField`, `networkPreForward_injectCommitment`, `networkPreForward_injectWriteCommitment`, `projectPreForward_getGenesisHash`. - [`architecture/svm/finality.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/finality.go) — `GetFinality`, `IsFinalizedCommitment`, and the moving-head rationale. - [`architecture/svm/slot_lag.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/slot_lag.go) — `FilterByMinContextSlot`, `MinContextSlotOf`, `isAtOrAheadOfSlot`. - [`common/config.go — SvmNetworkConfig.Commitment`](https://github.com/erpc/erpc/blob/main/common/config.go#L2336-L2342) ### Related pages - [SVM slot tracking & health](/reference/svm/slot-tracking.llms.txt) — the state poller, `getSlot` correction, ingestion lag, and cordoning. - [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt) — the finality classification tables and cache-key derivation. - [Networks](/config/projects/networks.llms.txt) — declaring an SVM network and the full `svm.*` schema. - [Consensus](/config/failsafe/consensus.llms.txt) — how `matchFinality` and `matchCommitment` gate a consensus policy. - [Matchers](/config/matcher.llms.txt) — `matchCommitment` semantics vs `matchFinality`. - [Error taxonomy](/reference/errors.llms.txt#svm-solana-error-contract) — `-32016` and the rest of the SVM error contract. --- --- # Slot tracking & health > Source: https://docs.erpc.cloud/reference/svm/slot-tracking > eRPC polls every Solana upstream for its slot and ingestion watermark — then corrects backward-moving getSlot answers, short-circuits unindexed getBlock calls, and pulls silently-stale or silent nodes out of routing before they serve you old state. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Slot tracking & health A Solana node can keep answering slot probes while quietly serving state hundreds of slots old — it is receiving block shreds from the network but failing to replay them. eRPC catches that by tracking two independent signals per upstream: how far the node has *replayed* (its processed and finalized slots) and how far it has *ingested* (its blockstore watermark). The gap between them is the silent-stale detector. Separately, transport silence on those same probes (after two consecutive all-dead polls) cordons a node that is not answering at all. **What you get** - Per-upstream processed and finalized slot views, converged across pods via shared counters - Ingestion-lag detection that catches nodes answering slot probes while serving stale reads - Probe-derived liveness: two consecutive all-silent polls cordon a dead upstream (RPC errors still count as alive) - Edge-triggered cordoning: an unhealthy upstream leaves routing, and rejoins on recovery, without gauge churn - `getSlot` answers that never move backwards through a cache window — corrected per commitment, never past the tip the caller asked for - Traffic-gated polling that halves background quota burn on busy networks - Opt-in `skipProcessedSlotProbe` for ~1-slot-finality chains (Alpenglow) ## Quick taste Illustrative, not a tuned production config — widen the poll gate on a rate-limited vendor: **Config path:** `projects[].networks[].svm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: svm svm: cluster: mainnet-beta # default 400ms (one slot). Raise it on metered vendors — the ticker # stays at one slot, this gates the actual fan-out. statePollerDebounce: 2s ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta", // default 400ms (one slot). Raise it on metered vendors — the ticker // stays at one slot, this gates the actual fan-out. statePollerDebounce: "2s", }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: reduce background poll quota on a metered Solana vendor** ```text My Helius plan is being consumed by eRPC's background Solana polling. Explain exactly which RPC calls the SVM state poller makes per tick, then raise statePollerDebounce appropriately in my eRPC config and tell me what freshness I trade away. Read the full reference first: https://docs.erpc.cloud/reference/svm/slot-tracking.llms.txt ``` **Prompt Example #2: diagnose a Solana upstream that keeps getting cordoned** ```text One of my eRPC Solana upstreams keeps disappearing from routing — erpc_upstream_cordoned goes to 1 and back. Explain both conditions that cordon an SVM upstream, which log line names the reason, and what I should check on the node. Reference: https://docs.erpc.cloud/reference/svm/slot-tracking.llms.txt ``` **Prompt Example #3: stop getting -32004 on getBlock at the tip** ```text Clients call getSlot then immediately getBlock on that slot through eRPC and get -32004 BlockNotAvailable. Explain eRPC's getSlot correction and the getBlock availability guard, and tell me whether enforceBlockAvailability or statePollerDebounce is the knob to change. Reference: https://docs.erpc.cloud/reference/svm/slot-tracking.llms.txt ``` **Prompt Example #4: disable the block-availability guard on a deployment without shred tracking** ```text My Solana provider does not expose getMaxShredInsertSlot, and I want to turn off eRPC's getBlock availability guard for that network. Set enforceBlockAvailability correctly in my eRPC config — including at networkDefaults level — and explain what behavior I lose. Reference: https://docs.erpc.cloud/reference/svm/slot-tracking.llms.txt ``` --- ### Slot tracking & health — full agent reference ### How it works **Slot is not block height.** These are two different counters on Solana and the distinction drives several behaviors on this page. Every slot is a ~400 ms leader window; a leader that fails to produce advances the *slot* but not the *block height*. So `getBlockHeight` trails `getSlot` by exactly the number of skipped slots since genesis, and the two can never be substituted for one another. **What the poller tracks.** Four values per upstream: | Accessor | Source call | Meaning | |---|---|---| | `LatestSlot()` | `getSlot {"commitment":"processed"}` | The processed tip — the node's replay frontier | | `FinalizedSlot()` | `getSlot {"commitment":"finalized"}` | The latest rooted slot | | `ShredInsertSlot()` | `getMaxShredInsertSlot` | Blockstore-ingestion watermark | | `MaxShredInsertSlotLag()` | derived | `maxShredInsertSlot − processedSlot` | | `FirstAvailableSlot()` | `getBlocksWithLimit(0, 1)` | The oldest block the node serves, from the same storage `getBlock` reads (long-term storage included). Probed for every upstream. `known=false` until observed; unknown is **not** slot 0. | **There is deliberately no confirmed tip.** Nothing polls `getSlot {"commitment":"confirmed"}`, and that absence is load-bearing for the `getSlot` correction below. **Tick cadence and the debounce gate.** The ticker fires at a fixed `DefaultPollInterval` of 400 ms — one Solana slot. The effective debounce — `upstreams[*].svm.statePollerDebounce` when non-zero, else `networks[*].svm.statePollerDebounce` (default 400 ms) — is a **gate on the fan-out**, not the ticker period: a tick that arrives inside the debounce window returns immediately without issuing any RPC. The ticker is deliberately *not* driven by the gate value, because a ticker firing at exactly the gate interval skips every other tick. The per-upstream override is a hard short-circuit for that upstream's poller only. `tipStalenessMargin` (the `getBlock` guard) still reads the *network* debounce; the indexed frontier itself is a MAX over shred-insert snapshots, so one slow peer next to a fresh tip peer does not shrink the guard — it only bites when every poller feeding the frontier is slower than the network gate (e.g. the override landed via `upstreamDefaults.svm` onto tip peers too). **Per-tick fan-out.** Up to three concurrent calls: `getSlot(processed)`, `getSlot(finalized)`, `getMaxShredInsertSlot`. Each runs in its own panic-recovered goroutine so a single bad response cannot take down the process. There is no dedicated `getHealth` probe — liveness is derived from these same outcomes (see below). Every upstream also refreshes its floor with `getBlocksWithLimit(0, 1)` after the fan-out joins: at most once per 30 s, shared across eRPC instances. **Traffic-gated polling.** Solana responses whose result is the `RpcResponse` envelope carry a `context.slot` telling eRPC which slot the node was at when it answered. That observation is harvested on the response path and fed into the poller, routed by the request's **effective commitment**: a finalized-commitment response feeds the finalized view *and* the latest view (a finalized slot is always a valid lower bound for the latest view); weaker commitments feed only the latest view. When both slot views are traffic-fresh within the debounce window, the tick **skips its two `getSlot` calls** — bounded at 4 consecutive skips, so live traffic can never fully starve independent verification. `getMaxShredInsertSlot` always runs. On busy networks this roughly halves background poll quota on metered vendors. The envelope check runs *first*, before the response body is touched: every other method returns a bare value, so peeking for `context.slot` there is a guaranteed miss — and not a free one, since the walk traverses the whole result and full `getBlock` responses reach multiple megabytes. **Cross-pod convergence.** Both slot views live in shared counters keyed by the unique upstream key, so horizontal replicas converge without each pod paying its own poll cost. The tracker is fed only from the counter's `OnValue` callback — it fires once per *accepted* value whatever the source (this poller's fetch, a live-traffic suggestion, or cross-instance propagation) and stays silent when the counter rejects a lower slot, so the tracker can never be fed a slot the counter itself refused. Rollback tolerance is `DefaultToleratedSlotRollback = 1024`; a backwards jump beyond that is recorded as a large-rollback event — the signature of a load balancer swapping in a node on another fork, a snapshot restore, or a cross-wired endpoint. **Ingestion lag is the silent-stale detector.** `getMaxShredInsertSlot` is the blockstore-ingestion watermark and is structurally **at or ahead of** the replayed (processed) slot, so: ``` ingestionLag = maxShredInsertSlot − processedSlot ``` That subtraction *is* the detector: shreds keep arriving while replay stalls, so the watermark runs away from the processed slot while the node still answers its state probes. Subtracting the other way would invert it — a degraded node would yield a negative number that clamps to zero and the detector could never fire. A negative result is treated as sampling skew (a later traffic suggestion raised the processed slot, or a shared-state peer wrote a higher slot for this upstream) and reported as **zero lag**, not as ingestion lag. **Health verdict.** `IsHealthy()` requires **both** signals: 1. probe-derived liveness — not transport-dead for `deadPollsBeforeUnhealthy` (2) consecutive polls, **and** 2. `MaxShredInsertSlotLag() <= MaxShredInsertSlotLagThreshold` (100 slots, ≈40 s) A poll is **alive** when any dispatched probe answers (a JSON-RPC error, vendor 429, or 5xx all count — the endpoint responded) or when the traffic gate skipped the `getSlot` calls. It is **dead** only on transport silence (transport failure, timeout, canceled, or a bare poll-context deadline from retry backoff). Probes rejected locally before dispatch (circuit breaker open, the upstream's own rate-limit budget) are **no-signal** — they move the dead counter neither way. A skipped `getSlot(processed)` (when `skipProcessedSlotProbe: true`) is also no-signal, so it cannot invent a dead streak. The shred-lag threshold is a compile-time constant in `common/architecture_svm.go`, **not** a config field. Do not confuse it with `svm.maxFinalizedSlotLag`, which is a separate consensus-scoped config key that happens to share the same default of 100. **Cordoning takes the verdict to routing.** A health verdict nobody routes on is not a defense, so every tick publishes it. `Cordon("*", reason)` removes the upstream from selection — the default selection policy runs `.removeCordoned()`, so a cordoned upstream is dropped for every request until it recovers. Cordoning is **edge-triggered**: cordon and uncordon fire only on a transition, never once per tick. Re-cordoning every 400 ms would restamp the reason (spawning a fresh `erpc_upstream_cordoned` gauge series per tick and resetting the cordon-duration observation), and the flag also means a recovering poller lifts only **its own** cordon, never an operator's manual one. Exact reason strings: | Condition | Reason | |---|---| | 2 consecutive all-dead polls | `svm state poller: upstream not answering state probes (N consecutive dead polls)` | | lag over threshold, probes answering | `svm state poller: shred-insert lag N slots exceeds threshold 100 (node ingests shreds but does not replay them)` | | recovery | `svm state poller: probes answering and shred-insert lag back within threshold` | **A cold poller cannot cordon.** `healthy` starts `true` and `maxShredInsertSlotLag` stays `0` until a real `getMaxShredInsertSlot` sample lands, so "not yet observed" reads as healthy. Unknown is not unhealthy. **Recovery is observable because polling continues while cordoned.** `Upstream.Forward` does not consult cordon state — only the selection policy does — so the poller keeps polling a cordoned upstream and can therefore see it come back. **`getSlot` correction.** A post-forward hook enforces the highest slot this instance already knows for the request's commitment, so clients never observe the slot number moving backwards through a cache window. It applies to cache hits too (the corrected response preserves its from-cache marker). The floor is chosen **per commitment**, and never exceeds the tip for the commitment the caller actually asked for: | Effective commitment | Floor | |---|---| | `finalized` | `min(finalizedTip, indexedTip)`; when the indexed tip is unknown, `finalizedTip − 32`. **Clamped from both directions** — stale values are raised, values above the floor are capped down. `finalizedTip` here is the **majority** tip, because this value is advertised to clients and a lone rogue upstream must not inflate it. | | `confirmed` | **Passed through uncorrected.** | | `processed` | The processed tip (`LatestSlot()`). Stale values are raised only; a value above the tip is left alone. | "Effective" includes the level the node applies when the request pins none: Solana's documented default is `finalized`, so an **unset** commitment takes the `finalized` row, not the `processed` one. Flooring an unpinned `getSlot` at the processed tip advertised a slot ~60 above the finalized root — exactly the band the `getBlock` guard below rejects, so eRPC handed clients a head it then refused to serve. `confirmed` is passed through because **no confirmed tip is tracked**. The poller's `LatestSlot` is the *processed* slot, and processed runs ahead of confirmed — flooring a confirmed answer with it would hand back a slot that is not confirmed and may never be, since its fork can be abandoned. That is a commitment-contract violation, not a freshness improvement, so eRPC declines to fabricate a confirmed tip. The `finalized` branch caps downward for a different reason: `getSlot(finalized)` reflects the **consensus** layer, but `getBlock` on a just-finalized slot returns `-32004` until the provider's indexer writes it. Using `min(finalizedTip, indexedTip)` means neither a slow indexer nor a fast one can push callers into the un-indexed window. When the indexed tip is unavailable — cold poller, or a vendor that does not implement `getMaxShredInsertSlot` — the fallback is a fixed 32-slot lag. **`getBlockHeight` is never corrected.** Only `getSlot` is routed to the corrector. Block height is a different counter that trails the slot number by every skipped slot, so rewriting a `getBlockHeight` answer to a slot value would be straightforwardly wrong. It is passed through untouched. **`getBlock` availability guard.** An upstream returns `-32004` both for a slot above its `maxShredInsertSlot` and for a slot above its own finalized root, so hitting all upstreams only to collect N identical `-32004`s wastes quota and delays the client's retry. When the requested slot is above what the pool can serve, `getBlock`/`getConfirmedBlock` are short-circuited with `ErrEndpointMissingData` before any upstream call, and the client gets agave's own answer: `-32004` `Block not available for slot N`. The short-circuit runs before the failsafe executor, so the network's retry and hedge do not run on it: the client gets the error at once, and the client's own retry reaches the slot once the pool has indexed it. The bound is **commitment-dependent**, on the same effective commitment as the `getSlot` correction: | Effective commitment | Bound | |---|---| | `finalized` (including unpinned) | `min(maxFinalizedRoot, indexedFrontier)` | | `confirmed`, `processed` | `indexedFrontier` alone — slots between the finalized and indexed frontiers *are* held at those levels | Both inputs are **MAX across upstreams**, never the majority tip: this is a rejection gate, so its only job is to avoid short-circuiting a slot that *some* upstream can serve, and the most-advanced upstream sets the bound. With roots skewed `1000/1000/1100`, the majority tip is `1000` and bounding by it would null out ~100 slots the third upstream is already holding. The advertising side above uses the majority tip, so every slot eRPC advertises is at or below the bound it serves. The guard allows a **staleness margin** above the frontier snapshot, because the snapshot refreshes at most once per debounce while the chain advances one slot per ~400 ms: ``` margin ≈ statePollerDebounce / 400ms + 2 ``` The `+2` covers tick scheduling and the cross-source skew between `getSlot` (served by the most-ahead upstream) and the MAX-over-snapshots frontier. Default debounce (400 ms) gives a margin of 3; a 2 s debounce gives 7. Within the margin the request forwards — the pool almost certainly indexed the slot since the last poll. Beyond it the guard still short-circuits genuinely-future slots. The guard **fails open** whenever the tip it needs is unknown — an indexed frontier of `0` forwards every slot, and a finalized root of `0` falls back to the indexed bound rather than collapsing to slot `0`. Absence of tracking is not evidence of unavailability, so a cold poller or a vendor without `getMaxShredInsertSlot` must not cost requests every upstream could serve. **`getBlockTime` and `minContextSlot` guards.** The same check, with the same tip per commitment and the same fail-open, answers two more reads locally, before any upstream call. Their margin is wider than the `getBlock` one: the slot must be more than **128 slots** (`maxRetryableSlotDistance`, the same slot count that separates a retryable miss from a real one for declared windows) beyond the bound: | Read | Bound | Local answer (agave's own error) | |---|---|---| | `getBlockTime(slot)` | `indexedFrontier` — agave serves any frozen bank, so the method has no finalized bound | `-32004` `Block not available for slot N` (`ErrEndpointMissingData`) | | Any method whose config object carries `minContextSlot` | The bound of the request's effective commitment (table above) | `-32016` `Minimum context slot has not been reached`, `data: {"contextSlot": }` (`ErrEndpointServerSideException`) | agave checks `minContextSlot` against its bank before it reads anything, so a slot far above every upstream's bank fails the same way on each one, and every failover, retry and hedge repeats it. The local `-32016` carries agave's meaning only: `contextSlot` is the pool's bound, so a client backs off and retries as it does for a node's answer. The local answer is final for the request: the guard runs before the failsafe executor, so retry and hedge never run on it. The client's next request is checked again against fresh tips. The getBlock staleness margin would be too tight here. A client that takes `minContextSlot` from a fresher node often asks for a slot a few slots past the pool's last snapshot, and the network's retry waits usually reach it: against live upstreams, slots 2-10 past the freshest processed slot succeeded on every run after about 0.5-2 s. A final local error at that distance would turn those successes into failures. So within 128 slots of the bound, and with a cold poller, the request forwards as it does without the guard. **Declared slot windows.** Optional `upstreams[*].svm.blockAvailability.{lower,upper}` (`exactSlot` / `latestSlotMinus` / `firstAvailableSlotPlus`) is an operator declaration of the slots an upstream may serve, gated by `svm.enforceBlockAvailability`. An upstream whose declared window excludes the slot a request names is skipped (lower: `-32001`, permanent for the request; upper: `-32004`). The upper bound is checked against the **end** of a `getBlocks` / `getBlocksWithLimit` range, not only its start. Without a declared window every upstream is tried. **Malformed slots are answered locally.** agave decodes a slot as a u64, so a slot param (`params[0]` of `getBlock`, `getBlockTime`, `getBlocks` and the other slot-first methods) or a `minContextSlot` that is a string, a fraction or exponent form, a negative integer, or an integer above `18446744073709551615` fails on every node with `-32602` and serde's message, for example ``Invalid params: invalid type: floating point `1.5`, expected u64.`` eRPC gives the same answer before any upstream call. `minContextSlot: null` is valid and forwards. Slots are read as u64, so a local `-32004` names the slot the client sent, up to `18446744073709551615`. **The floor is the oldest block the upstream serves, not `getFirstAvailableBlock`.** `getFirstAvailableBlock` reports only the local ledger, so a node backed by long-term storage reports a floor far above slots it serves (Alchemy devnet: ~509M while serving 116M+). eRPC instead probes `getBlocksWithLimit(0, 1)`, which agave answers from the same storage `getBlock` reads; an empty answer is no observation. There is no pool-level `-32009` short-circuit. The floor is probed for every upstream. It skips nothing by itself: it anchors a declared `firstAvailableSlotPlus` bound (the SVM analogue of EVM's `earliestBlockPlus`) and orders the history sweep below. A bound that does not need the floor (`exactSlot`, `latestSlotMinus`) overrides whatever the vendor reports; `exactSlot: 0` declares full history. A cold poller, an unobserved floor, or a computed min>max range fail-open. `firstAvailableSlotPlus` with an unobserved floor is unbounded (unlike EVM's `earliestBlockPlus`, which computes `0+N` before detection). The floor is probed every `30s` until observed, then frozen; a `firstAvailableSlotPlus` bound's `updateRate` re-probes it on that cadence, like EVM's `earliestBlockPlus`. **Consensus slot-lag pre-filter.** For a request whose resolved finality is `Finalized` **and** with a consensus policy active, upstreams whose `FinalizedSlot` trails the reference by more than `svm.maxFinalizedSlotLag` are pruned before consensus runs — the same query sent to a stale upstream and a current one returns different answers for data the caller has been promised is immutable. The reference slot is **not** the raw pool max, which is poisonable: a single upstream reporting a wildly inflated finalized slot would become the reference, every honest upstream would trail it by more than the lag, and the filter could shrink the pool to just the liar. Instead, when the leader outruns the runner-up by more than `maxFinalizedSlotLag`, the **runner-up** becomes the reference — the leader still passes (the filter only drops trailers) but can no longer drag the bar above the honest pack. This defends a single liar; colluding upstreams would need a majority-based baseline. The filter is defensive throughout: an upstream with no state poller is **included** (bootstrap has not finished; excluding it would break forwarding for newly-registered upstreams), and an upstream whose poller reports slot `0` is **included** (the poller has not seen a successful tick, so we cannot tell trailing from not-yet-woken). When `maxFinalizedSlotLag` is `0` or negative, filtering is disabled entirely. ### Config schema | Field | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[*].svm.statePollerDebounce` | Duration | `400ms` (one slot) | Pool/network default gate between poll fan-outs when an upstream does not override. A **gate**, not the ticker period — the ticker stays at 400 ms. Raising it widens the `getBlock` guard's staleness margin proportionally. | | `upstreams[*].svm.statePollerDebounce` | Duration | `0` / omit → inherit network | Hard per-upstream override for that upstream's poll fan-out gate only (same precedence as `upstreams[*].evm.statePollerDebounce`). Non-zero short-circuits the network debounce for this upstream; zero/omit inherits. Inherited from `upstreamDefaults.svm` when the upstream omits the field — do **not** put a raised value there unless every upstream should poll slowly (that also keeps the `getBlock` margin at the network value while every shred snapshot ages). Does **not** disable the poller — `0` means inherit, never "off". `tipStalenessMargin` still follows the *network* debounce. The upstream still votes in the majority served tip (`SvmHighestLatestSlot` / `SvmHighestFinalizedSlot`); `blockAvailability` tip-exclusion affects routing only. Dead-detection (`deadPollsBeforeUnhealthy = 2`) counts polls, so a 5s gate cordons after ~10s instead of ~0.8s. | | `networks[*].svm.skipProcessedSlotProbe` | `bool` | `false` (poll) | When `true`, skips `getSlot(processed)` and lets the finalized probe double-feed `LatestSlot`. **Only safe on ~1-slot-finality chains** (Alpenglow); on a ~32-slot-gap chain (TowerBFT) it shifts the shred-lag cordon and availability windows by that gap. Propagated from `networkDefaults.svm` when set `true`. | | `networks[*].svm.maxFinalizedSlotLag` | `*int64` | `100` slots (≈40 s) | Consensus-scoped only: applied when a consensus policy is active **and** the request's resolved finality is `Finalized`. **Tri-state** — omit for the 100-slot default, `0` to **disable** the filter entirely, `>0` for that value. | | `networks[*].svm.enforceBlockAvailability` | `*bool` | `true` | Gates the `getBlock`/`getConfirmedBlock`, `getBlockTime` and `minContextSlot` availability guards **and** declared `svm.blockAvailability` windows. Set `false` when shred-insert tracking is unavailable or unreliable on a deployment. | `maxFinalizedSlotLag` is a pointer precisely so an explicit `0` is distinguishable from "unset": a plain integer would collapse those two cases and make the documented disable switch unreachable. The `100` default is materialized in exactly one place (`SetDefaults`) so every reader downstream can simply test `lag != nil && *lag > 0`. `enforceBlockAvailability` is materialized at read time rather than in `SetDefaults` — `SvmEnforceBlockAvailability()` maps `nil` to `true`. Both pointer fields survive `networkDefaults.svm` inheritance: an explicit `false` or `0` set in `networkDefaults` is copied through, because the merge tests for `nil` rather than for the zero value. ### Worked examples **1. Cut background poll cost on a metered vendor.** Four calls per upstream every 400 ms is ~10 requests/second/upstream at default settings. A 2 s gate cuts that by 5× at the cost of a slightly wider `getBlock` guard margin (3 → 7 slots): **Config path:** `projects[].networkDefaults.svm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: svm: # Ticker stays at 400ms; this gates the fan-out. Under live traffic the # poller additionally skips its two getSlot calls when context.slot # observations are already fresh (bounded at 4 consecutive skips). statePollerDebounce: 2s networks: - architecture: svm svm: { cluster: mainnet-beta } ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { svm: { // Ticker stays at 400ms; this gates the fan-out. Under live traffic the // poller additionally skips its two getSlot calls when context.slot // observations are already fresh (bounded at 4 consecutive skips). statePollerDebounce: "2s", }, }, networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta" } }], }] ``` **2. Disable the consensus slot-lag filter.** Some fleets want every upstream to vote regardless of lag — for example when the pool is deliberately heterogeneous and the consensus threshold already tolerates a trailing minority. An explicit `0` is the documented disable switch: **Config path:** `projects[].networks[].svm` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: svm svm: cluster: mainnet-beta commitment: finalized # 0 = DISABLED (not "zero slots of tolerance"). Omitting the key entirely # would take the 100-slot default instead. maxFinalizedSlotLag: 0 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta", commitment: "finalized", // 0 = DISABLED (not "zero slots of tolerance"). Omitting the key entirely // would take the 100-slot default instead. maxFinalizedSlotLag: 0, }, }] ``` **3. Raise debounce on an archive-only upstream without slowing tip peers.** Tip-excluded archive vendors still pay the full poll fan-out at the network debounce unless overridden. Set a longer gate on that upstream alone; siblings that omit the field keep the network value. Prefer this over `upstreamDefaults.svm.statePollerDebounce` so tip peers stay tight. Note: `blockAvailability` tip-exclusion does **not** remove the archive from the majority served-tip ballot — the served tip needs `floor(N/2)+1` votes, so whenever slow upstreams are at least half of the SVM pollers (e.g. one tip + one archive, or two tip + two archives) a 5s archive can advertise a ~12-slot-stale head. Keep fresh tip peers a strict majority of the pollers (or accept the lag). The `getBlock` guard margin stays on the network debounce; the indexed frontier is MAX so one slow peer is fine: **Config path:** `projects[].upstreams[]` **YAML — `erpc.yaml`:** ```yaml upstreams: - id: tip-internal endpoint: http://solana-internal:8899 svm: cluster: mainnet-beta # inherits networks[*].svm.statePollerDebounce - id: archive-vendor endpoint: https://archive.example.com svm: cluster: mainnet-beta # Hard override — this upstream's poller only; tip peers stay tight. statePollerDebounce: 5s blockAvailability: lower: firstAvailableSlotPlus: 0 upper: latestSlotMinus: 340000 ``` **TypeScript — `erpc.ts`:** ```typescript upstreams: [ { id: "tip-internal", endpoint: "http://solana-internal:8899", svm: { cluster: "mainnet-beta" }, }, { id: "archive-vendor", endpoint: "https://archive.example.com", svm: { cluster: "mainnet-beta", // Hard override — this upstream's poller only; tip peers stay tight. statePollerDebounce: "5s", blockAvailability: { lower: { firstAvailableSlotPlus: 0 }, upper: { latestSlotMinus: 340000 }, }, }, }, ] ``` **4. Turn off the block-availability guard for a vendor without shred tracking.** The guard already fails open when the frontier is unknown, so this is only needed when tracking exists but is unreliable. Setting it in `networkDefaults` works — an explicit `false` survives the merge: **Config path:** `projects[].networkDefaults.svm` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networkDefaults: svm: # Explicit false is preserved through networkDefaults inheritance. # Cost: getBlock for a not-yet-indexed slot fans out to every upstream # and collects N identical -32004s before the retry fires. enforceBlockAvailability: false networks: - architecture: svm svm: { cluster: mainnet-beta } ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networkDefaults: { svm: { // Explicit false is preserved through networkDefaults inheritance. // Cost: getBlock for a not-yet-indexed slot fans out to every upstream // and collects N identical -32004s before the retry fires. enforceBlockAvailability: false, }, }, networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta" } }], }] ``` **5. Tighten the consensus filter for a settlement reader.** 100 slots is ~40 s. A reader that must not vote across a 40-second spread can tighten it to a few slots — the defensive fallbacks keep the pool from emptying: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml networks: - architecture: svm svm: cluster: mainnet-beta commitment: finalized # ~2s of tolerance instead of ~40s. Upstreams with no poller yet, or a # zero slot, are still INCLUDED — unknown state never excludes. maxFinalizedSlotLag: 5 failsafe: - matchMethod: "getBlock|getTransaction" matchFinality: ["finalized"] consensus: maxParticipants: 3 agreementThreshold: 2 ``` **TypeScript — `erpc.ts`:** ```typescript networks: [{ architecture: "svm", svm: { cluster: "mainnet-beta", commitment: "finalized", // ~2s of tolerance instead of ~40s. Upstreams with no poller yet, or a // zero slot, are still INCLUDED — unknown state never excludes. maxFinalizedSlotLag: 5, }, failsafe: [{ matchMethod: "getBlock|getTransaction", matchFinality: ["finalized"], consensus: { maxParticipants: 3, agreementThreshold: 2 }, }], }] ``` ### Request/response behavior - **`getSlot` responses may be rewritten**, including on cache hits, to the highest slot known for the request's commitment. `confirmed` is exempt. - **`getBlockHeight` responses are never rewritten.** - **`getBlock` / `getConfirmedBlock` may be answered without any upstream call** when the requested slot is beyond the indexed frontier plus margin. The client sees the SVM missing-data contract (`-32004` family) and eRPC's indexing-lag retry fires immediately. - **Cordoned upstreams still receive poller traffic**, so recovery is detected; they receive no client traffic. - **`getGenesisHash` never reaches an upstream** — it is answered from the immutable genesis table. - Unlike EVM's `eth_blockNumber`, `getSlot` returns a bare integer (not hex) and the correction is unconditional — there is no `enforceHighestBlock` directive gate. ### Best practices - **Leave the network `statePollerDebounce` at its default unless a vendor bill says otherwise.** 400 ms is one slot; polling faster buys no fresher data, polling slower widens the `getBlock` guard margin. - **Raise debounce on archive-only upstreams via `upstreams[*].svm.statePollerDebounce`, not the network gate and not `upstreamDefaults.svm`**, so tip peers keep a tighter poll. Keep enough tip voters that majority tip stays on the fresh peers. - **When you do raise the network `statePollerDebounce`, expect the guard margin to widen with it.** That is the intended trade, not a bug: the frontier snapshot is staler, so the guard must be more permissive to avoid false rejections at the tip. - **Prefer providers that implement `getMaxShredInsertSlot`.** Without it you lose the silent-stale detector, and the `getSlot(finalized)` correction falls back to a fixed 32-slot lag instead of the real indexed tip. - **Alert on `erpc_upstream_cordoned` for SVM upstreams.** The two cordon conditions are both genuine node faults, and the reason label tells you which. - **Do not tune `maxFinalizedSlotLag` expecting it to affect non-consensus routing.** It is scoped to consensus-eligible finalized requests. Score-based selection already penalizes lagging upstreams on every path. - **Read `erpc_upstream_latest_block_number` on an SVM network as a slot, not a block height.** The metric names are architecture-neutral; the values are slots. ### Edge cases & gotchas 1. **`svm.maxFinalizedSlotLag: 0` disables the filter — it does not mean "zero tolerance".** Omitting the key gives the 100-slot default; `0` turns filtering off entirely. 2. **`MaxShredInsertSlotLagThreshold` (100) is not configurable.** It is a compile-time constant governing per-upstream health, distinct from the `maxFinalizedSlotLag` config key despite the shared default value. 3. **`statePollerDebounce` does not change the ticker period.** The ticker is pinned at 400 ms; the setting gates the fan-out. Setting it below 400 ms therefore has no effect. Per-upstream `0` / omit inherits the network gate — it does **not** disable the poller (disabling the SVM state poller is out of scope). 4. **Per-upstream debounce does not change `tipStalenessMargin`.** The margin still reads `networks[*].svm.statePollerDebounce`. The indexed frontier is MAX across shred snapshots, so one slow peer next to a fresh tip peer does not false-reject head `getBlock`s. It *does* when every poller feeding the frontier is slower than the network gate (wholesale `upstreamDefaults.svm.statePollerDebounce`, or the only tip peer is cold/cordoned). Separately: every poller still votes in the majority served tip — `blockAvailability` tip-exclusion is routing-only — so whenever slow pollers are ≥ half the pool (e.g. 1+1 or 2+2) the advertised head can follow them. 5. **There is no Prometheus metric for ingestion lag.** It is logged (`shredInsertSlotLag` on the cordon WARN) and it drives cordoning, but no gauge exposes it. Alert on `erpc_upstream_cordoned` and read the `reason` label. 6. **`getSlot` at `confirmed` is not corrected**, so a client polling `getSlot(confirmed)` across pods can still observe the value move backwards. Use `processed` or `finalized` if monotonicity matters more than the confirmed contract. 7. **A `finalized` `getSlot` answer can be *lower* than what the upstream returned.** That is the indexing-lag cap doing its job — the raw consensus tip is not yet fetchable via `getBlock`. 8. **The block-availability guard can still false-reject.** The margin is a heuristic over a snapshot; a caller far ahead of the pool's indexed frontier gets the missing-data path rather than a forward. Widen it by raising the network `statePollerDebounce`, or disable the guard. 9. **A cold poller neither cordons nor guards.** Both features treat unknown state as healthy/available, so a freshly-started instance behaves as if every upstream were fine until the first samples land. 10. **The poller does not lift a manual cordon.** The edge-trigger flag records that *this poller* cordoned; an operator's `Cordon` via the admin API is untouched by recovery. 11. **Large-rollback events are recorded, not acted on.** A backwards slot jump beyond 1024 is surfaced as `erpc_upstream_block_head_large_rollback`; it does not itself cordon. 12. **`context.slot` harvesting only covers envelope methods.** `getSlot`, `getBlock`, and `getTransaction` return bare values and contribute nothing to the traffic gate. `getProgramAccounts` is included because its envelope form is opt-in via `withContext: true` and the non-envelope miss is cheap. 13. **Declared `svm.blockAvailability` shares `enforceBlockAvailability`.** Setting the switch to `false` disables the declared window and the `getBlock` guard together. There is no second knob. 14. **The observed floor is never a default gate.** The floor is probed for every upstream, but no slot-named read is skipped on it unless the upstream declares `firstAvailableSlotPlus`. `exactSlot` / `latestSlotMinus` bounds ignore it entirely. 15. **`firstAvailableSlotPlus` with an unobserved floor is unbounded.** Unknown floor is not slot 0 — the request forwards until the poller has a real sample. 16. **History reads go deepest floor first, and continue only toward a deeper floor.** Within each failover tier, `getSignatureStatuses` and `getSignaturesForAddress` try upstreams with a known floor first, deepest first; unknown floors follow in score order. `getSignatureStatuses` with `searchTransactionHistory: true` that returns a `null`, and `getSignaturesForAddress` that returns fewer entries than its limit (`limit`, else Solana's default 1000), are also the normal end of history. So the 200 becomes MissingData, and the whole request goes to the next upstream, only when another selected upstream has a known floor strictly below this one. Ties, an unknown floor on either side, and a lone upstream serve the answer as is. Without `searchTransactionHistory: true` a null is a valid recent-status answer. A non-positive or non-integer `limit`, or a non-array result, fails open. There is no cross-upstream merge. 17. **A continued answer stays the fallback.** The verdict is permanent (`WithPermanentMissingData`), so a completed sweep is not re-swept after a block-time delay, and no hedge leg or retry asks the same upstream for the page again within the client request. If the deeper upstream fails, the client receives the shallower answer through last-valid-response. 18. **The history sweep does not run on consensus participant slots.** Consensus participants (`IsConsensusSlot`) vote on the bodies they returned; turning a legitimate short page into MissingData would make consensus agree on an error. 19. **History-sweep continuation is not wrong-empty misbehavior.** Sweep verdicts carry `historySweepContinuation` in error details; the network layer skips `MetricUpstreamWrongEmptyResponseTotal` and `RecordUpstreamMisbehavior` for them. 20. **An unknown cursor is the upstream's own verdict.** Some vendor proxies answer `getSignaturesForAddress` with `-32020` ("Transaction … not found") when the `before`/`until` signature is unknown to them; agave answers an empty page there. eRPC treats `-32020` on this method like a page that ends at the floor: it asks each other upstream once, never asks the rejecting upstream again in that request, and serves what the others answer. When every upstream rejects the cursor, the client receives the raw `-32020`. Source: [`architecture/svm/error_normalizer.go:L345-359`](https://github.com/erpc/erpc/blob/main/architecture/svm/error_normalizer.go#L345-L359) 21. **A far-future `minContextSlot` or `getBlockTime` slot never reaches an upstream.** More than 128 slots beyond the bound, eRPC answers `-32016` (with `data.contextSlot`) or `-32004` itself, once, with no retry or hedge. Within 128 slots the request forwards, even past the `getBlock` staleness margin. This is not eRPC's `Unauthorized` `-32016`: on SVM that number always means agave's `MinContextSlotNotReached`. `svm.enforceBlockAvailability: false` turns these guards off with the `getBlock` guard. 22. **A `getBlockTime` of `null` for a rooted slot is that provider's missing data.** At or below the provider's finalized slot, and from the slot the cluster records block times (`39824214` on mainnet-beta), agave answers a block it lacks with `-32007` or `-32009`, never `null`. eRPC turns such a `null` into a permanent `-32009` for that provider, asks each other provider once, and serves an error, never the `null`. Above the provider's finalized slot, and before block times were recorded, `null` keeps its normal path. ### Observability The SVM poller feeds the shared health tracker, so the standard upstream gauges populate for SVM networks. **The metric names say "block"; on an SVM network the values are slots.** | Metric | Type | SVM meaning | |---|---|---| | `erpc_upstream_latest_block_number` | gauge | The upstream's **processed slot** | | `erpc_upstream_finalized_block_number` | gauge | The upstream's **finalized (rooted) slot** | | `erpc_upstream_block_head_lag` | gauge | Processed slots behind the freshest upstream | | `erpc_upstream_finalization_lag` | gauge | Finalized slots behind the freshest upstream | | `erpc_upstream_block_head_large_rollback` | gauge | Non-zero = backwards slot jump > 1024; wrong-fork / snapshot-restore signal | | `erpc_upstream_cordoned` | gauge | `1` while cordoned; the `reason` label carries the poller's exact string | | `erpc_upstream_cordon_event_total` | counter | Increments only on a cordon **transition** (edge-triggered) | | `erpc_upstream_cordon_duration_seconds` | histogram | Observed on uncordon | | `erpc_upstream_stale_latest_block_total` | counter | A `getSlot` answer was corrected upward or capped | | `erpc_upstream_svm_first_available_slot` | gauge | The oldest block an upstream serves, from `getBlocksWithLimit(0, 1)`. Absent until first observed; set on any accepted value including cross-pod propagation | | `erpc_upstream_stale_lower_bound_total{confidence="configured"}` | counter | A slot-named read skipped an upstream below its declared `svm.blockAvailability.lower` | | `erpc_upstream_stale_upper_bound_total{confidence="configured"}` | counter | A slot-named read skipped an upstream above its declared `svm.blockAvailability.upper` | | `erpc_network_retry_attempt_total{reason="missing_data"}` | counter | Includes retries triggered by the `getBlock` availability guard | | `erpc_network_dynamic_block_time_milliseconds` | gauge | EMA **slot** time (wall-clock Δ / accepted slot gap on head advances; α=0.1, ≥3 samples). Out-of-range samples ([10ms, 120s]) are rejected and the last published value is kept. Absent/0 until warm. Feeds realtime cache-policy `ttl.blockTimeMultiplier` (`ResolveTTL`) and other `GetNetworkBlockTime` consumers. | **Notable log lines:** - `"svm upstream unhealthy; cordoning out of rotation"` — WARN, carries `shredInsertSlot`, `shredInsertSlotLag`, `latestSlot`, `reason`. - `"svm upstream recovered; uncordoning"` — INFO, carries `shredInsertSlotLag`. - `"upstream returned older slot than we know, falling back to highest known slot"` — DEBUG, carries `knownHighestSlot`, `responseSlot`, and either `upstreamId` or `fromCache`. - `"bootstrapping svm state poller"` — DEBUG, carries `tickInterval` and the effective `debounce`. **OTel span:** `Network.PostForward.getSlot`, with `request.id` and `network.id` attributes. ### Source code entry points - [`architecture/svm/svm_state_poller.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/svm_state_poller.go) — `Poll` fan-out, debounce and traffic gates, ingestion-lag computation, `IsHealthy`, `applyHealthToRouting` (edge-triggered cordoning), slot accessors, shared-counter wiring. - [`architecture/svm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/hooks.go) — `networkPostForward_getSlot` (per-commitment correction), `beyondPoolTip` (the shared tip check), `networkPreForward_getBlock`, `networkPreForward_getBlockTime` and `networkPreForward_minContextSlot` (availability guards), `effectiveCommitment`, `tipStalenessMargin`, `upstreamPostForward_trackContextSlot`. - [`architecture/svm/slot_lag.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/slot_lag.go) — `FilterByFinalizedSlotLag`, `ReferenceFinalizedSlot` (second-highest clamp), `FilterByMinContextSlot`. - [`architecture/svm/ledger_floor.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/ledger_floor.go) — slot-named request extraction shared by the declared-window checks (`slot_bounds.go`). - [`architecture/svm/history_sweep.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/history_sweep.go) — `getSignatureStatuses` null and `getSignaturesForAddress` short-page continuation toward a deeper floor. - [`architecture/svm/slot_bounds.go`](https://github.com/erpc/erpc/blob/main/architecture/svm/slot_bounds.go) — declared `svm.blockAvailability` resolution and per-upstream skip. - [`common/architecture_svm.go — SvmStatePoller interface, MaxShredInsertSlotLagThreshold`](https://github.com/erpc/erpc/blob/main/common/architecture_svm.go#L29-L59) - [`common/config.go — network statePollerDebounce, skipProcessedSlotProbe, maxFinalizedSlotLag, enforceBlockAvailability`](https://github.com/erpc/erpc/blob/main/common/config.go#L2863-L2874) - [`common/config.go — upstreams[*].svm.statePollerDebounce`](https://github.com/erpc/erpc/blob/main/common/config.go#L2918-L2923) - [`common/defaults.go — mergeSvmNetworkDefaults (incl. skipProcessedSlotProbe) and SvmNetworkConfig.SetDefaults`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2579-L2606) ### Related pages - [SVM commitment & finality](/reference/svm/commitment.llms.txt) — how the effective commitment is resolved, and `minContextSlot` semantics. - [SVM JSON-RPC cache](/config/database/svm-json-rpc-cache.llms.txt) — finality classification and cache-key derivation. - [Networks](/config/projects/networks.llms.txt) — the full `networks[*].svm` schema. - [Upstreams](/config/projects/upstreams.llms.txt) — declaring `type: svm` upstreams and `svm.cluster`. - [Cordoning](/operation/cordoning.llms.txt) — how cordon state interacts with selection policies. - [Consensus](/config/failsafe/consensus.llms.txt) — the policy the slot-lag pre-filter protects. - [Error taxonomy](/reference/errors.llms.txt#svm-solana-error-contract) — `-32004`, `-32014`, and the missing-data family. --- --- # Cut RPC cost & latency > Source: https://docs.erpc.cloud/use-cases/cut-costs-and-latency > Serve repeated questions from cache, deduplicate identical requests, and stop paying providers for the same answer twice. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Cut RPC cost & latency Most blockchain data never changes — a block from last year is the same block forever. eRPC caches those answers permanently, merges identical in-flight requests into one, and races a backup upstream only when it actually helps. Teams typically watch their provider bill drop while p99 latency gets faster: cached answers return in microseconds and never count against a rate limit. - **[EVM JSON-RPC cache](/config/database/evm-json-rpc-cache.llms.txt)** — Finality-aware caching: permanent for old blocks, careful for fresh ones. - **[Cache drivers](/config/database/drivers.llms.txt)** — Memory for speed, Redis/Postgres/DynamoDB for shared permanence. - **[Batching & multiplexing](/operation/batch.llms.txt)** — A thousand identical requests become one upstream call. - **[Hedge](/config/failsafe/hedge.llms.txt)** — Pay for a second request only when the first is being slow. - **[Shared state](/config/database/shared-state.llms.txt)** — A fleet of eRPC pods shares one view of chain progress. All of the above in one place — illustrative, not a tuned production config: **Config path:** `(root)` **YAML — `erpc.yaml`:** ```yaml database: evmJsonRpcCache: # two cache tiers: in-process for speed, redis for shared permanence connectors: - id: hot driver: memory - id: cold driver: redis redis: addr: redis-cache:6379 # finalized data is immutable: cache it forever; fresh data gets a short TTL policies: - connector: hot finality: finalized - connector: cold finality: finalized - connector: hot finality: unfinalized ttl: 5s # one shared view of chain tip across all pods sharedState: connector: id: redis-shared driver: redis redis: addr: redis-cache:6379 projects: - id: main networkDefaults: failsafe: - matchMethod: "*" # pay for a 2nd request only on slow tails hedge: delay: { quantile: 0.7, min: 100ms, max: 2s } maxCount: 1 upstreamDefaults: # pack outbound calls into JSON-RPC batches jsonRpc: supportsBatch: true batchMaxSize: 10 batchMaxWait: 50ms # In-flight multiplexing (identical concurrent requests → one call) is automatic. ``` **TypeScript — `erpc.ts`:** ```typescript database: { evmJsonRpcCache: { // two cache tiers: in-process for speed, redis for shared permanence connectors: [ { id: "hot", driver: "memory" }, { id: "cold", driver: "redis", redis: { addr: "redis-cache:6379" } }, ], // finalized data is immutable: cache forever; fresh data gets a short TTL policies: [ { connector: "hot", finality: "finalized" }, { connector: "cold", finality: "finalized" }, { connector: "hot", finality: "unfinalized", ttl: "5s" }, ], }, // one shared view of chain tip across all pods sharedState: { connector: { id: "redis-shared", driver: "redis", redis: { addr: "redis-cache:6379" } }, }, }, projects: [{ id: "main", networkDefaults: { failsafe: [{ matchMethod: "*", // pay for a 2nd request only on slow tails hedge: { delay: { quantile: 0.7, min: "100ms", max: "2s" }, maxCount: 1 }, }], }, upstreamDefaults: { // pack outbound calls into JSON-RPC batches jsonRpc: { supportsBatch: true, batchMaxSize: 10, batchMaxWait: "50ms" }, }, }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: cut my RPC provider bill with eRPC caching** ```text I want to reduce the number of paid RPC calls my app makes by caching blockchain data in eRPC. Set up a two-tier cache (memory + Redis) in my eRPC config with finality-aware TTLs so finalized data is cached forever and fresh data expires quickly. Read the reference and follow the child-page links inside it: https://docs.erpc.cloud/use-cases/cut-costs-and-latency.llms.txt ``` **Prompt Example #2: reduce p99 latency with caching and hedge together** ```text I want to push p99 RPC latency as low as possible. Review my eRPC config and configure eRPC's cache layer and hedge feature together so cached answers return in microseconds and slow uncached calls are raced against a backup upstream. Reference: https://docs.erpc.cloud/use-cases/cut-costs-and-latency.llms.txt ``` **Prompt Example #3: deduplicate identical in-flight requests under high concurrency** ```text Under high concurrency my backend fires hundreds of identical eth_blockNumber and eth_getBlockByNumber calls simultaneously. Configure eRPC's multiplexing and batching in my eRPC config so those collapse to a single upstream call. Reference: https://docs.erpc.cloud/use-cases/cut-costs-and-latency.llms.txt ``` --- ### Cut costs — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions: - [EVM JSON-RPC cache](/config/database/evm-json-rpc-cache.llms.txt) — policy matching, finality semantics, TTLs, freshness gating, skip-cache directives. - [Cache drivers](/config/database/drivers.llms.txt) — every connector's config, TTL behavior, and operational footguns. - [Batching & multiplexing](/operation/batch.llms.txt) — inbound JSON-RPC batches, outbound upstream batching, in-flight dedup rules and exclusions. - [Shared state](/config/database/shared-state.llms.txt) — what's shared, pubsub propagation, clusterKey. - [Hedge](/config/failsafe/hedge.llms.txt) — quantile-based delays so hedging only fires on slow tails. Cost-relevant interactions an agent should weigh: cache hits skip rate-limit budgets and selection entirely; the multiplexer dedupes only identical (network, method, params) requests; finality classification decides whether a response is cached forever, with TTL, or gated on connector freshness. Field-level tables live in each page's agent section. --- --- # How eRPC works > Source: https://docs.erpc.cloud/use-cases/how-it-works > Every JSON-RPC call travels a battle-tested pipeline — auth, smart caching, parallel hedging, multi-upstream consensus — and arrives with full diagnostic headers. Zero glue code required. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # How eRPC works Your JSON-RPC call enters eRPC and immediately gets smarter. It checks a shared cache, races multiple providers in parallel if one is slow, retries against a fresh upstream on errors, and reaches consensus across nodes when data fidelity matters — all before a response reaches your client. Every hop is traced: `X-ERPC-*` headers tell you exactly what happened, and Prometheus counters back it up. - **[Survive provider outages](/use-cases/survive-provider-outages.llms.txt)** — Automatic failover, retry, hedge, and circuit breaker across providers. - **[Cut costs & latency](/use-cases/cut-costs-and-latency.llms.txt)** — EVM-aware cache with block-finality TTLs and shared connectors. - **[Scale chains & providers](/use-cases/scale-chains-and-providers.llms.txt)** — Selection policies, scoring, shadow upstreams, and concurrency controls. - **[Trust the data](/use-cases/trust-the-data.llms.txt)** — Multi-upstream consensus, integrity checks, and getLogs splitting. - **[Lock it down](/use-cases/lock-it-down.llms.txt)** — Authentication strategies, rate limiters, and CORS configuration. - **[See everything](/use-cases/see-everything.llms.txt)** — Prometheus metrics, OpenTelemetry spans, and per-request diagnostic headers. ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: set up a production-ready eRPC config from scratch** ```text I want to set up eRPC in front of my EVM RPC providers so it handles failover, caching, and tail-latency automatically. Walk me through a production-ready my eRPC config that covers the full request lifecycle — auth, cache, retry, hedge, and circuit breaker. Read the reference first: https://docs.erpc.cloud/use-cases/how-it-works.llms.txt ``` **Prompt Example #2: understand and tune an existing eRPC config** ```text Audit my existing my eRPC config and explain what happens to a JSON-RPC call at each stage of the eRPC pipeline — which policies match, what the failsafe chain looks like, and whether any obvious gaps exist (missing timeout, no hedge, etc.). Reference: https://docs.erpc.cloud/use-cases/how-it-works.llms.txt ``` **Prompt Example #3: debug unexpected X-ERPC-* header values** ```text My eRPC responses have unexpected X-ERPC-Attempts and X-ERPC-Hedges values — some calls show 4+ attempts even for simple eth_call requests. Walk me through the pipeline order and explain which stage is likely causing the extra attempts, then adjust my eRPC config to reduce unnecessary retries. Reference: https://docs.erpc.cloud/use-cases/how-it-works.llms.txt ``` --- ### eRPC request lifecycle — full agent reference ### How it works eRPC routes each JSON-RPC call through a deterministic, layered pipeline. Understanding the pipeline order matters for configuration — earlier stages short-circuit later ones. **1. HTTP ingress** (`erpc/http_server.go`) The handler parses the URL path for `{projectId}/{architecture}/{chainId}`, applies aliasing rules if configured, reads and decompresses the body (gzip supported), and dispatches single or batch JSON-RPC payloads. Batch items fan out as concurrent goroutines; results reassemble before the response is written. The real client IP is resolved from trusted forwarder headers before any auth or rate-limit checks. **2. RequestProcessor** (`erpc/request_processor.go:35–67`) `ProcessUnary` is the entry point for both HTTP and gRPC. It resolves the project, wraps raw JSON bytes in `NormalizedRequest`, calls `Validate()` (missing `method` → immediate error), authenticates the consumer via `project.AuthenticateConsumer`, resolves `networkID = "{architecture}:{chainId}"`, applies directive defaults from `network.Config().DirectiveDefaults`, then delegates to `project.Forward`. **3. Project layer** (`erpc/projects.go`) `PreparedProject.Forward` acquires a project-level rate-limit permit (no-op when `rateLimitBudget` is unset), fires `HandleProjectPreForward` — the first EVM hook, which handles `eth_call` / `eth_estimateGas` (default block tag), `eth_chainId` (served from config), and proactive `eth_getLogs` / `trace_filter` range splitting. If the hook handles the request, `HandleNetworkPostForward` is called on the result before returning. Otherwise the call proceeds to `network.Forward`. **4. Network layer** (`erpc/networks.go:931–1603`) `Network.Forward` is the core dispatch function, in execution order: 1. **Static responses** — matched against `network.cfg.StaticResponses` before any upstream is contacted. 2. **Multiplexing** — identical in-flight requests share one leader goroutine; followers wait and receive a copied response with their original request ID patched in. 3. **Cache read** — `cacheDal.Get` fans out across all matching policies; first hit short-circuits the rest of the pipeline. 4. **Upstream ordering** — `policyEngine.GetOrdered` returns upstreams ranked by selection policy scores; falls back to registry order on cold start. 5. **EVM network pre-forward hook** (`HandleNetworkPreForward`) — upstream-aware short-circuits for `eth_getLogs` range enforcement, `eth_chainId`, `trace_filter`, and `eth_blockNumber` (answered from the served tip while `enforceHighestBlock` is on). 6. **Future-block short-circuit** — with `evm.shortCircuitFutureBlocks: true`, a numbered `eth_getBlockByNumber` beyond every upstream's head returns `null` without touching any upstream. 7. **Method guard** — `eth_accounts` and `eth_sign` are hardcoded unsupported; stateful methods require exactly one targeted upstream. 8. **Network rate limiting** — network-level budget checked. 9. **Request preparation** — `evm.NormalizeHttpJsonRpc` normalizes params (block tag → concrete hex interpolation, EVM-specific transformations), caches block number for downstream availability checks. 10. **Failsafe executor selection** — `getFailsafeExecutors` iterates `failsafe[]` in config order, returning the first whose `matchMethod` (wildcard) and `matchFinality` match. **5. Failsafe executor chain** (`erpc/network_executor.go:69–200`) The executor nests policies in a fixed order: ``` timeout (wraps entire invocation) ↳ if consensus enabled && !SkipConsensus: consensus( retry( hedge(tryOneUpstream) ← one upstream per consensus slot ) ) else: retry( hedge(runUpstreamSweep) ← all upstreams per sweep ) ``` - **Timeout** wraps the context with `context.WithTimeoutCause`; the cause is `ErrDynamicTimeoutExceeded`. Can be a static duration or an adaptive quantile function over observed per-method latency. - **Consensus** is delegated to the `consensusRunner` interface. The executor does not import the consensus package directly. - **Retry** (`runRetry`) iterates up to `maxAttempts`. For data-unavailable retries (`block_unavailable`, `empty_result`, `missing_data`) it uses an EMA block-time-relative delay (falling back to `emptyResultDelay`). For genuine errors it uses exponential backoff via `failsafe.ComputeBackoff`. `firstInformativeErr` is tracked so a bare `ErrNoUpstreamsLeftToSelect` on a later attempt does not mask the root cause. - **Hedge** (`runHedge`) fires up to `maxCount` parallel copies after an adaptive delay. Write methods are never hedged. A hedge leg returning an emptyish result does not win the race — siblings continue until a non-null response arrives. **6. Upstream sweep loop** (`erpc/networks.go:1226–1407`) For each iteration inside `sweepFn`: 1. Calls `req.NextUpstream()` — atomic round-robin with skip logic for consumed and permanently errored upstreams; safe for concurrent hedge goroutines. 2. **Block availability gating** — compares the request's block number against the upstream's `EvmEffectiveLatestBlock`. Retryable if within `maxRetryableBlockDistance` (default 128) of the upstream head; fail-open on poller errors. 3. Calls `HandleUpstreamPreForward` then `u.Forward`. 4. `HandleUpstreamPostForward` validates the response (integrity checks, mark-empty-as-error methods, `eth_sendRawTransaction` idempotency). 5. `normalizeResponse` rewrites the JSON-RPC `id` to match the client's original byte-for-byte (preserving large 64-bit integers via `IDRawBytes()`). 6. `MarkUpstreamCompleted` releases retryable-errored upstreams back into rotation for the next failsafe retry round. Deterministic client errors return immediately. **7. Response write and async cache** Back in `http_server.go`, `setResponseHeaders` emits the full `X-ERPC-*` diagnostic surface (attempts, retries, hedges, cache status, winning upstream, duration). The JSON-RPC response body is streamed. An async goroutine fires `cacheDal.Set` with a 10-second deadline under `appCtx` — a client disconnect never aborts the cache write. Panics in the write goroutine are recovered and reported via `erpc_unexpected_panic_total{scope="cache-set"}`. **eth_query\* (MIP-16) path** One `EvmQueryExecutor` answers `eth_queryBlocks`, `eth_queryTransactions`, `eth_queryLogs`, `eth_queryTraces`, and `eth_queryTransfers` for both transports. gRPC `QueryService` streams enter through `ProcessQueryStream` (auth and rate limiting identical to the unary path); JSON-RPC calls enter through `Network.Forward`, which hands them to the executor before the cache and per-upstream dispatch and returns one page per call. The executor resolves the range once, checks availability, tries native gRPC BDS upstreams first (MIP-16 request passed through unchanged), and otherwise builds block-aligned pages from `eth_getBlockByNumber`, `eth_getBlockReceipts`, `eth_getLogs` and `trace_block` / `debug_traceBlockByNumber` sub-requests, each sent through `Network.Forward` with the client request as parent. See [method handlers](/reference/evm/method-handlers.llms.txt). ### Config schema Config fields governing the lifecycle. Network-level failsafe and directive defaults are the primary control surface. | YAML path | Type | Default | Behavior / footguns | |---|---|---|---| | `networks[].failsafe[].matchMethod` | string | `"*"` | Wildcard pattern; first matching executor wins. [`erpc/network_executor.go:L83-84`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L83-L84) | | `networks[].failsafe[].matchFinality` | `[]DataFinalityState` | `[]` (any) | Empty = match all finalities. [`erpc/network_executor.go:L79`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L79) | | `networks[].failsafe[].timeout` | `*Duration` | nil (no timeout) | Wraps full executor invocation; cause is `ErrDynamicTimeoutExceeded`. [`erpc/network_executor.go:L86-89`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L86-L89) | | `networks[].failsafe[].retry.maxAttempts` | int | 1 (no retry) | Upper bound on retry iterations. [`erpc/network_executor.go:L210-213`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L210-L213) | | `networks[].failsafe[].retry.emptyResultMaxAttempts` | int | 0 (disabled) | Cap for data-unavailable retries independently of `maxAttempts`. | | `networks[].failsafe[].retry.emptyResultDelay` | `*Duration` | nil | Fixed wait before data-unavailable retry, used before EMA block-time warms up. | | `networks[].failsafe[].retry.emptyResultAccept` | `[]string` | `DefaultEmptyResultAccept()` | Methods for which an empty/null result is NOT retried (e.g. `eth_call`, `eth_getLogs`). | | `networks[].failsafe[].retry.backoffFactor` | float | per `failsafe.ComputeBackoff` | Exponential backoff multiplier for genuine-error retries. | | `networks[].failsafe[].retry.backoffMaxDelay` | `*Duration` | per `failsafe.ComputeBackoff` | Maximum inter-retry delay. | | `networks[].failsafe[].hedge.maxCount` | int | 0 (disabled) | Maximum concurrent hedge attempts beyond the primary. | | `networks[].failsafe[].hedge.delay` | `AdaptiveDuration` | — | Scalar or `quantile`+tracker for adaptive timing. | | `networks[].failsafe[].consensus` | `*ConsensusConfig` | nil | Enables consensus; delegates to `consensus.Run`. | | `networks[].directiveDefaults.retryEmpty` | `*bool` | false | Retry on emptyish upstream responses. [`common/request.go:L575-578`](https://github.com/erpc/erpc/blob/main/common/request.go#L575-L578) | | `networks[].directiveDefaults.retryPending` | `*bool` | true (implicit) | Retry tx-lookup methods until confirmed. [`common/request.go:L579-583`](https://github.com/erpc/erpc/blob/main/common/request.go#L579-L583) | | `networks[].directiveDefaults.skipCacheRead` | `*string` | `""` (off) | `"true"` = skip all; connector-id pattern = skip matching. | | `networks[].directiveDefaults.useUpstream` | `*string` | `""` | Upstream id or glob; applied inside `NextUpstream` loop. | | `networks[].directiveDefaults.skipInterpolation` | `*bool` | false | Prevent block tag → hex replacement in outbound params. | | `networks[].directiveDefaults.skipConsensus` | `*bool` | false | Bypass consensus; retry+hedge still apply. [`erpc/network_executor.go:L178-191`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L178-L191) | | `networks[].evm.maxRetryableBlockDistance` | `*int64` | 128 | Blocks ahead of upstream head that are retryable. [`erpc/networks.go:L1975-1979`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1975-L1979) | | `projects[].rateLimitBudget` | string | `""` | Project-level budget ID; empty = no project rate limiting. | | `networks[].rateLimitBudget` | string | `""` | Network-level budget ID. | | `networks[].multiplexing.enabled` | bool | false | Deduplicate identical in-flight requests. [`erpc/networks.go:L1990`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1990) | | `networks[].staticResponses` | `[]StaticResponseConfig` | `[]` | Matched before cache and upstream; zero upstream contact. | | `server.executionHeaders` | `*ExecutionHeadersMode` | `"all"` | `"all"` = full per-attempt trace; `"summary"` = counters only; `"off"` = none. | **EVM network config** — all under `networks[].evm.` in YAML; defaults set by `EvmNetworkConfig.SetDefaults()` (`common/defaults.go`): | YAML path | Type | Default | Behavior / footguns | |---|---|---|---| | `evm.chainId` | int64 | required (0 = unset) | Used for `eth_chainId` responses and network ID formation (`evm:`). | | `evm.fallbackFinalityDepth` | int64 | `1024` | Depth used when the network cannot determine finality dynamically. A block is considered finalized if `latestBlock - blockNumber >= fallbackFinalityDepth`. | | `evm.fallbackStatePollerDebounce` | Duration | unset | Poll interval for the state poller while the block time is unknown; unset, 0.7s (the 1s cold block time × 0.7). | | `evm.getLogsMaxAllowedRange` | int64 | `30_000` | Max block range for `eth_getLogs` before forced splitting. [`common/defaults.go:L2092-2094`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2092-L2094) | | `evm.getLogsMaxAllowedAddresses` | int64 | `0` (unlimited) | Max address count in `eth_getLogs` filter. | | `evm.getLogsMaxAllowedTopics` | int64 | `0` (unlimited) | Max topic count in `eth_getLogs` filter. | | `evm.getLogsSplitOnError` | `*bool` | `true` | Split and retry `eth_getLogs` when upstream returns range-too-large error. [`common/defaults.go:L2095-2097`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2095-L2097) | | `evm.getLogsSplitConcurrency` | int | `10` | Max concurrent sub-requests when splitting `eth_getLogs`. [`common/defaults.go:L2098-2100`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2098-L2100) | | `evm.traceFilterSplitOnError` | `*bool` | nil (disabled) | Split and retry `trace_filter`/`arbtrace_filter` on range-too-large. Opt-in required. | | `evm.traceFilterSplitConcurrency` | int | `10` | Max concurrent sub-requests when splitting `trace_filter`. [`common/defaults.go:L2105-2107`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2105-L2107) | | `evm.enforceBlockAvailability` | `*bool` | nil (true in logic) | Whether to gate requests based on upstream known block bounds. | | `evm.markEmptyAsErrorMethods` | `[]string` | 11 methods (see below) | Methods for which an empty/null upstream result is converted to `ErrEndpointMissingData` and retried. Default set: `eth_blockNumber`, `eth_getBlockByNumber`, `eth_getTransactionByHash`, `eth_getTransactionByBlockHashAndIndex`, `eth_getTransactionByBlockNumberAndIndex`, `eth_getUncleByBlockHashAndIndex`, `eth_getUncleByBlockNumberAndIndex`, `debug_traceTransaction`, `trace_transaction`, `trace_block`, `trace_get`. `eth_getBlockByHash`, `eth_getTransactionReceipt`, `eth_getBlockReceipts` are intentionally excluded. [`common/defaults.go:L2044-2058`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2044-L2058) | | `evm.dynamicBlockTimeDebounceMultiplier` | `*float64` | `0.7` | Scales EMA block time to derive the state-poller debounce interval. | | `evm.blockUnavailableDelayMultiplier` | `*float64` | `1.0` | Multiplies EMA-estimated block time to derive the dynamic retry delay for `ErrUpstreamBlockUnavailable`/`ErrEndpointMissingData`. Returns `0` before EMA warms up — falls back to `failsafe[*].retry.emptyResultDelay`. | | `evm.idempotentTransactionBroadcast` | `*bool` | nil (enabled) | When enabled, `eth_sendRawTransaction` converts "already known" to success and verifies "nonce too low" via `eth_getTransactionByHash`. Set to `false` to return raw upstream errors. | | `evm.emptyResultConfidence` | `AvailbilityConfidence` | `blockHead` | Confidence level for empty-result retries: `blockHead` = retry empties for blocks ≤ latest head; `finalizedBlock` = stricter, only retry for blocks ≤ finalized head. [`common/defaults.go:L2075-2079`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2075-L2079) | | `evm.servedTip` | object | `nil` (quorum 2) | Tunes how `latest`/`finalized` is chosen: `quorum`, `maxRegressionBlocks`, `guaranteedMethods`, `guaranteedFor`, `followCacheHead`. Keys: [Networks config](/config/projects/networks.llms.txt#config-schema); rule: [Block tracking](/reference/evm/block-tracking.llms.txt#served-tip). | | `evm.integrity.enforceHighestBlock` | `*bool` | `true` | **Deprecated** — migrate to `directiveDefaults.enforceHighestBlock`. | | `evm.integrity.enforceGetLogsBlockRange` | `*bool` | `true` | **Deprecated** — migrate to `directiveDefaults.enforceGetLogsBlockRange`. | | `evm.integrity.enforceNonNullTaggedBlocks` | `*bool` | `true` | **Deprecated** — migrate to `directiveDefaults.enforceNonNullTaggedBlocks`. | ### Worked examples **1. Baseline resilient config — timeout + retry + hedge for any method.** Good starting point for a production network with multiple upstreams. The timeout bounds the whole race; retry recovers transient upstream errors; hedge cuts tail latency on slow providers: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "*" timeout: duration: 10s retry: maxAttempts: 3 backoffMaxDelay: 1s hedge: delay: quantile: 0.7 min: 100ms max: 2s maxCount: 1 ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "*", timeout: { duration: "10s" }, retry: { maxAttempts: 3, backoffMaxDelay: "1s" }, hedge: { delay: { quantile: 0.7, min: "100ms", max: "2s" }, maxCount: 1, }, }] ``` **2. Slow-data retry for pending transactions.** `eth_getTransactionReceipt` and `eth_getTransactionByHash` return null until the transaction is mined. Combine `emptyResultMaxAttempts` with the directive default `retryPending: true` to poll until confirmed, using block-time-relative delays: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml directiveDefaults: retryPending: true failsafe: - matchMethod: "eth_getTransactionReceipt|eth_getTransactionByHash" retry: maxAttempts: 10 emptyResultMaxAttempts: 10 emptyResultDelay: 500ms ``` **TypeScript — `erpc.ts`:** ```typescript directiveDefaults: { retryPending: true }, failsafe: [{ matchMethod: "eth_getTransactionReceipt|eth_getTransactionByHash", retry: { maxAttempts: 10, emptyResultMaxAttempts: 10, emptyResultDelay: "500ms", }, }] ``` **3. Consensus for critical state reads.** Use consensus when multiple upstreams must agree on a result before it is returned. `skipConsensus` directive lets callers opt out per-request: **Config path:** `projects[].networks[].failsafe[]` **YAML — `erpc.yaml`:** ```yaml failsafe: - matchMethod: "eth_getBalance|eth_call" consensus: minParticipants: 2 method: "majority" ``` **TypeScript — `erpc.ts`:** ```typescript failsafe: [{ matchMethod: "eth_getBalance|eth_call", consensus: { minParticipants: 2, method: "majority" }, }] ``` **4. Multiplexing for high-traffic hot paths.** When many clients request the same block simultaneously, multiplexing deduplicates the upstream request — one upstream call serves all waiting followers with a response ID patch per follower: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml multiplexing: enabled: true ``` **TypeScript — `erpc.ts`:** ```typescript multiplexing: { enabled: true } ``` ### Request/response behavior - **Directive precedence:** HTTP headers → query params (query params override headers for `use-upstream`, `retry-empty`, `retry-pending`, `skip-cache-read`, `skip-interpolation`, `skip-consensus`). Config `directiveDefaults` are applied only when directives are not already set — HTTP-set directives are never overwritten. [`common/request.go:L563-565`](https://github.com/erpc/erpc/blob/main/common/request.go#L563-L565) - **Response headers** emitted by `setResponseHeaders` (`erpc/http_server.go:1105`) under `server.executionHeaders`: | Header | When present | Value | |---|---|---| | `X-ERPC-Version` | always | eRPC version string | | `X-ERPC-Commit` | always | git commit SHA | | `X-ERPC-Attempts` | always | total physical ops (upstream + cache) | | `X-ERPC-Upstream-Attempts` | always | upstream-scope attempt count | | `X-ERPC-Upstream-Retries` | always | upstream-scope retry count | | `X-ERPC-Upstream-Hedges` | always | upstream-scope hedge count | | `X-ERPC-Network-Attempts` | always | network-scope rotation count | | `X-ERPC-Network-Retries` | always | network-scope retry count | | `X-ERPC-Network-Hedges` | always | network-scope hedge count | | `X-ERPC-Cache-Attempts` | only if cache exercised | cache-scope attempt count | | `X-ERPC-Consensus-Slots` | only if consensus used | number of consensus slots | | `X-ERPC-Consensus-Disputes` | only if disputes | number of disputes | | `X-ERPC-Cache` | if response available | `HIT` or `MISS` | | `X-ERPC-Upstream` | if upstream response | upstream ID that served it | | `X-ERPC-Duration` | if response | total request duration in milliseconds | | `X-ERPC-Upstreams` | `executionHeaders=all` | per-attempt trace: `id=role:outcome:durationMs:won\|lost` | - **Request directives** — settable via HTTP header or query param (query overrides header). The `X-ERPC-Enforce-*` and `X-ERPC-Integrity` directives are settable via both header and query param. [`common/request.go:L38-114`](https://github.com/erpc/erpc/blob/main/common/request.go#L38-L114) | Header | Query param | Behavior | |---|---|---| | `X-ERPC-Retry-Empty` | `retry-empty` | Retry emptyish upstream responses | | `X-ERPC-Retry-Pending` | `retry-pending` | Retry pending tx lookups | | `X-ERPC-Skip-Cache-Read` | `skip-cache-read` | `"true"` = skip all; connector-id pattern = skip matching | | `X-ERPC-Use-Upstream` | `use-upstream` | Pin request to matching upstream(s) by id, glob, or tag | | `X-ERPC-Skip-Interpolation` | `skip-interpolation` | Don't replace block tags with hex in outbound params | | `X-ERPC-Skip-Consensus` | `skip-consensus` | Bypass consensus; retry+hedge still apply | | `X-ERPC-Enforce-Highest-Block` | `enforce-highest-block` | Block integrity validation | | `X-ERPC-Enforce-GetLogs-Range` | `enforce-getlogs-range` | Enforce `eth_getLogs` block range limit | | `X-ERPC-Enforce-Non-Null-Tagged-Blocks` | `enforce-non-null-tagged-blocks` | Reject null on tagged block lookups | | `X-ERPC-Integrity` | `integrity` | Per-request data-integrity level (`off`/`intrinsic`/`corroborated`/`authoritative`) or profile name; see [Integrity checks](/config/failsafe/integrity.llms.txt) | - **Retry reasons** — `shouldRetryWithReason` returns one of: `execution_exception_retryable` (EVM execution exception with `retryableTowardNetwork=true`), `block_unavailable` (`ErrCodeUpstreamBlockUnavailable`, subject to `emptyResultMaxAttempts` cap), `missing_data` (`ErrCodeEndpointMissingData` unless `RetryEmpty=false`), `retryable_error` (generic `IsRetryableTowardNetwork`), `empty_result` (emptyish response with `RetryEmpty=true`), `pending_tx` (tx-lookup methods with `RetryPending=true`). Composite requests are never retried at network scope. [`erpc/network_executor.go:L374-463`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L374-L463) - **Batch requests** fan out to per-item goroutines; each item is processed independently through the full pipeline and reassembled before writing. - **Composite subrequests** (`IsCompositeRequest=true`) skip network-scope retry and hedge to prevent exponential amplification of range-split sub-requests. [`erpc/network_executor.go:L378-380`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L378-L380) - **Response ID fidelity:** `normalizeResponse` uses `IDRawBytes()` for byte-perfect round-trip of the JSON-RPC `id` field, preserving large 64-bit integer IDs that cannot be represented as `float64`. [`erpc/networks.go:L2234-2266`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2234-L2266) ### Best practices - **Set a timeout** for every failsafe block in production; without it, a hung upstream holds the goroutine indefinitely and can exhaust the connection pool under load. - **Use adaptive hedge delay** (`quantile: 0.7`, `min: 100ms`, `max: 2s`) over static delays — static delays go stale as provider latencies shift; quantile mode self-adjusts per method. - **Enable multiplexing** for networks that see bursts of identical calls (e.g. `eth_blockNumber`, `eth_getBlockByNumber?latest`); it eliminates duplicate upstream cost at zero config complexity. - **Set `emptyResultDelay`** as a bootstrap fallback for data-unavailable retries — the EMA block-time delay takes a few requests to warm up; without a fallback the first retries fire immediately. - **Do not set `directiveDefaults.retryEmpty: true` globally** unless you also set `emptyResultMaxAttempts`; without a cap, methods that legitimately return null (e.g. unindexed blocks on archive nodes) will exhaust `maxAttempts` retries on every call. - **Prefer `staticResponses`** for methods your upstreams do not support and will never support (e.g. a custom method returning a fixed value); this avoids wasting upstream budget on guaranteed errors. - **eRPC's own requests** (state pollers, chainId probes) set `UpstreamPolicies: TimeoutOnly`, bypassing retry, hedge, and circuit breaker — only per-attempt timeout applies. Never forward internal requests to a public consumer-facing failsafe path. ### Edge cases & gotchas 1. **`ApplyDirectiveDefaults` is called twice** — once in `RequestProcessor` and again defensively in `Network.Forward` for gRPC callers. The guard ensures only the first call has effect. [`common/request.go:L563-565`](https://github.com/erpc/erpc/blob/main/common/request.go#L563-L565) 2. **Multiplexer follower race on close**: a follower arriving during leader cleanup retries `LoadOrStore` and becomes the new leader or joins a new follower group. [`erpc/networks.go:L2017-2025`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2017-L2025) 3. **`ErrNoUpstreamsLeftToSelect` degeneration on retries**: after the first retry round, all upstreams may be marked consumed, hiding the original error. `firstInformativeErr` is tracked and surfaced in the final `ErrFailsafeRetryExceeded` wrapping. [`erpc/network_executor.go:L265-284`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L265-L284) 4. **Hedge emptyish rejection**: a fast `null` from a lagging upstream does not win the hedge race — in-flight siblings continue until a non-null result arrives. Methods in `emptyResultAccept` (e.g. `eth_call`) are exempt. [`erpc/network_executor.go:L607-624`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L607-L624) 5. **`SkipConsensus` falls through to retry+hedge**: when `skipConsensus=true`, the executor skips consensus entirely but all other failsafe policies still apply. [`erpc/network_executor.go:L178-191`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L178-L191) 6. **Cache write panic recovery**: panics in the async write goroutine are recovered and reported via `erpc_unexpected_panic_total{scope="cache-set"}`. [`erpc/networks.go:L1496-1508`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1496-L1508) 7. **Stateful method enforcement**: methods marked `Stateful` require exactly one targeted upstream. Without a `UseUpstream` selector, multiple upstreams return `ErrNotImplemented`. `eth_accounts` and `eth_sign` are always unsupported. [`erpc/networks.go:L2112-2143`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L2112-L2143) 8. **Block availability check is fail-open**: if `EvmAssertBlockAvailability` errors (poller issues, partial state), the request proceeds to the upstream rather than being gated. [`erpc/networks.go:L1949-1959`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1949-L1959) 9. **`eth_sendRawTransaction` is never wrapped in `ErrFailsafeRetryExceeded`**: execution- reverted responses are surfaced directly — the revert IS the answer, not a retry condition. [`erpc/network_executor.go:L278-283`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L278-L283) 10. **Async cache write does not block the response**: the write goroutine uses `appCtx`, not the request context, so a client disconnect never aborts the write. The 10-second deadline is on the write itself, not on waiting for it. [`erpc/networks.go:L1494-1518`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L1494-L1518) 11. **Query shim retry safety**: a gRPC query stream error is only retried on the next upstream if no page has been emitted (`StreamError.PageEmitted` gate). Partial-result retries are forbidden. [`erpc/query_executor.go:L126-136`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go#L126-L136) 12. **`TranslateToJsonRpcException` dominant-code selection**: when all upstreams return skipped or unsupported errors, the wire JSON-RPC code depends on the first child's error type — either `-32601` (method not found) or `-32603` (server error). Clients cannot reliably distinguish "globally unsupported" from "internal error" by code alone; the `data` field carries the full eRPC error chain for programmatic detection. 13. **`trace_block` → `debug_traceBlockByNumber` fallback in shim**: `shimQueryTraces` first tries `trace_block`; if the upstream returns `ErrCodeEndpointUnsupported`, it retries with `debug_traceBlockByNumber?callTracer`. If that is also unsupported, returns gRPC `Unimplemented`. [`erpc/query_shim.go:L388-420`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go#L388-L420) 14. **`paginateLogsByBlock` never splits a block across pages**: when adding a block's logs would exceed the page limit and the page already has items, the function stops before that block (producing a cursor). If the first block alone exceeds the limit, all its logs are included — the limit is a soft cap at block boundaries, not an absolute log count. [`erpc/query_shim.go:L617-649`](https://github.com/erpc/erpc/blob/main/erpc/query_shim.go#L617-L649) 15. **Hash-based projection preserves block hash**: `ProjectBlockFields` never zeros the `Hash` field even when `sel.Hash=false`, because the hash is required for cursor semantics in paginated query responses. [`erpc/query_field_projection.go:L12-15`](https://github.com/erpc/erpc/blob/main/erpc/query_field_projection.go#L12-L15) 16. **`MarkEmptyAsErrorMethods` only fires when `RetryEmpty` directive is true**: even if a method is in the list, conversion to `ErrEndpointMissingData` is gated on `req.Directives().RetryEmpty`. Operators must set `retryEmpty: true` (directive default or per-request header) for this feature to activate. [`architecture/evm/common.go:L23-25`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L23-L25) 17. **Custom `markEmptyAsErrorMethods` completely replaces the default 11-method set** — there is no merge. Setting `markEmptyAsErrorMethods: ["custom_method"]` disables all default methods. An explicitly empty `markEmptyAsErrorMethods: []` disables the feature entirely. [`common/defaults.go:L2110-2112`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2110-L2112) 18. **200-OK EVM revert detection uses `dt[1:11]`**: in `ExtractJsonRpcError`, the revert-payload check is `dt[1:11] == "0x08c379a0"` because `jr.GetResultString()` returns the JSON-encoded value — `dt[0]` is the JSON double-quote character, so the actual hex string starts at index 1. A check starting at index 0 always fails on valid JSON strings. [`architecture/evm/error_normalizer.go:L609-624`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L609-L624) 19. **`FullySyncedThreshold = 4`**: an upstream must return `eth_syncing: false` four consecutive times before eRPC stops sending syncing-check probes. One `syncing=true` resets the counter. [`architecture/evm/evm_state_poller.go:L21`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L21) ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_requests_received_total` | counter | project, network, category, finality, user, agent_name | Request enters `project.Forward` | | `erpc_network_successful_request_total` | counter | project, network, vendor, upstream, category, attempt, finality, emptyish, user, agent_name | `project.Forward` returns non-error | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, error, severity, finality, user, agent_name | `project.Forward` returns error | | `erpc_network_request_duration_seconds` | histogram | project, network, vendor, upstream, category, finality, user | Per-request total duration (success and error) | | `erpc_network_retry_attempt_total` | counter | project, network, category, reason, finality | Each network-scope retry attempt | | `erpc_network_data_unavailable_wait_seconds` | histogram | project, network, category, reason, finality | Deliberate catch-up delay before data-unavailable retry | | `erpc_network_hedged_request_total` | counter | project, network, upstream, category, hedgeCount, finality, user, agent_name | Hedge attempt fired to a specific upstream | | `erpc_network_hedge_discards_total` | counter | project, network, upstream, category, attempt, hedge, finality, user, agent_name | Hedge request discarded (another leg won) | | `erpc_network_hedge_winner_total` | counter | project, network, upstream, category, finality | Upstream won a hedge race | | `erpc_network_timeout_fired_total` | counter | project, network, category, finality, scope | Network-scope timeout fired | | `erpc_network_multiplexed_requests_total` | counter | project, network, category | Follower piggybacked on in-flight leader | | `erpc_network_static_response_served_total` | counter | project, network, category | Static response matched | | `erpc_upstream_wrong_empty_response_total` | counter | project, vendor, network, upstream, category, finality, user, agent_name | Upstream returned empty while another returned data | | `erpc_upstream_request_errors_total` | counter | (upstream error labels) | Upstream skip due to block availability check failure | | `erpc_upstream_attempt_outcome_total` | counter | project, network, upstream, category, outcome, is_hedge, is_retry, finality | One increment per upstream attempt with its terminal outcome | Served-tip and bench metrics: see the [metrics reference](/reference/metrics.llms.txt#area-3-block-number-and-tip-tracking). Key OpenTelemetry spans: - `Network.Forward` — top-level; attributes: `cache.hit`, `multiplexed`, `failsafe.matched_method` - `PolicyEngine.GetOrdered` — upstream ordering time - `Network.forwardAttempt` — per-attempt; attributes: `execution.attempt`, `execution.retry`, `execution.hedge` - `Network.UpstreamLoop` — per-upstream iteration; attributes: `upstream.id`, `upstream.latest_block`, `skipped`, `skip_reason` - `Network.TryForward` — call to `doForward` per upstream - `Network.NormalizeResponse` — response ID rewrite - `Network.EnrichStatePoller` — state poller suggestion after block response - `Upstream.PreForwardHook` / `Upstream.PostForwardHook` — EVM method hooks per upstream - `Project.Forward` → `Project.PreForwardHook` → `Network.PostForwardHook` - `QueryStream.Handle` — gRPC query stream top-level span - `Query.Execute`, `Query.ResolveQueryBounds`, `Query.ShimBlocks/Logs/Transactions/Traces/Transfers`, `Query.ForwardSubrequest` - `Cache.Get` / `Cache.Set` — cache fan-out spans with `network.id` / `upstream.id` attributes - `Evm.ExtractBlockReferenceFromRequest` / `Evm.ExtractBlockReferenceFromResponse` — block-ref resolution detail spans ### Source code entry points - [`erpc/request_processor.go`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go) — `RequestProcessor.ProcessUnary` / `ProcessQueryStream`: project resolution, auth, network selection, unified entry point for HTTP and gRPC. - [`erpc/networks.go`](https://github.com/erpc/erpc/blob/main/erpc/networks.go) — `Network.Forward`: multiplexing, cache read/write, upstream ordering, block-availability gating, all EVM hooks, `normalizeResponse`, `enrichStatePoller`. - [`erpc/network_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go) — `networkExecutor.Run`: failsafe policy composition (timeout → consensus → retry → hedge); retry reason classification and backoff computation. - [`erpc/projects.go`](https://github.com/erpc/erpc/blob/main/erpc/projects.go) — `PreparedProject.Forward`: project-level rate limiting, metrics, shadow upstreams, EVM hook wrapper. - [`erpc/http_server.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go) — HTTP ingress, batch dispatch, directive enrichment, `setResponseHeaders`. - [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go) — Four EVM lifecycle hooks: `HandleProjectPreForward`, `HandleNetworkPreForward`, `HandleNetworkPostForward`, `HandleUpstreamPostForward`. - [`common/request.go`](https://github.com/erpc/erpc/blob/main/common/request.go) — `NormalizedRequest`: directive system, `NextUpstream` round-robin, `MarkUpstreamCompleted`, composite type, finality caching, `ExecState`. - [`erpc/query_executor.go`](https://github.com/erpc/erpc/blob/main/erpc/query_executor.go) — `EvmQueryExecutor.Execute`: structured query dispatch; native pipe-through vs. shim routing. ### Related pages - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — retry, hedge, and circuit breaker in depth. - [Cut costs & latency](/use-cases/cut-costs-and-latency.llms.txt) — cache policies, TTLs, and storage drivers. - [Scale chains & providers](/use-cases/scale-chains-and-providers.llms.txt) — selection policies, scoring, and shadow upstreams. - [Trust the data](/use-cases/trust-the-data.llms.txt) — consensus, integrity checks, and getLogs splitting. - [Lock it down](/use-cases/lock-it-down.llms.txt) — auth strategies, rate limiters, CORS. - [See everything](/use-cases/see-everything.llms.txt) — Prometheus metrics, OTel spans, dashboards. - [Retry](/config/failsafe/retry.llms.txt) — retry policy config reference. - [Hedge](/config/failsafe/hedge.llms.txt) — hedge policy config reference. - [Rate limiters](/config/rate-limiters.llms.txt) — budget and rule configuration. --- --- # Lock it down > Source: https://docs.erpc.cloud/use-cases/lock-it-down > Keys, JWTs, sign-in with Ethereum, per-user rate limits — your RPC endpoint stops being a free-for-all. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Lock it down An open RPC endpoint gets discovered fast — and someone else's bot ends up spending your provider budget. eRPC puts real access control in front: API keys for your services, JWTs or Sign-in-with-Ethereum for your users, network allowlists for your infra, and per-user rate budgets so no single consumer can starve the rest. Browsers can talk to it directly, under CORS rules you control. - **[Authentication](/config/auth.llms.txt)** — Secrets, JWT, Sign-in-with-Ethereum, and IP allowlists. - **[Rate limiters](/config/rate-limiters.llms.txt)** — Budgets that protect providers, projects, and fairness between users. - **[CORS](/config/projects/cors.llms.txt)** — Serve browsers directly on your own origin rules. - **[Admin API](/operation/admin.llms.txt)** — Operational controls behind their own separate auth. All of the above in one place — illustrative, not a tuned production config: **Config path:** `(root)` **YAML — `erpc.yaml`:** ```yaml rateLimiters: # a reusable budget: fairness between consumers budgets: - id: per-user rules: - method: "*" maxCount: 200 period: 1s projects: - id: main # serve browsers directly, on your own origin rules cors: allowedOrigins: ["https://app.example.com"] allowCredentials: false auth: strategies: # API keys for your services, throttled by the budget above - type: secret rateLimitBudget: per-user secret: value: \${MY_API_KEY} # infra allowlist: no key needed inside your network - type: network network: allowedCIDRs: ["10.0.0.0/8"] allowLocalhost: true # Admin API auth is separate: admin.auth (same strategy types). ``` **TypeScript — `erpc.ts`:** ```typescript rateLimiters: { // a reusable budget: fairness between consumers budgets: [{ id: "per-user", rules: [{ method: "*", maxCount: 200, period: "1s" }], }], }, projects: [{ id: "main", // serve browsers directly, on your own origin rules cors: { allowedOrigins: ["https://app.example.com"], allowCredentials: false, }, auth: { strategies: [ // API keys for your services, throttled by the budget above { type: "secret", rateLimitBudget: "per-user", secret: { value: process.env.MY_API_KEY }, }, // infra allowlist: no key needed inside your network { type: "network", network: { allowedCIDRs: ["10.0.0.0/8"], allowLocalhost: true }, }, ], }, }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add API-key auth and per-user rate limits** ```text My eRPC endpoint is wide open and I need to lock it down with API keys and per-user rate budgets so no single consumer can exhaust my provider quota. Update my eRPC config with authentication strategies and fair-use limits. Read the full reference first: https://docs.erpc.cloud/use-cases/lock-it-down.llms.txt ``` **Prompt Example #2: enable CORS for browser clients and configure JWT auth** ```text I want my frontend app to call eRPC directly from the browser using JWT tokens issued by my auth service. Configure CORS and JWT strategy in my eRPC config so only my domain can make requests and tokens are validated properly. Reference: https://docs.erpc.cloud/use-cases/lock-it-down.llms.txt ``` **Prompt Example #3: audit auth and rate-limit config for gaps** ```text Review the auth and rate-limiter setup in my eRPC config for security gaps — missing IP allowlist coverage, missing method-level rate rules, or strategies without budgets. Suggest hardening steps. Reference: https://docs.erpc.cloud/use-cases/lock-it-down.llms.txt ``` --- ### Lock it down — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions: - [Authentication](/config/auth.llms.txt) — every strategy (secret, jwt, siwe, network, database) with full per-strategy config. - [Rate limiters](/config/rate-limiters.llms.txt) — budgets, per-method rules, auto-tuner behavior and footguns. - [CORS](/config/projects/cors.llms.txt) — matching semantics and preflight behavior. - [Admin API](/operation/admin.llms.txt) — admin-scoped auth and every endpoint. Composition notes: auth strategies attach per project (and separately for admin); each strategy can carry its own `rateLimitBudget`, so per-user fairness is an auth-level concern while provider protection is an upstream-level budget. Exact fields and defaults live in each page's agent section. --- --- # Scale chains & providers > Source: https://docs.erpc.cloud/use-cases/scale-chains-and-providers > One config line per provider, every chain they support — and the best upstream wins each request. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Scale chains & providers Supporting a new chain shouldn't be a project. Give eRPC one provider API key and it unlocks every chain that vendor supports — upstreams appear lazily the first time a request needs them. Behind the scenes, a scoring engine continuously ranks all your endpoints on real latency, errors, and how far behind the chain tip they are, so the next request always goes to whoever deserves it most. Auditioning a brand-new provider? Mirror live traffic to it in shadow mode before trusting it with a single real response. - **[Providers](/config/projects/providers.llms.txt)** — 22 vendors built in — one key, all their chains. - **[Networks](/config/projects/networks.llms.txt)** — Per-chain settings and friendly aliases like /main/arbitrum. - **[Upstreams](/config/projects/upstreams.llms.txt)** — Fine-grained control over each endpoint when you need it. - **[Selection & scoring](/config/projects/selection-policies.llms.txt)** — Live health metrics pick the best upstream, every time. - **[Shadow upstreams](/config/projects/shadow-upstreams.llms.txt)** — Test new providers on real traffic with zero user impact. All of the above in one place — illustrative, not a tuned production config: **Config path:** `projects[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main # one key → every chain the vendor supports, upstreams appear lazily providers: - endpoint: alchemy://\${ALCHEMY_API_KEY} - endpoint: drpc://\${DRPC_API_KEY} upstreams: # mix in your own node alongside vendors - id: my-own-node endpoint: http://10.0.0.5:8545 # audition a new provider on 20% of live traffic, zero user impact - id: candidate-provider endpoint: https://rpc.new-vendor.xyz shadow: enabled: true sampleRate: 0.2 networks: - architecture: evm evm: { chainId: 1 } # /main/ethereum instead of /main/evm/1 alias: ethereum # who deserves the next request, re-evaluated continuously selectionPolicy: evalFunc: | (upstreams, ctx) => upstreams .preferTag('!tier:fallback') .sortByScore() ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", // one key → every chain the vendor supports, upstreams appear lazily providers: [ { endpoint: \`alchemy://\${process.env.ALCHEMY_API_KEY}\` }, { endpoint: \`drpc://\${process.env.DRPC_API_KEY}\` }, ], upstreams: [ // mix in your own node alongside vendors { id: "my-own-node", endpoint: "http://10.0.0.5:8545" }, // audition a new provider on 20% of live traffic, zero user impact { id: "candidate-provider", endpoint: "https://rpc.new-vendor.xyz", shadow: { enabled: true, sampleRate: 0.2 }, }, ], networks: [{ architecture: "evm", evm: { chainId: 1 }, // /main/ethereum instead of /main/evm/1 alias: "ethereum", // who deserves the next request, re-evaluated continuously selectionPolicy: { evalFunc: (upstreams, ctx) => upstreams.preferTag("!tier:fallback").sortByScore(), }, }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: add new chains and providers from scratch** ```text I want to add Alchemy and dRPC to my eRPC config so every chain they support is available automatically, with live scoring picking the best upstream per request. Work with my existing eRPC config. Read the full reference first: https://docs.erpc.cloud/use-cases/scale-chains-and-providers.llms.txt ``` **Prompt Example #2: shadow-test a new provider before trusting it** ```text I want to audition a new RPC vendor on real traffic before giving it any production requests. Configure a shadow upstream in my eRPC config that mirrors a sample of live traffic to the candidate and logs mismatches, with zero user impact. Read the reference first: https://docs.erpc.cloud/use-cases/scale-chains-and-providers.llms.txt ``` **Prompt Example #3: tune scoring so fallback providers stay idle unless needed** ```text I have primary and fallback providers in my eRPC config and I want the selection policy to always prefer primaries and only route to fallbacks when primaries are degraded. Walk through the scoring and tag config to make this work. Reference: https://docs.erpc.cloud/use-cases/scale-chains-and-providers.llms.txt ``` --- ### Scale chains — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions: - [Providers](/config/projects/providers.llms.txt) — every vendor's settings keys, URL shortcut schemes, lazy upstream generation. - [Networks](/config/projects/networks.llms.txt) — network defaults inheritance, aliases, lazy bootstrap. - [Upstreams](/config/projects/upstreams.llms.txt) — endpoint schemes, block availability gating, cordon reasons, defaults inheritance. - [Selection & scoring](/config/projects/selection-policies.llms.txt) — score components, multipliers, custom eval functions, tags. - [Shadow upstreams](/config/projects/shadow-upstreams.llms.txt) — mirroring, sampling, mismatch observability. Resolution chain an agent must know: provider shortcut endpoints expand to vendor-specific upstreams per network on first use; explicit `upstreams` and generated ones merge, with `upstreamDefaults` then upstream-level overrides applied; the selection policy orders the final set before every request. Full field tables live in each page's agent section. --- --- # See everything > Source: https://docs.erpc.cloud/use-cases/see-everything > Per-request metrics, traces, and honest healthchecks — know about problems before your users do. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # See everything When something degrades at 3 a.m., "the RPC feels slow" isn't a diagnosis. eRPC measures every request at every hop — which project, which chain, which upstream, which method, cache hit or miss, retried or hedged — and exposes it all as Prometheus metrics and OpenTelemetry traces. Grafana dashboards ship in the repo. Your on-call sees exactly which provider degraded and when, instead of guessing. - **[Monitoring & metrics](/operation/monitoring.llms.txt)** — The 20 metrics that matter on day one, plus ready-made dashboards. - **[Tracing & logging](/operation/tracing.llms.txt)** — Follow one request through every policy and upstream attempt. - **[Healthcheck](/operation/healthcheck.llms.txt)** — Readiness that tells your load balancer the truth. - **[Error taxonomy](/reference/errors.llms.txt)** — Every error normalized to a named code you can alert on. - **[Metrics reference](/reference/metrics.llms.txt)** — All 122 metrics, every label, in one table. All of the above in one place — illustrative, not a tuned production config: **Config path:** `(root)` **YAML — `erpc.yaml`:** ```yaml # structured logs with secret redaction logLevel: info # Prometheus on :4001/metrics metrics: enabled: true port: 4001 # one OTel trace per request, every hop; keep 10% of traces tracing: enabled: true protocol: grpc endpoint: otel-collector:4317 sampleRate: 0.1 # /healthcheck is always on; error codes are normalized automatically. ``` **TypeScript — `erpc.ts`:** ```typescript // structured logs with secret redaction logLevel: "info", // Prometheus on :4001/metrics metrics: { enabled: true, port: 4001 }, // one OTel trace per request, every hop; keep 10% of traces tracing: { enabled: true, protocol: "grpc", endpoint: "otel-collector:4317", sampleRate: 0.1, } ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: wire up Prometheus metrics and a Grafana dashboard** ```text I want to enable eRPC metrics so I can import the bundled Grafana dashboard and start monitoring upstream health and cache hit rates. Update my eRPC config with the metrics config and tell me which metrics matter most on day one. Read the full reference first: https://docs.erpc.cloud/use-cases/see-everything.llms.txt ``` **Prompt Example #2: add distributed tracing and structured logging** ```text I need to trace individual requests through eRPC all the way to the upstream to debug slow responses. Configure OpenTelemetry tracing and structured log output in my eRPC config with a sensible sample rate for production. Reference: https://docs.erpc.cloud/use-cases/see-everything.llms.txt ``` **Prompt Example #3: build alerts for upstream degradation and chain-tip lag** ```text I want Prometheus alerts that fire when an upstream starts erroring heavily or falls behind the chain tip. Walk me through the right metric names, labels, and threshold values to use, given my eRPC setup in my eRPC config. Reference: https://docs.erpc.cloud/use-cases/see-everything.llms.txt ``` --- ### See everything — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions: - [Monitoring & metrics](/operation/monitoring.llms.txt) — metrics server config, key operational metrics, Grafana dashboards. - [Tracing & logging](/operation/tracing.llms.txt) — OTel endpoint/sampling/protocol, span hierarchy, log levels, secret redaction. - [Healthcheck](/operation/healthcheck.llms.txt) — eval strategies, root vs per-project checks, k8s probes. - [Error taxonomy](/reference/errors.llms.txt) — every error code, retryability, HTTP status mapping. - [Metrics reference](/reference/metrics.llms.txt) — the complete 122-metric catalog with labels and cardinality warnings. Alerting hints for agents: upstream health is `erpc_upstream_request_errors_total` by `error`/`severity`, chain-tip freshness is `erpc_network_latest_block_timestamp_distance_seconds`, and benching events surface via cordon metrics — exact names, labels, and firing conditions are in the metrics reference agent section. --- --- # Survive provider outages > Source: https://docs.erpc.cloud/use-cases/survive-provider-outages > Keep serving traffic when an RPC provider slows down, rate-limits you, or disappears entirely. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Survive provider outages Every RPC provider has a bad day. With eRPC in front, your users never find out: slow answers get raced against a second provider, errors fail over automatically, and an upstream that keeps misbehaving is quietly benched until it recovers. You ship one endpoint; eRPC turns a pool of imperfect providers into something that behaves like a perfect one. - **[Retry](/config/failsafe/retry.llms.txt)** — Errors fail over to the next-best upstream, automatically. - **[Hedge](/config/failsafe/hedge.llms.txt)** — Slow request? A backup race starts before the user notices. - **[Timeout](/config/failsafe/timeout.llms.txt)** — Nothing hangs — every request has a hard ceiling. - **[Circuit breaker](/config/failsafe/circuit-breaker.llms.txt)** — Repeat offenders get benched until they behave again. - **[Cordoning](/operation/cordoning.llms.txt)** — See why an upstream was benched, or bench one yourself. - **[Healthcheck](/operation/healthcheck.llms.txt)** — Tell your load balancer the truth about readiness. All of the above in one place — illustrative, not a tuned production config: **Config path:** `projects[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main # applies to every chain in this project networkDefaults: failsafe: - matchMethod: "*" # nothing hangs: hard ceiling per request timeout: duration: 30s # errors fail over to the next-best upstream retry: maxAttempts: 3 # slow answers get raced at their p70 latency hedge: delay: { quantile: 0.7, min: 100ms, max: 2s } maxCount: 1 upstreamDefaults: failsafe: - matchMethod: "*" # one in-place retry per upstream before rotating away retry: maxAttempts: 1 # bench repeat offenders, probe again after 5m circuitBreaker: failureThresholdCount: 20 failureThresholdCapacity: 80 halfOpenAfter: 5m successThresholdCount: 8 # Cordoning is automatic (no config); /healthcheck reflects readiness. ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", // applies to every chain in this project networkDefaults: { failsafe: [{ matchMethod: "*", // nothing hangs: hard ceiling per request timeout: { duration: "30s" }, // errors fail over to the next-best upstream retry: { maxAttempts: 3 }, // slow answers get raced at their p70 latency hedge: { delay: { quantile: 0.7, min: "100ms", max: "2s" }, maxCount: 1 }, }], }, upstreamDefaults: { failsafe: [{ matchMethod: "*", // one in-place retry per upstream before rotating away retry: { maxAttempts: 1 }, // bench repeat offenders, probe again after 5m circuitBreaker: { failureThresholdCount: 20, failureThresholdCapacity: 80, halfOpenAfter: "5m", successThresholdCount: 8, }, }], }, }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: make my RPC layer survive provider outages** ```text I want my app to keep serving traffic even when an RPC provider slows down, rate-limits me, or goes offline. Configure eRPC in my eRPC config with retry, hedge, timeout, and circuit breaker so outages are transparent to my users. Read the reference and follow the child-page links inside it: https://docs.erpc.cloud/use-cases/survive-provider-outages.llms.txt ``` **Prompt Example #2: add circuit breaking to bench a flaky provider automatically** ```text One of my RPC providers is intermittently returning errors and degrading my app. Add a circuit breaker to my eRPC config so eRPC benches that upstream after repeated failures and probes it again once it recovers, without any manual intervention. Reference: https://docs.erpc.cloud/use-cases/survive-provider-outages.llms.txt ``` **Prompt Example #3: tune failover speed to minimize user-visible errors** ```text My eRPC config in my eRPC config already has retry and hedge configured but users still see occasional errors during provider incidents. Review the timeout, retry backoff, and hedge delay settings and tighten them so failover is as fast as possible without excessive upstream cost. Reference: https://docs.erpc.cloud/use-cases/survive-provider-outages.llms.txt ``` --- ### Survive outages — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions and combine policies per method: - [Retry](/config/failsafe/retry.llms.txt) — scopes (network vs upstream), empty-result handling, backoff math. - [Hedge](/config/failsafe/hedge.llms.txt) — fixed vs quantile delays, clamps, loser cancellation. - [Timeout](/config/failsafe/timeout.llms.txt) — the three-level timeout hierarchy and dynamic quantile mode. - [Circuit breaker](/config/failsafe/circuit-breaker.llms.txt) — thresholds, half-open probing, and how it complements selection-policy exclusion (cordoning is a third, independent mechanism). - [Cordoning](/operation/cordoning.llms.txt) — every cordon reason and how to inspect/override it. - [Healthcheck](/operation/healthcheck.llms.txt) — eval strategies and load-balancer integration. Composition rules an agent must know: failsafe entries are matched per request via `matchMethod`/`matchFinality`; at network scope the executor chain nests timeout(consensus(retry(hedge(upstreams)))); retries at network scope rotate across upstreams while upstream-scope retries re-attempt the same one. Full ordering and per-policy field tables are in each feature page's agent section. --- --- # Trust the data > Source: https://docs.erpc.cloud/use-cases/trust-the-data > Don't let one misbehaving node feed your app a wrong answer — verify, cross-check, and enforce integrity automatically. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Trust the data A wrong answer is worse than a slow one. RPC nodes lag behind the chain tip, prune history, and occasionally just lie. eRPC can ask several providers the same question and only accept an answer they agree on, refuse responses that would silently travel back in time, and split huge log queries so no provider quietly truncates your results. Your app sees one consistent chain, even when the nodes behind it disagree. - **[Consensus](/config/failsafe/consensus.llms.txt)** — Multiple providers vote; disagreement is detected, not served. - **[Integrity](/config/failsafe/integrity.llms.txt)** — No time travel: block numbers and logs can - **[Block tracking](/reference/evm/block-tracking.llms.txt)** — eRPC always knows each upstream - **[getLogs splitting](/reference/evm/getlogs-splitting.llms.txt)** — Huge queries split automatically — no more truncated events. - **[Method handlers](/reference/evm/method-handlers.llms.txt)** — Per-method smarts normalize quirks across providers. All of the above in one place — illustrative, not a tuned production config: **Config path:** `projects[].networks[]` **YAML — `erpc.yaml`:** ```yaml projects: - id: main networks: - architecture: evm evm: chainId: 1 # split bigger ranges automatically; on provider errors, split & retry getLogsMaxAllowedRange: 10000 getLogsSplitOnError: true directiveDefaults: # no silent time travel, no silently truncated log ranges enforceHighestBlock: true enforceGetLogsBlockRange: true failsafe: - matchMethod: "eth_getBalance|eth_call" # sensitive reads: providers must agree before you get an answer consensus: maxParticipants: 3 agreementThreshold: 2 disputeBehavior: returnError # Block tracking (latest/finalized per upstream) is always on — no config needed. ``` **TypeScript — `erpc.ts`:** ```typescript projects: [{ id: "main", networks: [{ architecture: "evm", evm: { chainId: 1, // split bigger ranges automatically; on provider errors, split & retry getLogsMaxAllowedRange: 10000, getLogsSplitOnError: true, }, directiveDefaults: { // no silent time travel, no silently truncated log ranges enforceHighestBlock: true, enforceGetLogsBlockRange: true, }, failsafe: [{ matchMethod: "eth_getBalance|eth_call", // sensitive reads: providers must agree before you get an answer consensus: { maxParticipants: 3, agreementThreshold: 2, disputeBehavior: "returnError", }, }], }], }] ``` ## Agent reference Copy one of these prompts into your AI agent session (Claude Code, Cursor, …) — each one points the agent at this page's machine-readable reference so it can do the work correctly: **Prompt Example #1: enforce consensus so one bad node can't mislead my app** ```text I want eRPC to require multiple providers to agree before returning sensitive reads like eth_getBalance and eth_call. Configure consensus in my eRPC config so disagreements surface as errors rather than silent wrong answers. Read the full reference first: https://docs.erpc.cloud/use-cases/trust-the-data.llms.txt ``` **Prompt Example #2: prevent silent block regressions and truncated log results** ```text My app occasionally gets stale block numbers and truncated eth_getLogs results from lagging nodes. Configure integrity checks and getLogs auto-splitting in my eRPC config to stop silent data quality issues. Reference: https://docs.erpc.cloud/use-cases/trust-the-data.llms.txt ``` **Prompt Example #3: debug why consensus is rejecting valid responses** ```text My eRPC consensus policy is returning dispute errors more than expected, and I want to understand whether it's genuine node disagreement or a config problem. Walk me through reading the relevant metrics and adjusting thresholds in my eRPC config. Reference: https://docs.erpc.cloud/use-cases/trust-the-data.llms.txt ``` --- ### Trust the data — agent starting points This page sells the outcome; implementation lives in the feature pages. Fetch their machine-readable companions: - [Consensus](/config/failsafe/consensus.llms.txt) — participant selection, agreement rules DSL, quotas, punishment, misbehavior export. - [Integrity](/config/failsafe/integrity.llms.txt) — highest-block enforcement, getLogs range checks, empty-result directives. - [Block tracking](/reference/evm/block-tracking.llms.txt) — state poller cadence, served tip, lag semantics (block-number deltas). - [getLogs splitting](/reference/evm/getlogs-splitting.llms.txt) — split triggers, sub-request failure semantics, merge/dedup rules. - [Method handlers](/reference/evm/method-handlers.llms.txt) — per-method normalization and edge cases. Key interaction: consensus and integrity both consume block-tracking state; getLogs splitting runs before failsafe policies so each sub-request is individually retried/hedged. Field-level tables and exact defaults live in each page's agent section. ## How it works **Hook dispatch model.** Four hook entry-points in [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go): - `HandleProjectPreForward` — runs at project layer before cache and upstream selection; handles `eth_call`, `eth_estimateGas`, `eth_chainId`, `eth_getLogs`, `trace_filter`/`arbtrace_filter`. - `HandleNetworkPreForward` — runs after upstream selection, can short-circuit; handles `eth_getLogs`, `eth_chainId`, `eth_blockNumber` (answered from the served tip), `trace_filter`/`arbtrace_filter`. - `HandleNetworkPostForward` — called after response comes back at network layer; handles `eth_blockNumber` (pinned to the served tip), `eth_getBlockByNumber`, `eth_getLogs`, `eth_sendRawTransaction`, `trace_filter`/`arbtrace_filter`. - `HandleUpstreamPostForward` — richest hook, called per-upstream; checks `MarkEmptyAsErrorMethods`, applies per-method validation, marks unexpected empties as `ErrEndpointMissingData`. **Block tag normalization.** [`NormalizeHttpJsonRpc`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go#L92) runs on every incoming JSON-RPC request: caches the numeric block number on the request, and when the tag is `"latest"` or `"finalized"` and the network has a known head, replaces the tag with a concrete `0x…` hex. Tags `"safe"` and `"pending"` are intentionally passed through unchanged. The `X-ERPC-Skip-Interpolation` directive or `skipInterpolation` request directive suppresses mutations while still caching the numeric block number. **Block reference extraction.** [`ExtractBlockReferenceFromRequest`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_ref.go#L18) and `ExtractBlockReferenceFromResponse` derive a `(blockRef, blockNumber)` pair. Special blockRef values: - `"*"` — wildcard for transaction/receipt hash lookups or composite range methods; uses `ConnectorReverseIndex` for cache lookups. - `"1"` — finalized-forever static data (chain ID, genesis block); cached indefinitely. - A numeric string (e.g. `"19827314"`) — concrete block; uses `ConnectorMainIndex`. **Empty-result handling.** [`upstreamPostForward_markUnexpectedEmpty`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go#L11) converts a `null`/empty result to `ErrEndpointMissingData` when: (1) the method is in `markEmptyAsErrorMethods`, (2) `req.Directives().RetryEmpty` is `true`, and (3) the block is NOT beyond the confidence head. When the network head is unknown the check fails open — empties are treated as retryable. **Syncing state.** A self-hosted node must return `eth_syncing: false` **four consecutive times** (`FullySyncedThreshold = 4` at [`architecture/evm/evm_state_poller.go:L21`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L21)) before eRPC stops syncing-check requests. One `syncing=true` resets the counter to 1. **Block-head rollback tolerance.** `DefaultToleratedBlockHeadRollback = 1024` at [`architecture/evm/evm_state_poller.go:L26`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go#L26) — the maximum block-head rollback the poller tolerates before treating it as a large rollback event (emits `erpc_upstream_block_head_large_rollback` gauge). A large rollback applies only once the lower head moves on, so a provider's node stuck far behind never pulls a head back. **Error normalizer precedence.** [`ExtractJsonRpcError`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L20) uses text-based matching in strict order: 1. Range-too-large → `ErrEndpointRequestTooLarge` 2. OP Stack sender rate limit → `ErrEndpointCapacityExceeded` (non-network-retryable) 3. Billing exhaustion (HTTP 402) → `ErrEndpointBillingIssue` 4. Rate limiting (HTTP 429 or text) → `ErrEndpointCapacityExceeded` 5. Block tag unsupported → `ErrEndpointClientSideException` 6. Missing data → `ErrEndpointMissingData` 7. Execution timeout → `ErrEndpointServerSideException` 8. EVM revert / VM exception → `ErrEndpointExecutionException` 9. Already-known / nonce-too-low → `ErrEndpointNonceException` 10. Insufficient funds → `ErrEndpointExecutionException` 11. Transaction rejected / out-of-gas → `ErrEndpointExecutionException` 12. Not-found method → `ErrEndpointUnsupported`; not-found block/state → `ErrEndpointMissingData` 13. Unsupported (HTTP 415/405, codes -32004/-32001) → `ErrEndpointUnsupported` 14. Malformed transaction (RLP errors) → `ErrEndpointClientSideException` (non-network-retryable) 15. Invalid type/map errors → `ErrEndpointClientSideException` (retryable) 16. Invalid args (code -32602/-32600) → `ErrEndpointClientSideException` 17. Unauthorized (HTTP 401/403) → `ErrEndpointUnauthorized` 18. Fallback → `ErrEndpointServerSideException` Special: a `0x08c379a0` prefix in a successful HTTP 200 result (`dt[1:11]`, not `dt[0:10]` — offset 0 is the JSON quote character) signals an EVM revert even with a 200 status. **gRPC error mapping.** BDS error codes take precedence when present in gRPC status details: `UNSUPPORTED_BLOCK_TAG`/`UNSUPPORTED_METHOD` → `ErrEndpointUnsupported`; `RANGE_OUTSIDE_AVAILABLE` → `ErrEndpointMissingData`; `RANGE_TOO_LARGE` → `ErrEndpointRequestTooLarge`; `RATE_LIMITED` → `ErrEndpointCapacityExceeded`; `TIMEOUT_ERROR`/`INTERNAL_ERROR` → `ErrEndpointServerSideException`. Without BDS: `Unimplemented` → Unsupported; `InvalidArgument` → ClientSide (non-network-retryable); `ResourceExhausted` → CapacityExceeded; `NotFound`/`OutOfRange` → MissingData. **ExecState counter model.** Per-request execution telemetry ([`common/exec_state.go`](https://github.com/erpc/erpc/blob/main/common/exec_state.go)): - `total Attempts = UpstreamAttempts + CacheAttempts` (`NetworkAttempts` is a rotation count, NOT summed — adding it would double-count) - `total Retries = UpstreamRetries + NetworkRetries + CacheRetries` - `total Hedges = UpstreamHedges + NetworkHedges + CacheHedges` - `Snapshot()` loads counters independently with no global lock — under high concurrency totals may briefly drift from component sums. **UpstreamAttemptOutcome values:** `success`, `empty`, `transport_error`, `server_error`, `client_error`, `rate_limited`, `missing_data`, `exec_revert`, `block_unavailable`, `breaker_open`, `cancelled`, `timeout`, `skipped`. **UpstreamSelectionReason values:** `primary`, `retry`, `hedge`, `consensus_slot`, `sweep`. ## Config schema All fields under `networks[*].evm.*`. Populated by `EvmNetworkConfig.SetDefaults()` ([`common/defaults.go:L2060`](https://github.com/erpc/erpc/blob/main/common/defaults.go#L2060)). | YAML path | Type | Default | Behavior | |---|---|---|---| | `evm.chainId` | int64 | required | EVM chain ID; used for `eth_chainId` responses and network ID (`evm:`). | | `evm.fallbackFinalityDepth` | int64 | `1024` | Depth used when finality cannot be determined dynamically. Block considered finalized if `latestBlock - blockNumber >= fallbackFinalityDepth`. | | `evm.fallbackStatePollerDebounce` | Duration | unset | Poll interval while the block time is not yet known; unset, 0.7s (the 1s cold block time × 0.7). | | `evm.integrity` | object | see below | **Deprecated** wrapper for directive-defaults; use `directiveDefaults` instead. | | `evm.integrity.enforceHighestBlock` | \*bool | `true` | Deprecated — migrates to `directiveDefaults.enforceHighestBlock`. | | `evm.integrity.enforceGetLogsBlockRange` | \*bool | `true` | Deprecated — migrates to `directiveDefaults.enforceGetLogsBlockRange`. | | `evm.integrity.enforceNonNullTaggedBlocks` | \*bool | `true` | Deprecated — migrates to `directiveDefaults.enforceNonNullTaggedBlocks`. | | `evm.getLogsMaxAllowedRange` | int64 | `30000` | Max block range for `eth_getLogs` before forced splitting. | | `evm.getLogsMaxAllowedAddresses` | int64 | `0` (unlimited) | Max address count in `eth_getLogs` filter. | | `evm.getLogsMaxAllowedTopics` | int64 | `0` (unlimited) | Max topic count in `eth_getLogs` filter. | | `evm.getLogsSplitOnError` | \*bool | `true` | When `eth_getLogs` gets a range-too-large error, split and retry. | | `evm.getLogsSplitConcurrency` | int | `10` | Max concurrent sub-requests when splitting `eth_getLogs`. | | `evm.traceFilterSplitOnError` | \*bool | `nil` (disabled) | When `trace_filter`/`arbtrace_filter` gets a range-too-large error, split and retry. Opt-in required. | | `evm.traceFilterSplitConcurrency` | int | `10` | Max concurrent sub-requests when splitting `trace_filter`. | | `evm.enforceBlockAvailability` | \*bool | `true` (nil resolves to true) | Gate requests to upstreams based on their known block bounds. | | `evm.maxRetryableBlockDistance` | \*int64 | `128` | Max block distance ahead of upstream's latest for which `block_unavailable` is retryable; larger distance is not retryable. | | `evm.markEmptyAsErrorMethods` | []string | 11 methods (see below) | Methods for which a `null`/empty upstream result is converted to `ErrEndpointMissingData` and retried. | | `evm.dynamicBlockTimeDebounceMultiplier` | \*float64 | `0.7` | Scales EMA block time to derive the state-poller debounce interval. Lower = fresher but more polling. | | `evm.blockUnavailableDelayMultiplier` | \*float64 | `1.0` | Multiplies EMA-estimated block time to derive dynamic retry delay on `ErrUpstreamBlockUnavailable` or `ErrEndpointMissingData`. Falls back to `failsafe[*].retry.emptyResultDelay` before the EMA warms up. | | `evm.idempotentTransactionBroadcast` | \*bool | `nil` (enabled) | When enabled, `eth_sendRawTransaction` converts "already known" errors to success and verifies "nonce too low" by polling `eth_getTransactionByHash`. Set to `false` to return raw upstream errors. | | `evm.emptyResultConfidence` | string | `"blockHead"` | Confidence level for empty-result retries: `"blockHead"` = retry empties for blocks ≤ latest head; `"finalizedBlock"` = stricter, only retry for blocks ≤ finalized head. | | `evm.maxFutureBlockRetryDistance` | \*int64 | — | **Deprecated** (yaml-only, tagged `json:"-"`). Replaced by `emptyResultConfidence`. A warning is logged and the value is ignored at runtime. | **Default `markEmptyAsErrorMethods` (11 methods):** `eth_blockNumber`, `eth_getBlockByNumber`, `eth_getTransactionByHash`, `eth_getTransactionByBlockHashAndIndex`, `eth_getTransactionByBlockNumberAndIndex`, `eth_getUncleByBlockHashAndIndex`, `eth_getUncleByBlockNumberAndIndex`, `debug_traceTransaction`, `trace_transaction`, `trace_block`, `trace_get`. Explicitly excluded: `eth_getBlockByHash` (subgraph upstreams commonly return null by hash), `eth_getTransactionReceipt` and `eth_getBlockReceipts` (pending tx / zero-tx blocks legitimately return empty). **Non-retryable write methods** (never network-retried): `eth_sendTransaction`, `eth_createAccessList`, `eth_submitTransaction`, `eth_submitWork`, `eth_newFilter`, `eth_newBlockFilter`, `eth_newPendingTransactionFilter`. Note: `eth_sendRawTransaction` is excluded because it has idempotency handling. ## Observability ### Prometheus metrics | Metric | Labels | Trigger | |---|---|---| | `erpc_cache_get_age_guard_reject_total` | project, network, method, connector, policy, ttl | Cached realtime result rejected: block timestamp age > TTL. | | `erpc_cache_get_success_hit_total` | project, network, category, connector, policy, ttl | Cache GET hit. | | `erpc_cache_get_success_miss_total` | project, network, category, connector, policy, ttl | Cache GET miss. | | `erpc_cache_get_error_total` | project, network, category, connector, policy, ttl, error | Cache GET connector error. | | `erpc_cache_get_skipped_total` | project, network, category | Cache GET skipped — no matching policy. | | `erpc_cache_set_success_total` | project, network, category, connector, policy, ttl | Cache SET succeeded. | | `erpc_cache_set_error_total` | project, network, category, connector, policy, ttl, error | Cache SET failed. | | `erpc_cache_set_skipped_total` | project, network, category, connector, policy, ttl | Cache SET skipped by policy. | | `erpc_cache_set_original_bytes_total` | project, network, category, connector, policy, ttl | Uncompressed bytes on cache SET. | | `erpc_cache_set_compressed_bytes_total` | project, network, category, connector, policy, ttl | Compressed bytes on cache SET. | | `erpc_upstream_attempt_outcome_total` | project, network, upstream, category, outcome, is_hedge, is_retry, finality | One increment per upstream attempt with its terminal outcome. | | `erpc_upstream_block_head_large_rollback` | project, vendor, network, upstream, finality | Block-head rollback exceeded `DefaultToleratedBlockHeadRollback` (1024 blocks). `finality` is the head axis (`latest`/`finalized`). | ### Trace spans | Span name | Source | |---|---| | `Project.PreForwardHook` | `HandleProjectPreForward` | | `Network.PreForwardHook` | `HandleNetworkPreForward` | | `Network.PostForwardHook` | `HandleNetworkPostForward` | | `Upstream.PreForwardHook` | `HandleUpstreamPreForward` | | `Upstream.PostForwardHook` | `HandleUpstreamPostForward` | | `Cache.Get` | `EvmJsonRpcCache.Get` — includes `network.id` attribute | | `Cache.Set` | `EvmJsonRpcCache.Set` — includes `upstream.id` attribute | | `Cache.FindGetPolicies` | Inside Cache.Get | | `Cache.GetForPolicy` | Per-connector goroutine — `cache.policy_summary`, `cache.connector_id`, `cache.method` | | `Evm.ExtractBlockReferenceFromRequest` | `block_ref.go` | | `Evm.ExtractBlockReferenceFromResponse` | `block_ref.go` | | `Upstream.PostForwardHook.eth_sendRawTransaction` | Idempotency path | ### Key log messages | Message | Level | When | |---|---|---| | `"interpolated block tag to concrete block number"` | Debug | `"latest"`/`"finalized"` tag resolved to hex; includes method, tag, resolvedHex, resolvedNumber, networkId. | | `"passed through block tag"` | Trace | Tag not interpolated. | | `"will not cache the response because we cannot resolve a block reference"` | Debug | Block ref empty on cache Set. | | `"rejecting cached result because block age exceeds policy TTL"` | Debug | Age guard rejection on cache Get. | | `"compressed cache value"` | Debug | Includes originalSize, compressedSize, savings%. | | `"cache connector errored during GET"` | Debug | Connector returned error in fan-out. | | `"returning cached response"` | Trace | Cache hit served. | ## Edge cases & gotchas 1. **`"safe"` and `"pending"` tags are never interpolated.** eRPC does not track the safe checkpoint or mempool state; these tags are passed through to the upstream unchanged. 2. **Block ref `"*"` for transaction lookups changes connector behavior.** When `blockRef == "*"`, the cache calls `ConnectorReverseIndex` instead of `ConnectorMainIndex`. Connectors that do not implement reverse indexing will miss these entries. 3. **`markEmptyAsErrorMethods` only fires when `RetryEmpty` directive is true.** Even if a method is in the list, the conversion to `ErrEndpointMissingData` is gated on `req.Directives().RetryEmpty`. Set `retryEmpty: true` in the failsafe retry policy or as a directive default for this to activate. 4. **An explicitly-set empty `markEmptyAsErrorMethods: []` disables the feature entirely** — including for methods in the default list. A non-nil empty slice is never replaced by the default set. 5. **Custom `markEmptyAsErrorMethods` completely replaces the default set** — there is no merge/extend. Setting `markEmptyAsErrorMethods: ["custom_method"]` means none of the default 11 methods will trigger empty-to-error conversion. 6. **`emptyResultBeyondConfidence` fails open.** When the network head is unknown (poller hasn't bootstrapped), it returns `false` — the empty result IS treated as retryable. This prevents spurious caching of null results during startup. 7. **`NetworkAttempts` is NOT summed into the total attempts.** `NetworkAttempts` counts upstream rotations; each rotation already generates one `UpstreamAttempts` increment. Summing both would double-count physical attempts. 8. **`ExecState.Snapshot()` is eventually consistent.** Each counter is loaded independently; under high concurrency `Snapshot().Attempts` may temporarily differ from `UpstreamAttempts + CacheAttempts`. 9. **Error normalizer: nonce/duplicate checks must precede rejected/gas checks.** Some providers use JSON-RPC code `-32003` for both "already known" and "out-of-gas". The normalizer checks "already known" and "nonce too low" first to ensure idempotency detection is not masked. 10. **OP Stack "sender is over rate limit" is non-network-retryable.** All providers route to the same OP Stack sequencer, so retrying on a different upstream would fail identically. 11. **Malformed RLP transactions are non-network-retryable.** No upstream would accept an invalid-encoding transaction. 12. **200-OK revert detection uses `dt[1:11]` not `dt[0:10]`.** The raw string from `GetResultString()` is JSON-encoded — `dt[0]` is the JSON double-quote character `"`. The `0x08c379a0` selector lives at positions 1-10. A check starting at index 0 would always fail. ([`architecture/evm/error_normalizer.go:L613`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go#L613)) 13. **cache.Get fan-out has a 30s defensive backstop** when the caller has no deadline. This prevents connection-pool leaks from hung connectors that lack a timeout of their own. 14. **Cache compression only occurs when compressed bytes are smaller than original bytes.** The compressor will not store the compressed form if compression overhead exceeds the savings. 15. **`deepCopyParams` is called only when changes are needed.** `NormalizeHttpJsonRpc` defers the copy until at least one mutation is confirmed; unchanged requests skip both the copy and the write-lock acquisition. 16. **JavaScript Runtime is single-threaded; each goroutine needs its own instance.** Sobek is not goroutine-safe. The selection policy system uses a per-goroutine pool at [`internal/policy/runtime_pool.go:L51`](https://github.com/erpc/erpc/blob/main/internal/policy/runtime_pool.go#L51). ## Source code entry points | File | Key symbols | |---|---| | [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go) | `HandleProjectPreForward`, `HandleNetworkPreForward`, `HandleNetworkPostForward`, `HandleUpstreamPostForward` | | [`architecture/evm/json_rpc.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc.go) | `NormalizeHttpJsonRpc`, `resolveBlockTagToHex`, `deepCopyParams` | | [`architecture/evm/block_ref.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/block_ref.go) | `ExtractBlockReferenceFromRequest`, `ExtractBlockReferenceFromResponse`, `ExtractBlockTimestampFromResponse` | | [`architecture/evm/error_normalizer.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/error_normalizer.go) | `ExtractJsonRpcError`, `ExtractGrpcError` | | [`architecture/evm/common.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/common.go) | `upstreamPostForward_markUnexpectedEmpty`, `emptyResultBeyondConfidence` | | [`architecture/evm/json_rpc_cache.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/json_rpc_cache.go) | `EvmJsonRpcCache` (GET/SET fan-out, policy matching, compression, age guard) | | [`architecture/evm/util.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/util.go) | `IsNonRetryableWriteMethod`, `IsMissingDataError` | | [`architecture/evm/evm_state_poller.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/evm_state_poller.go) | `EvmStatePoller`, `FullySyncedThreshold` (4), `DefaultToleratedBlockHeadRollback` (1024) | | [`architecture/evm/eth_sendRawTransaction.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/eth_sendRawTransaction.go) | Idempotency handling for `eth_sendRawTransaction` | | [`common/exec_state.go`](https://github.com/erpc/erpc/blob/main/common/exec_state.go) | `ExecState`, `UpstreamAttemptOutcome`, `UpstreamSelectionReason` | | [`common/architecture_evm.go`](https://github.com/erpc/erpc/blob/main/common/architecture_evm.go) | `EvmUpstream` interface, `EvmStatePoller` interface, `AvailbilityConfidence`, `EvmNodeType`, `EvmSyncingState` | | [`common/config.go`](https://github.com/erpc/erpc/blob/main/common/config.go) | `EvmNetworkConfig`, `EvmServedTipConfig`, `EvmIntegrityConfig` | | [`common/defaults.go`](https://github.com/erpc/erpc/blob/main/common/defaults.go) | `EvmNetworkConfig.SetDefaults()`, `DefaultMarkEmptyAsErrorMethods()` | | [`common/runtime.go`](https://github.com/erpc/erpc/blob/main/common/runtime.go) | `Runtime` (Sobek/V8-compatible JS engine wrapper) | --- --- # Why eRPC? > Source: https://docs.erpc.cloud/why > eRPC eliminates provider failures, stale data, and blind spots — one proxy in front of every RPC upstream you run. > Format: machine-readable markdown export of the docs page above. > All collapsible AI sections are inlined and fully expanded. # Why eRPC? Every RPC provider drops requests, returns stale blocks, and silently serves empty results. eRPC sits in front of all of them and fixes that — automatically. A request that hits eRPC gets auth-checked, deduplicated if identical calls are already in-flight, served from cache if the data is finalized, and then sent through a failsafe chain that retries, hedges, and falls over to a backup upstream — all before your application sees anything. If a provider has a slow moment, a hedge request races it silently. If it goes dark, retry and failover kick in. A single Prometheus endpoint covers the whole fleet. The result: provider outages stop reaching your users, historical data is never re-fetched, and you finally know which upstream is slow and why. --- ### Why eRPC — full agent reference ### How it works The request pipeline runs in a fixed order. An HTTP request arrives at `erpc/http_server.go`, is parsed (batch requests fan out concurrently), and forwarded through `RequestProcessor.ProcessUnary` (`erpc/request_processor.go:35-67`). That function resolves the project, validates the JSON-RPC body, authenticates the consumer, resolves the network, applies `DirectiveDefaults`, and calls `project.Forward`. **Project layer** (`erpc/projects.go`): acquires a project-level rate limit permit, fires `HandleProjectPreForward` (EVM hook for `eth_call`, `eth_estimateGas`, `eth_chainId`, `eth_getLogs`, `trace_filter` — may short-circuit with an early response), then delegates to `network.Forward`. **Network layer** (`erpc/networks.go:931-1603`): in order — 1. Static response check — matched entries return immediately without touching any upstream. 2. Multiplexing — identical in-flight requests are deduplicated; followers wait for the leader's result. 3. Cache read — a non-null hit is returned immediately and closes the multiplexer. 4. Upstream ordering — the policy engine scores upstreams on latency, error rate, throttling, and block lag, returning them in score order. 5. EVM pre-forward hook — range splitting for `eth_getLogs`, shortcircuit for `eth_chainId`, and `eth_blockNumber` answered from the served tip. 6. Future-block short-circuit — with `evm.shortCircuitFutureBlocks: true`, `eth_getBlockByNumber` requests for blocks beyond all upstream heads return a truthful `null` immediately. 7. Block-tag normalization — `"latest"` and `"finalized"` are replaced with concrete hex block numbers before the request reaches any upstream. 8. Failsafe execution — the selected executor runs `timeout(retry(hedge(runUpstreamSweep)))`, or `timeout(consensus(retry(hedge(tryOneUpstream))))` when consensus is enabled. 9. Async cache write — on a successful non-null response, the result is written to cache in a background goroutine with a 10-second deadline using the application context (not the request context, so client disconnects do not abort the write). 10. State poller enrichment — for `eth_getBlockByNumber?latest/finalized` and `eth_blockNumber`, the returned block number is fed back to the upstream's `EvmStatePoller`. **Failsafe nesting order** is always fixed regardless of config order: ``` timeout └─ [consensus] └─ retry └─ hedge └─ upstream sweep ``` Timeout wraps the entire invocation so a single wall-clock budget governs all retry and hedge attempts. Retry sits outside hedge so a hedge race counts as one retry attempt. Consensus sits outside both because it orchestrates multiple upstream slots, each of which can independently retry and hedge. **Upstream sweep loop** (`erpc/networks.go:1226-1407`): iterates upstreams in score order, skipping permanently errored ones and those blocked by `UseUpstream` directive filters. For each candidate, block availability is gated — requests for blocks within 128 blocks of the upstream's latest are retryable; beyond that, the upstream is permanently skipped for this request. Winners set `Attempts/Retries/Hedges` on the response. **Response ID normalization** rewrites the JSON-RPC `id` field byte-for-byte using `IDRawBytes()` to preserve large 64-bit integers that cannot be round-tripped through `float64`. ### Config schema The `/why` page is an overview. Each capability has its own config surface: | Config area | Canonical page | |---|---| | Failsafe (timeout / retry / hedge / consensus) | [/config/failsafe](/config/failsafe.llms.txt) | | Caching policies and storage drivers | [/use-cases/cut-costs-and-latency](/use-cases/cut-costs-and-latency.llms.txt) | | Upstream selection and scoring | [/config/projects/selection-policies](/config/projects/selection-policies.llms.txt) | | EVM block tracking and served tip | [/reference/evm/block-tracking](/reference/evm/block-tracking.llms.txt) | | Multiplexing | `networks[].multiplexing.enabled` (bool, default `false`) — [/config/projects/networks](/config/projects/networks.llms.txt) | | Rate limiters | [/config/rate-limiters](/config/rate-limiters.llms.txt) | | Auth | [/config/auth](/config/auth.llms.txt) | ### Worked examples **1. Survive a provider outage with automatic failover.** Two upstreams configured; retry with 3 attempts and a hedge after 200ms means a down provider is bypassed within one request cycle, with no client timeout fired: See [/use-cases/survive-provider-outages](/use-cases/survive-provider-outages.llms.txt) for a full annotated config. **2. Eliminate re-fetches for finalized data.** Cache all finalized blocks to Redis so `eth_getBlockByNumber("0x1234567")` only hits an upstream once ever. Block-tag normalization ensures `eth_getBlockByNumber("latest")` is stored under its concrete number, not the `"latest"` tag: See [/use-cases/cut-costs-and-latency](/use-cases/cut-costs-and-latency.llms.txt) for cache policy configuration. **3. Multi-chain fan-out with per-network failsafe tuning.** Each `networks[]` entry carries its own `failsafe[]` array, so Ethereum mainnet can use aggressive hedging while a cheaper L2 uses a simple retry-only policy — all in a single eRPC instance. **4. Request deduplication under thundering herd.** When many callers request the same `eth_getLogs` range simultaneously (common in indexer deployments), multiplexing (`networks[].multiplexing.enabled: true`) collapses them into one upstream call. Every caller receives a copy of the result with their own request ID patched in. ### Request/response behavior - Every response carries `X-ERPC-*` diagnostic headers: `X-ERPC-Attempts`, `X-ERPC-Upstream-Retries`, `X-ERPC-Upstream-Hedges`, `X-ERPC-Cache` (HIT/MISS), `X-ERPC-Upstream` (winning upstream ID), `X-ERPC-Duration`. Source: [`erpc/http_server.go:L1105`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go#L1105) - HTTP status follows JSON-RPC spec: 200 for all JSON-RPC responses (including errors); transport-level failures get appropriate 4xx/5xx codes. - Batch requests are dispatched concurrently; all results are re-assembled in order before writing the response. - eRPC's own requests (state pollers, chainId probes, state probes, subscription calls) set `UpstreamPolicies` to a value other than `Configured` — they bypass retry, hedge, and circuit breaker policies; only per-attempt timeout applies. - Request directives (`X-ERPC-Use-Upstream`, `X-ERPC-Skip-Cache-Read`, `X-ERPC-Retry-Empty`, etc.) override network `directiveDefaults` on a per-request basis. See the directive reference in [KB 01](/reference/architecture.llms.txt). ### Best practices - Start with the [use-cases](/use-cases.llms.txt) pages — each one maps a concrete operational goal (survive outages, cut costs, low-latency reads) to a minimal working config. - Enable multiplexing (`networks[].multiplexing.enabled: true`) for any network that receives burst traffic or shared infrastructure queries; the deduplication is zero-cost when no duplicates arrive. - Leave `evm.enforceBlockAvailability` at its default (enabled) — it prevents requests from being sent to upstreams that haven't indexed the requested block yet, turning silent wrong-data scenarios into handled retries. - Pair hedging with [rate limiters](/config/rate-limiters.llms.txt) on paid upstreams — each hedge fires a real request; without a budget cap, a spike can trigger overage charges. - Use `server.executionHeaders: "summary"` in production to reduce per-response header size while keeping attempt/retry/hedge counters; use `"all"` only for debugging (it emits per-attempt upstream trace strings). - The async cache write uses `appCtx`, not the request context — a client disconnect or timeout does NOT abort a cache write in progress. The 10-second limit governs the write itself. ### Edge cases & gotchas 1. **`ApplyDirectiveDefaults` is a no-op if directives are already set.** The HTTP server sets directives before `Network.Forward` calls `ApplyDirectiveDefaults` defensively. A request constructed programmatically (gRPC, internal) without HTTP headers uses the network defaults unchanged. Source: `common/request.go:563-565` 2. **Multiplexer followers may arrive during leader teardown.** The `LoadOrStore` loop retries — a late follower either joins a new leader slot or becomes the new leader itself. Source: `erpc/networks.go:2017-2025` 3. **`"safe"` and `"pending"` block tags are NOT interpolated.** eRPC does not track the safe checkpoint or mempool state; these tags pass through to upstreams unchanged. Source: `architecture/evm/json_rpc.go:L76-L82` 4. **Composite requests skip network-scope retry and hedge.** Range-split `eth_getLogs` sub-requests and query shim sub-requests bypass both policies to prevent exponential sub-request amplification. Source: `erpc/network_executor.go:378-380`, `521-526` 5. **`ErrNoUpstreamsLeftToSelect` masking on retry.** After the first retry round, consumed upstreams may all be marked, producing a bare `ErrNoUpstreamsLeftToSelect` that loses the root cause. The executor tracks `firstInformativeErr` and surfaces it in the final `ErrFailsafeRetryExceeded`. Source: `erpc/network_executor.go:265-284` 6. **Cache write panics are recovered.** Panics in the async cache-write goroutine are caught and reported via `erpc_unexpected_panic_total{scope="cache-set"}` — the process does not crash. Source: `erpc/networks.go:1496-1508` 7. **Future-block short-circuit is per-method.** Only `eth_getBlockByNumber` with a concrete block number triggers the early-null return. Other methods (e.g. `eth_getTransactionReceipt`) go through the normal upstream sweep and rely on block-availability gating per upstream. ### Observability | Metric | Type | Labels | When it fires | |---|---|---|---| | `erpc_network_requests_received_total` | counter | project, network, category, finality, user, agent_name | Request enters `project.Forward` | | `erpc_network_successful_request_total` | counter | project, network, vendor, upstream, category, attempt, finality, emptyish, user, agent_name | `project.Forward` returns non-error | | `erpc_network_failed_request_total` | counter | project, network, category, attempt, error, severity, finality, user, agent_name | `project.Forward` returns error | | `erpc_network_request_duration_seconds` | histogram | project, network, vendor, upstream, category, finality, user | Per-request total duration (success and error) | | `erpc_network_multiplexed_requests_total` | counter | project, network, category | Follower piggybacks on in-flight leader | | `erpc_network_retry_attempt_total` | counter | project, network, category, reason, finality | Each network-scope retry attempt | | `erpc_network_hedged_request_total` | counter | project, network, upstream, category, hedgeCount, finality, user, agent_name | Hedge attempt fired to a specific upstream | | `erpc_network_hedge_winner_total` | counter | project, network, upstream, category, finality | Upstream won a hedge race | | `erpc_network_timeout_fired_total` | counter | project, network, category, finality, scope | Network-scope timeout fired | | `erpc_network_static_response_served_total` | counter | project, network, category | Static response matched | Key OTel spans: `Network.Forward`, `Project.Forward`, `PolicyEngine.GetOrdered`, `Network.forwardAttempt`, `Network.UpstreamLoop`, `Network.TryForward`, `Cache.Get`, `Cache.Set`. Source: `erpc/networks.go`, `erpc/projects.go`, `architecture/evm/json_rpc_cache.go`. ### Source code entry points - [`erpc/request_processor.go`](https://github.com/erpc/erpc/blob/main/erpc/request_processor.go) — unified entry point for unary and gRPC stream requests; wires project, auth, and network resolution - [`erpc/network_executor.go:L70-L200`](https://github.com/erpc/erpc/blob/main/erpc/network_executor.go#L70-L200) — failsafe policy orchestration; fixed timeout/consensus/retry/hedge nesting - [`erpc/networks.go:L931-L1603`](https://github.com/erpc/erpc/blob/main/erpc/networks.go#L931-L1603) — `Network.Forward`: static check, multiplexing, cache read, upstream ordering, block availability gating, failsafe execution, async cache write - [`erpc/projects.go`](https://github.com/erpc/erpc/blob/main/erpc/projects.go) — project-level rate limiting, metrics, EVM hook wrappers - [`erpc/http_server.go`](https://github.com/erpc/erpc/blob/main/erpc/http_server.go) — HTTP ingress, batch dispatch, directive enrichment, `X-ERPC-*` response header emission - [`architecture/evm/hooks.go`](https://github.com/erpc/erpc/blob/main/architecture/evm/hooks.go) — four EVM hook dispatch entry-points (HandleProjectPreForward, HandleNetworkPreForward, HandleNetworkPostForward, HandleUpstreamPostForward) - [`common/request.go`](https://github.com/erpc/erpc/blob/main/common/request.go) — directive system, upstream round-robin selection, exec state, finality caching ### Related pages - [Survive provider outages](/use-cases/survive-provider-outages.llms.txt) — the canonical failover use case - [Cut costs and latency](/use-cases/cut-costs-and-latency.llms.txt) — caching and deduplication in practice - [Failsafe overview](/config/failsafe.llms.txt) — timeout, retry, hedge, consensus config - [Selection policies](/config/projects/selection-policies.llms.txt) — upstream scoring and ordering - [Rate limiters](/config/rate-limiters.llms.txt) — budget caps for upstream and project traffic - [Auth](/config/auth.llms.txt) — consumer authentication and access control - [Networks config](/config/projects/networks.llms.txt) — multiplexing, directiveDefaults, EVM block tracking ---