Data Fetching Methods
| Method | Use Case | Latency | Cost |
|---|---|---|---|
| REST API | One-time queries | ~100-500ms | Request-based |
| WebSocket | Real-time updates | ~10-50ms | Connection-based |
| JSON-RPC | Direct node access | ~50-200ms | Variable |
| GraphQL | Complex queries | ~100-300ms | Request-based |
REST API Approach
Best for simple, one-time requests:
// Get ETH balance via REST
const response = await fetch(
'https://eth-mainnet.g.alchemy.com/v2/' + API_KEY,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getBalance',
params: ['0x...', 'latest'],
id: 1
})
}
)
const data = await response.json()WebSocket for Real-Time Data
Subscribe to new blocks and events:
const ws = new WebSocket(
'wss://eth-mainnet.ws.alchemy.com/v2/' + API_KEY
)
ws.onopen = () => {
ws.send(JSON.stringify({
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['newHeads'],
id: 1
}))
}
ws.onmessage = (event) => {
console.log('New block:', JSON.parse(event.data))
}Caching Strategies
- Client-side caching - Use React Query or SWR
- CDN caching - Cache static responses
- Indexing services - The Graph for historical data
💡 Pro Tip: Use batched queries to reduce API calls. Most providers allow multiple requests in one call.
Error Handling
- Implement retry logic with exponential backoff
- Set up fallback providers for redundancy
- Monitor rate limits and quotas