This Recipe shows how to send batch requests to your Chainstack node instead of sending multiple loop-based requests. Adopting this approach can substantially boost the performance of your DApp.
Overview
id
field to match responses with their corresponding requests. This recipe uses ethers.js v6, which correctly handles response ordering. If you’re using ethers.js v5, be aware of this ordering issue.Environment setup
npm install ethers
Batch requests with ethers
JsonRpcProvider
in ethers
can accept a single request or an array of requests using the _send
method.In this example, the script gets the details of the last 20 blocks using a batch.The code
ethers.toQuantity()
method. All these request objects are stored in pastBlocksPromises._send()
method on the provider sends all these requests in a batch.pastBlocks
.Get your Chainstack endpoint
Run the code
endpoint
const. Then you can run it with node YOUR_SCRIPT_NAME
The console will log the time needed to execute the batch, meaning sending the requests and receiving the responses; it then logs block numbers and hashes of the last 20 blocks.Understanding the response
for
loop.
For context, during the development of this Recipe, a regular for
loop would take about 10/12 seconds.