Case: mortgage calculator with 50k operations per day — what to use: asynchronous, multithreading, or multiprocessing?
sobes.tech AI
Answer from AI
For a mortgage calculator with 50k operations per day, the choice between asynchronous programming, multithreading, and multiprocessing depends on the nature of the tasks:
-
If the operations are mainly I/O-bound (e.g., database requests, external services), then asynchronous programming (asyncio) will allow efficient handling of many requests with fewer resource costs.
-
If the operations are CPU-bound (complex calculations), then Python's GIL will limit multithreading, and it is better to use multiprocessing for parallel execution.
-
Multithreading in Python is effective only for I/O-bound tasks.
In the case of a mortgage calculator, if the calculations are not too heavy, an asynchronous server (e.g., FastAPI with async) can be used to handle many requests simultaneously. If the calculations are heavy, it is advisable to offload them to separate processes or services (via multiprocessing or separate microservices) to avoid blocking the main thread.
Example with asyncio:
import asyncio
async def calculate_mortgage(data):
# asynchronous operations, e.g., requests
await asyncio.sleep(0.01) # simulation
return compute(data)
async def main(requests):
tasks = [calculate_mortgage(r) for r in requests]
results = await asyncio.gather(*tasks)
return results
If CPU-bound, then:
from multiprocessing import Pool
def calculate(data):
return compute(data)
with Pool() as pool:
results = pool.map(calculate, requests)