Logo
New RPC users get 35% off their first monthView the offer
OnFinality Learn
Network & Protocol Guides12 min read

Base RPC WebSocket Connections: Endpoints, Flashblocks, and Reliability

Learn how to connect to Base mainnet and Sepolia via WebSocket RPC, use Flashblocks for sub-second block events, and build reliable subscriptions with ethers.js and viem.

TL;DR

This guide explains how to use Base RPC WebSocket endpoints for real-time data, including the OP-stack subscription surface and Flashblocks. It provides runnable examples with ethers.js and viem, discusses reconnection strategies, and offers a reliability checklist.

Direct Answer: Base RPC WebSocket Endpoints and Flashblocks

Base RPC WebSocket connections allow you to subscribe to real-time blockchain events such as new blocks, pending transactions, and logs. The primary WSS endpoints are wss://base-rpc.publicnode.com for Base mainnet and wss://base-sepolia-rpc.publicnode.com for Base Sepolia, though you can also use dedicated providers like OnFinality's Base network page for managed endpoints. A key feature is Flashblocks, which streams block events at sub-second intervals, enabling faster dApp responsiveness. This guide covers the mechanics, provides runnable code examples, and outlines best practices for reliability.

Flashblocks are a documented feature of Base's OP-Stack implementation, but their exact cadence (e.g., 200ms or 250ms) should be verified against the Base RPC reference documentation or your provider's documentation, as it may vary by network and configuration.

  • Mainnet WSS: wss://base-rpc.publicnode.com
  • Sepolia WSS: wss://base-sepolia-rpc.publicnode.com
  • Flashblocks provide faster block event streaming than traditional 2-second blocks.

Understanding Base RPC WebSocket Architecture

Base is an OP-Stack rollup, meaning it inherits the Ethereum JSON-RPC interface, including WebSocket subscriptions. The standard subscription methods are eth_subscribe and eth_unsubscribe, which allow you to listen to newHeads, logs, newPendingTransactions, and syncing events. When you connect via WSS, you establish a persistent, bidirectional channel that pushes updates as they occur, unlike HTTP which requires polling.

Flashblocks are a custom extension that emits block headers more frequently than the canonical block time. Instead of waiting for a full block (typically 2 seconds on Base), Flashblocks stream block headers as soon as they are produced, often at sub-second intervals. This is achieved by the sequencer publishing intermediate state roots. To use Flashblocks, you may need to specify a custom subscription type or use a provider that supports them, such as those listed on OnFinality's RPC Assistant.

  • Standard subscriptions: newHeads, logs, newPendingTransactions, syncing.
  • Flashblocks are a Base-specific feature; not all providers support them.
  • WebSocket connections are stateful; you must handle reconnections.

Connecting to Base RPC WebSocket with ethers.js

ethers.js provides a WebSocketProvider class that simplifies connecting to WSS endpoints. Below is a complete example that subscribes to newHeads on Base mainnet and logs block numbers. Ensure you have ethers installed (npm install ethers).

The example uses the public endpoint, but for production, consider using a managed provider like OnFinality's API service for higher reliability and rate limits.

// npm install ethers
const { WebSocketProvider } = require("ethers");

const wsUrl = "wss://base-rpc.publicnode.com";
const provider = new WebSocketProvider(wsUrl);

async function subscribe() {
  provider.on("block", (blockNumber) => {
    console.log("New block:", blockNumber);
  });
}

subscribe().catch(console.error);

// To unsubscribe after 10 seconds:
setTimeout(() => {
  provider.off("block");
  provider.destroy();
  console.log("Unsubscribed and closed.");
}, 10000);

Connecting to Base RPC WebSocket with viem

viem is a modern TypeScript library that offers first-class WebSocket support. Use createPublicClient with a webSocket transport. The example below subscribes to new block headers and logs them. Install viem with npm install viem.

viem's watchBlockNumber is a high-level wrapper that handles reconnection automatically, but you can also use watchBlocks for more control.

// npm install viem
import { createPublicClient, webSocket } from 'viem';
import { base } from 'viem/chains';

const client = createPublicClient({
  chain: base,
  transport: webSocket('wss://base-rpc.publicnode.com')
});

const unwatch = client.watchBlockNumber({
  onBlockNumber: (blockNumber) => {
    console.log('New block:', blockNumber);
  },
});

// To stop watching after 10 seconds:
setTimeout(() => unwatch(), 10000);

Using Flashblocks for Sub-Second Block Events

Flashblocks allow you to receive block events faster than the standard 2-second block time. To use them, you need a provider that supports the flashblocks subscription type. For example, some providers expose a custom method like eth_subscribe with parameter flashblocks or a dedicated endpoint. Check your provider's documentation; OnFinality's Base RPC reference may list supported methods.

The exact cadence of Flashblocks is not standardized; it is documented behavior that you should verify with your provider. For instance, Base's official docs state that Flashblocks are emitted every 200ms on mainnet, but this is subject to change. Always test in a development environment.

  • Flashblocks are not available on all endpoints; verify support.
  • They are useful for real-time UIs, but may increase load on your client.
  • Use them only when you need sub-second updates; otherwise, standard blocks are sufficient.
// Example using viem with a hypothetical flashblocks transport
// This is illustrative; check your provider's API for exact usage.
import { createPublicClient, webSocket } from 'viem';
import { base } from 'viem/chains';

const client = createPublicClient({
  chain: base,
  transport: webSocket('wss://your-provider-flashblocks-endpoint')
});

// Assuming the provider emits 'block' events at flashblock cadence
const unwatch = client.watchBlocks({
  onBlock: (block) => {
    console.log('Flashblock:', block.number);
  },
});

Expected Results and How to Verify

When you run the ethers.js example, you should see a new block number logged every 2 seconds (or faster if Flashblocks are enabled). The block numbers should be sequential and increasing. To verify the connection is working, you can also call provider.getBlockNumber() and compare it with the subscription output.

For viem, the watchBlockNumber callback will fire with the latest block number. You can cross-check with a public explorer like Basescan. If you don't see updates, check your network connection, firewall, or endpoint availability.

  • Expected output: sequential block numbers increasing over time.
  • Use provider.getBlockNumber() to confirm the latest block.
  • If no events, test with a simple eth_blockNumber call via WebSocket.

Common Failures and Fixes for WebSocket Connections

WebSocket connections can drop due to network instability, server timeouts, or rate limiting. Common errors include 'Connection closed', 'ETIMEDOUT', or 'Unexpected server response'. To handle these, implement automatic reconnection with exponential backoff. Both ethers.js and viem have built-in reconnection options, but you may need to customize them.

For ethers.js, you can listen to the 'error' and 'close' events and recreate the provider. For viem, the webSocket transport has a reconnect option. Additionally, consider using a dedicated provider like OnFinality's WebSocket RPC disconnection fixes guide for advanced strategies.

  • Implement reconnection with backoff to handle drops.
  • Monitor connection health with heartbeat pings.
  • Use multiple endpoints for failover.
  • Check rate limits; public endpoints may throttle.
// Example reconnection logic for ethers.js
let provider;
let reconnectAttempts = 0;

function connect() {
  provider = new WebSocketProvider(wsUrl);
  provider.on('block', (blockNumber) => console.log('Block:', blockNumber));
  provider.on('error', (err) => {
    console.error('Error:', err);
    provider.destroy();
    reconnect();
  });
  provider.on('close', () => {
    console.log('Connection closed');
    reconnect();
  });
}

function reconnect() {
  const delay = Math.min(1000 * 2 ** reconnectAttempts, 30000);
  reconnectAttempts++;
  setTimeout(connect, delay);
}

connect();

Tradeoffs and Limitations of Base RPC WebSockets

WebSocket connections are more complex than HTTP and require careful resource management. They keep a persistent connection open, which can consume memory and bandwidth, especially with many subscriptions. Flashblocks increase the frequency of events, which can overwhelm clients that are not optimized for high-throughput data.

Public endpoints often have rate limits and may not support Flashblocks. For production, consider a commercial provider like OnFinality's pricing plans that offer higher limits and dedicated support. Also, be aware that WebSocket subscriptions are not guaranteed to be delivered in order; you may need to handle reorgs by checking block hashes.

  • Persistent connections require more resources than HTTP polling.
  • Flashblocks may cause high event frequency; design your client accordingly.
  • Public endpoints may have usage limits; use a managed provider for scale.
  • Handle chain reorganizations by verifying block hashes.

Next Steps and Further Resources

Now that you understand Base RPC WebSocket connections, you can build real-time dApps, monitors, or analytics tools. For a deeper dive, explore the Base RPC reference documentation for all available methods. If you need a reliable endpoint, check OnFinality's Base network page for managed services.

You can also use OnFinality's RPC Assistant to generate endpoint URLs and test them. For more learning resources, visit the OnFinality Learn hub for guides on RPC best practices and troubleshooting.

Base RPC Rate Limits, Infrastructure, and When to Move to a Dedicated Endpoint

Public Base RPC endpoints, including WebSocket and Flashblocks, are shared infrastructure. They enforce rate limits to ensure fair usage, which can lead to throttling or disconnections during high-frequency requests or heavy subscription loads. Flashblocks, which emit events every 200ms, and WebSocket subscriptions (e.g., newHeads, logs) significantly increase the request count and can quickly hit these limits.

For production applications, relying on public endpoints is risky due to variable latency, rate limiting, and potential downtime. If your app requires consistent performance, high throughput, or guaranteed uptime, consider moving to a dedicated endpoint. Dedicated endpoints offer higher rate limits, dedicated resources, and better reliability. Evaluate your usage patterns: if you exceed typical public limits or need 24/7 stability, a dedicated solution is advisable. For more details, see the Base RPC endpoint guide.

  • Public endpoints are shared and rate-limited; throttling can occur under load.
  • Flashblocks and WebSocket subscriptions increase request frequency, exacerbating limits.
  • For production, assess your needs; dedicated endpoints provide higher limits and reliability.

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started