Blockchain infrastructure · 5 MIN READ

Several RPC providers: pin reads to one block hash, outvote a lagging or lying node, retry within bounds

Pin multi-provider reads to an agreed block hash, quarantine providers that disagree or lag, and fail over with bounded retries and backoff.

Production services rarely trust one JSON-RPC endpoint: providers have outages, rate limits, stale replicas and occasionally wrong data. Adding a second URL does not fix that by itself. Reads must agree on which block they describe, a provider that disagrees must be detected rather than averaged in, and retries must stop before they turn a provider incident into your outage. This lesson models providers in memory behind the same interface ethclient implements.

blockchain · A MAP OF THE IDEA

  1. Verify chain per provider
  2. Pin block hash by majority
  3. Read only at pinned hash
  4. Bounded retry, then failover

Useful when

  • A lagging or forked provider is detected instead of silently trusted.
  • Fakes behind the ethclient interface make outage drills instant and deterministic.

Watch out

  • Agreement among providers that share one upstream is a single vote.
  • AtHash helpers send requireCanonical false; use the raw client when it matters.

Implementation & operation cost: Extra header calls per pinned read, a provider pool with health state and metrics, and a retry policy that must be tuned and reviewed.

01

Latest is not a coordinate

Two providers asked for latest at the same moment can answer for different blocks, and a load-balanced endpoint can serve two consecutive calls from two different backends. A balance from one call and an allowance from the next may then describe states that never coexisted. Pick the block first, usually head minus your confirmation depth or the finalized tag, resolve it to a hash, and make every later read refer to that hash. A read by number lets a provider on another fork answer quietly from its own state; a read by hash, as EIP-1898 allows, fails loudly when the provider does not have that block. The rpc-boundaries lesson already verifies the chain ID and bounds each call; pinning is the next layer.

02

Outvote, then fail over

The program defines Reader as the two ethclient methods the service needs, and a compile-time assertion proves that *ethclient.Client satisfies it, so fakes and the real client are interchangeable. Five fake providers cover the cases: three agree on block 100, one serves a forked header, one is still at block 99, and the first healthy one is rate limited. pin computes each header hash locally and requires a strict majority of all configured providers; balance then reads at the pinned hash with bounded per-provider retries.

go
package main

import (
	"context"
	"errors"
	"fmt"
	"math/big"
	"net/http"
	"time"

	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethclient"
	"github.com/ethereum/go-ethereum/rpc"
)

// Reader is the slice of *ethclient.Client this service depends on.
type Reader interface {
	HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
	BalanceAtHash(ctx context.Context, account common.Address, block common.Hash) (*big.Int, error)
}

var _ Reader = (*ethclient.Client)(nil) // the real client fits the same interface

type Provider struct {
	Name string
	Reader
}

// fake is an in-memory node: a header per height, a balance per block hash and a
// script of failures returned before any balance read succeeds.
type fake struct {
	headers  map[uint64]*types.Header
	balances map[common.Hash]*big.Int
	failures []error
}

func (f *fake) HeaderByNumber(ctx context.Context, n *big.Int) (*types.Header, error) {
	if h, ok := f.headers[n.Uint64()]; ok {
		return h, nil
	}
	return nil, ethereum.NotFound // what ethclient returns for a null block
}

func (f *fake) BalanceAtHash(ctx context.Context, _ common.Address, block common.Hash) (*big.Int, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	if len(f.failures) > 0 {
		err := f.failures[0]
		f.failures = f.failures[1:]
		return nil, err
	}
	if b, ok := f.balances[block]; ok {
		return new(big.Int).Set(b), nil
	}
	return nil, errors.New("header for hash not found")
}

// pin asks every provider for the header at n and accepts a hash only if a strict
// majority of all configured providers return it.
func pin(ctx context.Context, ps []Provider, n uint64) (common.Hash, []Provider, error) {
	answers := make([]common.Hash, len(ps))
	votes := map[common.Hash]int{}
	var best common.Hash
	for i, p := range ps {
		h, err := p.HeaderByNumber(ctx, new(big.Int).SetUint64(n))
		if err != nil {
			fmt.Printf("%s: no header %d (%v), excluded\n", p.Name, n, err)
			continue
		}
		answers[i] = h.Hash() // computed locally from the returned header fields
		votes[answers[i]]++
		if votes[answers[i]] > votes[best] {
			best = answers[i]
		}
	}
	if 2*votes[best] <= len(ps) {
		return common.Hash{}, nil, fmt.Errorf("no majority for block %d", n)
	}
	var agreeing []Provider
	for i, p := range ps {
		switch answers[i] {
		case best:
			agreeing = append(agreeing, p)
		case common.Hash{}:
		default:
			fmt.Printf("%s: reports %s at %d, quarantined\n", p.Name, answers[i].TerminalString(), n)
		}
	}
	return best, agreeing, nil
}

func retryable(err error) bool {
	var httpErr rpc.HTTPError
	if errors.As(err, &httpErr) {
		return httpErr.StatusCode == http.StatusTooManyRequests || httpErr.StatusCode >= 500
	}
	return errors.Is(err, context.DeadlineExceeded)
}

type Backoff struct {
	Attempts   int
	Base, Max  time.Duration
	Sleep      func(context.Context, time.Duration) error
	PerAttempt time.Duration
}

// balance tries each agreeing provider in order with bounded, growing waits.
func balance(ctx context.Context, ps []Provider, b Backoff, a common.Address, block common.Hash) (*big.Int, error) {
	for _, p := range ps {
		wait := b.Base
		for attempt := 1; attempt <= b.Attempts; attempt++ {
			callCtx, cancel := context.WithTimeout(ctx, b.PerAttempt)
			v, err := p.BalanceAtHash(callCtx, a, block)
			cancel()
			if err == nil {
				fmt.Printf("%s: balance at %s = %s wei\n", p.Name, block.TerminalString(), v)
				return v, nil
			}
			if !retryable(err) || attempt == b.Attempts {
				fmt.Printf("%s: attempt %d: %v, next provider\n", p.Name, attempt, err)
				break
			}
			fmt.Printf("%s: attempt %d: %v, retry in %v\n", p.Name, attempt, err, wait)
			if err := b.Sleep(ctx, wait); err != nil {
				return nil, err
			}
			wait = min(2*wait, b.Max)
		}
	}
	return nil, errors.New("all providers failed")
}

func main() {
	header := func(n uint64, root byte) *types.Header {
		return &types.Header{Number: new(big.Int).SetUint64(n), Difficulty: new(big.Int), Root: common.Hash{root}}
	}
	canonical, fork := header(100, 0xaa), header(100, 0xbb)
	limited := rpc.HTTPError{StatusCode: 429, Status: "429 Too Many Requests"}
	funds := map[common.Hash]*big.Int{canonical.Hash(): big.NewInt(5_000_000_000_000_000_000)}

	providers := []Provider{
		{"alpha", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds,
			failures: []error{limited, limited, limited}}},
		{"beta", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds}},
		{"gamma", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds}},
		{"delta", &fake{headers: map[uint64]*types.Header{100: fork}}},
		{"epsilon", &fake{headers: map[uint64]*types.Header{99: header(99, 0xaa)}}},
	}
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	hash, agreeing, err := pin(ctx, providers, 100)
	if err != nil {
		panic(err)
	}
	fmt.Printf("pinned block 100 = %s, agreed by %d of %d\n", hash.TerminalString(), len(agreeing), len(providers))

	var slept time.Duration
	policy := Backoff{Attempts: 3, Base: 100 * time.Millisecond, Max: time.Second, PerAttempt: 500 * time.Millisecond,
		Sleep: func(_ context.Context, d time.Duration) error { slept += d; return nil }}
	if _, err := balance(ctx, agreeing, policy, common.HexToAddress("0xbb"), hash); err != nil {
		panic(err)
	}
	fmt.Println("total backoff:", slept)
}
Read the code

Header.Hash() is keccak256 over the RLP of the returned fields, so the client computes it rather than trusting a quoted hash. epsilon has no header 100 and returns ethereum.NotFound, which is what ethclient reports for a null block, so it is excluded rather than counted as dissent. delta's header differs and so does its hash; it is quarantined. Three of five agree, a strict majority. alpha answers every balance call with an rpc.HTTPError of status 429; retryable treats 429 and 5xx as transient, waits 100ms and then 200ms, and after the third attempt moves on. beta answers at the pinned hash. Sleep is injected, so the run is instant and the total backoff of 300ms can be asserted instead of waited for.

03

Wire real clients behind the same interface

With real endpoints the shape stays the same: dial each provider with an explicit HTTP client, verify its chain ID before it joins the pool, and wrap it with a client-side limiter so your own traffic stays under the provider's quota instead of discovering the quota through 429 responses.

go
type limited struct {
	Reader
	lim *rate.Limiter
}

func (l limited) BalanceAtHash(ctx context.Context, a common.Address, h common.Hash) (*big.Int, error) {
	if err := l.lim.Wait(ctx); err != nil { // errors out if the wait would pass the deadline
		return nil, err
	}
	return l.Reader.BalanceAtHash(ctx, a, h)
}

func dial(ctx context.Context, name, url string, want *big.Int) (Provider, error) {
	rc, err := rpc.DialOptions(ctx, url, rpc.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}))
	if err != nil {
		return Provider{}, err
	}
	client := ethclient.NewClient(rc)
	id, err := client.ChainID(ctx)
	if err != nil || id.Cmp(want) != 0 {
		client.Close()
		return Provider{}, fmt.Errorf("%s: chain %v, want %v (err %v)", name, id, want, err)
	}
	return Provider{Name: name, Reader: limited{client, rate.NewLimiter(20, 5)}}, nil
}

// After dialing: choose the coordinate once, then confirm it across providers.
fin, err := providers[0].HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber)))
if err != nil {
	return err
}
hash, agreeing, err := pin(ctx, providers, fin.Number.Uint64())
Read the code

This fragment dials real endpoints, so run it in your own native environment with URLs from configuration and never with credentials in source. rpc.WithHTTPClient supplies an http.Client whose Timeout caps every HTTP exchange, in addition to per-call contexts. A provider reporting another chain ID never joins the pool. rate.NewLimiter(20, 5) allows 20 requests per second with bursts of 5, and Wait returns an error instead of sleeping past the context deadline. rpc.FinalizedBlockNumber selects the finalized tag; pin then confirms that block hash across providers before any read.

04

Quorum, canonical hashes and retry budgets

Agreement is evidence only if the providers are independent: three brands reselling one upstream are one vote, and the strongest single check is a node you operate or a light client that verifies consensus. Pinning by hash has a subtlety in this release: ethclient's BalanceAtHash, CallContractAtHash and the other AtHash helpers send requireCanonical as false, so a node may answer from a block it still stores after a reorg removed it from the canonical chain. When that matters, call the raw rpc.Client with rpc.BlockNumberOrHashWithHash(hash, true); geth then fails with hash is not currently canonical. Retry only reads and only transient classes (429, 5xx, timeouts), with a per-attempt timeout, an attempt cap per provider and an overall deadline, and add random jitter so many workers do not retry in lockstep; the example omits jitter to stay deterministic. go-ethereum's HTTPError carries the status and body but not response headers, so honoring Retry-After needs a custom http.RoundTripper. Never fail over a send by assuming a timeout meant failure; the raw-transactions lesson explains why.

05

Test the pool like a distributed system

Because the service depends on an interface, failure modes are cheap to script: a provider one block behind, one on a fork, one returning 429 for a minute, one that hangs until the context expires, one that returns a malformed header, and all of them at once. Assert outcomes rather than just errors: which provider was quarantined, how many attempts ran, the total backoff, and that no read used a block other than the pinned hash. Export the same facts as production metrics: per-provider error rate by class, head lag in blocks, disagreements per hour and retry budget spent. A disagreement is an incident to investigate, not noise to retry away.

TAKE THIS WITH YOU

Choose one block, resolve it to a hash that a majority of independent providers agree on, read only at that hash, and retry transient failures within a fixed budget before failing over.

Check your understanding

Two providers answer latest for different blocks. What makes reads across several providers consistent?

Go to the source

Progress stays in this browser. No account needed.