How to use websockets when building on Ethereum, Polygon, Optimism, and Arbitrum.
What are WebSockets and how do they differ from HTTP requests?
WebSockets is a bidirectional communication protocol that maintains a network connection between two parties, typically a server and a client. Unlike HTTP, with WebSockets clients don't need to continuously make requests when they want information.
Instead, in an open WebSocket connection a server can push network updates to clients by allowing them to subscribe to certain network states, such as new transactions or blocks being added to the blockchain.
This dramatically improves the efficiency of certain HTTP “push” network requests - instead of making an HTTP request every second to pull the latest data, the client can simply open a WebSocket connection and wait for the updates to arrive.
How can I set up a WebSocket connection?
It’s quite simple to set up a new WebSocket connection to Ethereum - try the command below in your terminal.
If you’d like an endpoint with higher rate limits, sign up for a free Alchemy account , grab a new API key to replace the command above, and get access to over 300 million compute units for free per month.
In addition to Ethereum, Alchemy currently supports WebSocket connections to these EVM-compatible blockchains:
How can I make WebSocket subscriptions for Ethereum blockchain updates?
Once you’ve run the command above, you’ll have an open WebSocket connection to an Ethereum node. To start / stop receiving push updates on certain state changes in the Ethereum network, you’ll need to send one of the following methods:
These two requests enable blockchain app developers to create and delete subscriptions. By setting their parameters properly, you’ll get push updates whenever new transactions are sent or new blocks are created.
Here’s an example of an eth_subscribe request:
// initiate websocket stream first
wscat -c wss://eth-mainnet.alchemyapi.io/v2/demo
// then call subscription
Using Alchemy’s Subscription API, there are four main types of WebSocket subscriptions you can make to receive push updates to an Ethereum node:
alchemy_pendingTransactions: Emits full transactions that are sent to the network, marked as "pending", and are sent from or to a certain address. A custom Alchemy subscription.
newHeads: Emits new blocks that are added to the blockchain.
logs: Emits logs attached to a new block that match certain topic filters. Note: newFullPendingTransactions and filteredNewFullPendingTransactions are being combined into a single API with parameters.
Reasons to Use HTTPS instead of WebSockets for JSON-RPC Node Requests
In general, the best practice that we recommend is that developers don’t send standard Ethereum JSON-RPC requests over WebSockets, and instead use HTTP(S) requests. Sending JSON-RPC requests over WebSockets may become unsupported in the future.
This is for four main reasons:
1. Silent failures
WebSockets client-side handling has many tricky edge cases and silent failure modes, which can make web3 dApp less stable.
2. Load balancing
When making requests to distributed systems such as Alchemy, individual HTTP requests are load-balanced to the fastest possible server.
When developers open a WebSocket connection, they incur additional latency by sending JSON-RPC requests only to a single node rather than the most available resource.
In most common request frameworks, support for retrying failed HTTP requests comes automatically, and can be configured easily. Conversely, in WebSockets retrying failed requests typically requires custom JSON-RPC id based tracking.
4. HTTP status codes
When web3 developers use WebSockets they won't receive HTTP status codes in WebSockets responses, which can be useful for debugging or sorting responses.
5. gZip Compression
To provide users with better product experiences, we updated our infrastructure serving HTTP requests to offer Alchemy developers support for gzip compression on all responses larger than 1kb in size.
In practice, we’ve seen roughly a 75% improvement in the total latency of typical JSON-RPC replayTransaction calls.
Go to the article below to learn how to implement gZip compression:
If you’re interested in getting pushed updates on the state of the Ethereum network and avoiding HTTP workaround strategies such as long polling, start using WebSockets today to streamline your request workflow!