Web3.py Patterns - Multithreading
Web3.py Patterns - Multithreading
py Patterns: Multithreading
Web3.py
web3.py Patterns:
Multithreading
Marc Garreau
Nov 2, 2022 • 3 min read
Like asyncio , threads can be used to improve the performance of I/O bound
processes in Python, and that includes your Web3.py script or dapp. The idea
behind threads and async libraries is similar: while your system is waiting for
something to happen (e.g., a response from a server), be productive elsewhere
(e.g., dispatch another request).
Performance
In small-scale tests (e.g., 50-200 concurrent eth_getBlock requests to a remote
node provider), the performance was comparable between the
AsyncHTTPProvider and a threaded approach utilizing the standard
HTTPProvider .
A sample output from logging the first 50 block numbers as they're returned:
Sample code
A "Hello, World"-style threaded example to get you off the ground:
import concurrent.futures
from web3 import Web3, HTTPProvider
w3 = Web3(HTTPProvider("..."))
blocks = []
def fetch_block(num):
b = w3.eth.get_block(num)
blocks.append(b)
https://snakecharmers.ethereum.org/web3-py-patterns-multithreading/ 1/3
5/30/24, 8:04 PM web3.py Patterns: Multithreading
import asyncio
from web3 import Web3, AsyncHTTPProvider
from web3.eth import AsyncEth
w3 = Web3(AsyncHTTPProvider("..."))
blocks = []
asyncio.run(main())
If your application spends much of its time I/O bound, e.g., waiting on responses
from remote nodes, you've got a good candidate to explore concurrency options.
The downside of using threads is added complexity. The example code in this
post may be blissfully simple, but when you need share context between threads,
the onus is on you to prevent deadlocks and race conditions.
When evaluating threads vs. asyncio for your use case, this gets a bit more
subjective if your scale doesn't necessitate the use of asyncio . A regular
sentiment I see is that asyncio code is generally easier to write and reason
about. Anecdotally, the release notes for Python 3.11 also indicate a greater recent
investment in asyncio than threading by the Python core team and community.
If you're looking for a rule of thumb: reach for an async provider first. If that isn't
an option, either because a needed feature isn't available yet or because you
depend on a library that is not asyncio -compatible, use threads.
https://snakecharmers.ethereum.org/web3-py-patterns-multithreading/ 2/3
5/30/24, 8:04 PM web3.py Patterns: Multithreading
Powered by Ghost
https://snakecharmers.ethereum.org/web3-py-patterns-multithreading/ 3/3