How to Build Reliable RPC Infrastructure for DeFi Protocols

blog_author_logo
GETBLOCK

May 18, 2026

9 min read

How to Build Reliable RPC Infrastructure for DeFi Protocols

DeFi is the one category of blockchain application where RPC infrastructure isn't just important, but it's existential. A 30-second RPC outage on a lending protocol can mean failed liquidations and bad debt accumulating in the system. A slow endpoint on a DEX means your users see stale prices while competitors show live ones. A dropped WebSocket connection on a bridge means cross-chain transfers get stuck mid-flight.

The stakes are higher here than anywhere else in crypto infrastructure, and the margin for error is thinner. This guide covers how to architect your DeFi backend for reliability at every stage, from early-stage MVP to multi-chain protocol with millions in TVL.

Understanding What Different DeFi Applications Need

Not all DeFi protocols stress RPC infrastructure in the same way. A DEX and a lending protocol both need reliable blockchain access, but the shape of that demand is completely different. Understanding your protocol's specific access pattern is the first step toward building infrastructure that actually works.

Decentralized Exchange(DEXes) and Automated Market Maker (AMMs)

These need low-latency pool reads and fast transaction submission. Price accuracy depends on how quickly your frontend can read the current pool state, and trade execution depends on how fast your backend can submit transactions to the network. WebSocket connections for real-time swap event monitoring are essential; without them, your price feeds will always lag the actual pool state.

Lending protocols

This has a different critical path: health factor monitoring. You need to continuously monitor borrower positions to identify liquidation opportunities before they lead to bad debt. This means high-frequency eth_call operations on lending pool contracts, plus access to archived data to calculate historical interest rates and utilization.

Yield aggregators

They are the most RPC-diverse category. They need to read data from multiple protocols simultaneously, such as checking APYs across Aave, Compound, Morpho, and others, often across multiple chains. Batch read efficiency matters more here than raw latency.

Bridges

They need multi-chain WebSocket event monitoring and reliable transaction confirmation tracking on both source and destination chains. Uptime requirements are stringent because a bridge outage can leave user funds stranded mid-transfer.

Ready to access blockchain data with flexible pricing? Sign up for GetBlock and start building with our RPC endpoints today.

Single-Chain Architecture: From MVP to Production

Most DeFi protocols start on a single chain and expand later. The architecture evolves in two stages.

Stage One: Shared Nodes for Early Development

When you're building your Minimum Viable Product (MVP) or running with under 50,000 daily active users, shared RPC endpoints are the right choice. The architecture is simple: your frontend connects directly to user wallets, while your backend server handles all blockchain reads and writes via a shared RPC endpoint.

1

2

3

4

5

import { FallbackProvider, JsonRpcProvider } from "ethers";
//Simple setup: one shared endpoint
const provider = new JsonRpcProvider(
  "https://go.getblock.io/<YOUR_ACCESS_TOKEN>/"
);

This works well for early-stage development because you're not competing with other protocols for liquidation opportunities, your user base is manageable, and the cost is minimal. GetBlock's free tier provides enough capacity to build and test using real mainnet data.

Stage Two: Dedicated Nodes with Failover

Once your protocol holds real Total Value Locked (TVL), reliability becomes non-negotiable. The production architecture adds a dedicated node as the primary endpoint and keeps a shared node as a fallback. If the dedicated node ever has an issue, your backend automatically fails over to the shared endpoint your protocol never goes dark.

1

2

3

4

5

6

7

8

9

10

11

12

import { FallbackProvider, JsonRpcProvider } from "ethers";
const dedicated = new JsonRpcProvider(
  "https://go.getblock.io/<DEDICATED_TOKEN>/"
);
const shared = new JsonRpcProvider(
  "https://go.getblock.io/<SHARED_TOKEN>/"
);
// Ethers.js FallbackProvider handles automatic failover
const provider = new FallbackProvider([
  { provider: dedicated, priority: 1, stallTimeout: 2000 },
  { provider: shared, priority: 2, stallTimeout: 5000 },
]);

The stallTimeout values are important here. Setting the dedicated node's stall timeout to 2 seconds means that if it doesn't respond within 2 seconds, the FallbackProvider immediately tries the shared node instead. For DeFi, 2 seconds of unresponsiveness is already too long; you'd rather fail over fast than wait for a slow response.

Multi-Chain Architecture

For protocols deployed across multiple chains e.g the way Aave operates on Ethereum, Polygon, Arbitrum, Optimism, and Base simultaneously, each chain gets its own RPC connection with its own configuration:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

from web3 import Web3;
CHAINS = {
   "ethereum": {
      "rpc": "https://go.getblock.io/<ACCESS_TOKEN>/",
      "chain_id": 1,
        "block_time": 12,
},
    "polygon": {
rpc": "https://go.getblock.io/<ACCESS_TOKEN>/",
   "chain_id": 137,
  "block_time": 2,
    },
   "arbitrum": {
        "rpc": "https://go.getblock.io/<ACCESS_TOKEN>/",
        "chain_id": 42161,
        "block_time": 0.25,
    },
   "base": {
        "rpc": "https://go.getblock.io/<ACCESS_TOKEN>/",
        "chain_id": 8453,
      "block_time": 2,
    },
}
# Create a Web3 instance for each chain
providers = {
    name: Web3(Web3.HTTPProvider(config["rpc"]))
    for name, config in CHAINS.items()
}

The block_time configuration affects how your polling intervals are tuned. Arbitrum produces blocks every 0.25 seconds, so polling for new events every 12 seconds (Ethereum's block time) would mean missing 47 out of every 48 blocks. Each chain needs monitoring loops calibrated to its own cadence.

GetBlock supports over 130 chains from a single dashboard — one account, one billing relationship, one support team. This becomes a significant operational advantage when you're managing RPC connections to five or more chains simultaneously. You won't need to juggle multiple providers as you expand to new chains.

Common DeFi RPC Patterns

1. Liquidation Monitoring

This is the highest-stakes RPC operation in DeFi. Lending protocols need to continuously check borrower health factors and execute liquidations before positions create bad debt. Speed and reliability here directly impact protocol solvency.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import asyncio
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("https://go.getblock.io/<YOUR_ACCESS_TOKEN>/"))
lending_pool = w3.eth.contract(
    address=LENDING_POOL_ADDR, abi=LENDING_POOL_ABI
)
async def monitor_liquidations():async def monitor_liquidations():
   # """Continuously check health factors for liquidation opportunities."""
    borrowers = await get_active_borrowers()
  for borrower in borrowers:
        user_data = lending_pool.functions.getUserAccountData(
            borrower
        ).call()
        health_factor = user_data[5] / 1e18
        if health_factor < 1.0:
            print(f"⚠️ Liquidatable: {borrower}, HF: {health_factor:.4f}")
            await execute_liquidation(borrower)

Liquidation monitoring is the single strongest argument for dedicated nodes in DeFi. On shared infrastructure, your health factor checks compete with other users' requests for throughput. During market volatility, exactly when liquidations spike, shared endpoints experience the most congestion. A dedicated node ensures your liquidation bot has consistent, uncontested access to the blockchain during the moments that matter most.

2. Real-Time DEX Price Feeds

DEXes need to show accurate prices, and "accurate" in this context means "reflecting the most recent swap." WebSocket subscriptions to pool contract events give you real-time price updates as swaps occur:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

const { WebSocketProvider, ethers } = require("ethers");
const wsProvider = new WebSocketProvider(
  "wss://go.getblock.io/<YOUR_ACCESS_TOKEN>/"
);
// Subscribe to Swap events on a Uniswap V3 pool
const swapFilter = {
address: UNISWAP_V3_POOL,
  topics: [
    ethers.id(
      "Swap(address,address,int256,int256,uint160,uint128,int24)"
)
]
};
wsProvider.on(swapFilter, (log) => {
  const decoded = poolInterface.parseLog(log);
  const price = calculatePriceFromSqrtPriceX96(
    decoded.args.sqrtPriceX96
  );
 updatePriceFeed(price);
});

Every swap on the pool triggers a Swap event, which your WebSocket listener receives immediately. You decode the event to extract the new sqrtPriceX96 value and calculate the human-readable price. This is how production DEX frontends maintain sub-second price accuracy.

3. TVL Calculation with Archive Data

Historical TVL calculations, essentially for analytics dashboards, audit reports, and investor presentations, require querying the blockchain state at specific past blocks. This is called archive data access, and it's a feature that many RPC providers lock behind expensive premium tiers.

1

2

3

4

5

6

7

8

9

# Query token balances at a specific historical block
block_number = 18_000_000
token_balance = token_contract.functions.balanceOf(
    PROTOCOL_VAULT
).call(block_identifier=block_number)
# Get the ETH price at that same block from a Chainlink oracle
eth_price = price_feed.functions.latestRoundData().call(
    block_identifier=block_number
)

GetBlock includes access to archive data on paid plans. This means you can build historical analytics, backtest strategies, and calculate point-in-time TVL.

4. Multi-Protocol Yield Comparison

Yield aggregators need to read supply rates from multiple lending protocols on the same chain to find the best returns for users. This means batch-reading from Aave, Compound, Morpho, and other protocol contracts in rapid succession:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

async def get_yields():
    results = {}
    # Aave: supply APY from the lending pool
    aave_rate = aave_pool.functions.getReserveData(USDC_ADDR).call()
    results["aave"] = aave_rate[2] / 1e27 * 100
# Compound: supply rate per block, annualized
    compound_rate = cusdc.functions.supplyRatePerBlock().call()
    results["compound"] = (
        compound_rate / 1e18 * BLOCKS_PER_YEAR * 100
)
    # Morpho: calculate from vault share price changes
    morpho_assets = morpho_vault.functions.totalAssets().call()
   # ... derive APY from asset growth over time
return results

Each protocol stores rate data differently: Aave uses ray units (1e27), Compound uses per-block rates, and Morpho uses vault-share pricing. Your aggregator needs to normalize these into comparable APY figures. The RPC calls themselves are lightweight eth_call operations, but the frequency adds up quickly when you're monitoring dozens of markets across multiple protocols.

Monitoring Your RPC Health

DeFi backends should actively monitor the health of their RPC connections, rather than assuming they're working. A simple health check endpoint catches latency spikes and outages before your users do:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import time
import requests
def health_check():

    """Monitor RPC endpoint health and alert on issues."""
    start = time.time()
    try:
        response = requests.post(
            RPC_URL,
            json={
                "jsonrpc": "2.0",
                "method": "eth_blockNumber",
                "params": [],
                "id": 1,
            },
            timeout=5,
        )
        latency = (time.time() - start) * 1000
        block = int(response.json()["result"], 16)
        if latency > 500:
            alert(f"RPC latency spike: {latency:.0f}ms")
        return {
            "status": "ok",
            "latency_ms": latency,
            "block": block,
        }
    except Exception as e:
        alert(f"RPC endpoint down: {e}")
       switch_to_fallback()

Run this check every 30 seconds, and you'll catch problems before they cascade into user-facing issues. 

GetBlock's dashboard analytics also let you monitor CU consumption by RPC method, which helps identify optimization opportunities — if 80% of your CU budget goes to eth_getLogs, that's the operation to cache or optimize first.

Scaling Your DeFi Infrastructure

During the MVP phase, the free tier lets you test with real mainnet data and validate your protocol's architecture. When you launch on mainnet with under $1 million in TVL, a Starter or Advanced plan provides enough throughput for a real user base.

Once your protocol holds significant TVL, e.g., over $10 million, dedicated nodes become the right choice, not because you've outgrown shared throughput limits, but because the reliability guarantee matters at that scale. A shared endpoint outage is an inconvenience for a small dApp; for a protocol holding $50 million in user deposits, it's a reputational crisis.

For multi-chain protocols, GetBlock's enterprise tier provides custom limits, priority support, and the ability to manage dedicated nodes across multiple chains from a single account.

Conclusion

DeFi infrastructure is less about clever code and more about reliability engineering. The RPC patterns themselves, health-factor checks, swap-event subscriptions, archive queries, and multi-protocol reads are well understood and straightforward to implement. What separates production-grade DeFi from weekend projects is the underlying infrastructure: failover architectures that keep your protocol running during outages, monitoring that catches problems before users do, and the confidence that your RPC provider can handle traffic spikes that come with market volatility.

GetBlock provides the multi-chain coverage, archive data access, dedicated node options, and global regional deployment that DeFi protocols need to operate reliably at scale.

Ready to start building? Get your free API key and deploy your DeFi protocol on production-grade infrastructure.

blog_author_logo
GETBLOCK

May 18, 2026

9 min read

twittertwittertelegramtelegramLinkedinLinkedin