0
from fastapi import FastAPI
import uvicorn
app = FastAPI()

#Some long processing code, with async declaration
async def doBTask():
    print ("Request started")
    #asyncio.sleep(20)
    sum = 0
    for n in range (1, 10000):
        for m in range(1,10000):
            if m%n ==0:
                pass
            else:
                sum = sum + n    
    
    print ("Completed")
    return sum


@app.get("/")
async def read_root():
    result = await doBTask()
    
    return {"Result": result}

uvicorn.run(app, host="0.0.0.0", port=7000)

When we call that URL in different tabs, the output is coming one after another (even print also). It is clearly single processing but not parallel request processing. Can someone guide where is the mistake, and why FastAPI with async and await not working?

Edit Here is the response I am getting if tried in different browsers and dummy params (you can see, it is processing one after another, even though I sent all at a time)

Request started
Completed
INFO:     127.0.0.1:58998 - "GET /?n=10 HTTP/1.1" 200 OK
Request started
Completed
INFO:     127.0.0.1:59012 - "GET /?m=30 HTTP/1.1" 200 OK
Request started
Completed
INFO:     127.0.0.1:59288 - "GET / HTTP/1.1" 200 OK
AjayR
  • 4,169
  • 4
  • 44
  • 78
  • 3
    async/await doesn't make the code parallel it makes it concurrent - it is not what you do to handle CPU heavy code - it is only useful for I/O heavy code like network requests. – Benjamin Gruenbaum Feb 24 '22 at 12:16
  • 2
    There is actually a really nice guide on this here https://fastapi.tiangolo.com/async/ – Benjamin Gruenbaum Feb 24 '22 at 12:17
  • How to achieve parallel requests in FastAPI – AjayR Feb 24 '22 at 12:32
  • Read the document I've sent it refers to deployment which explains how to deploy a parallel server. – Benjamin Gruenbaum Feb 24 '22 at 12:36
  • 1
    Usually you'll deploy with multiple workers (for example through gunicorn); if you have code that isn't async-compatible, don't define your endpoints as async - FastAPI should then use a ThreadPool internally to handle those requests instead. – MatsLindh Feb 24 '22 at 13:13
  • Does this answer your question? [fastapi asynchronous background tasks blocks other requests?](https://stackoverflow.com/questions/67599119/fastapi-asynchronous-background-tasks-blocks-other-requests) – MatsLindh Feb 24 '22 at 13:50
  • The solution is run through workers which can be run in parellal – AjayR Mar 03 '22 at 16:03

0 Answers0