question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] about threads issue with fastapi.

See original GitHub issue

Hi, I have a question about the threads issue with fastapi.

When I run the example from tutorial uvicorn main:app --reload --port 4681 --host 0.0.0.0 with the following main.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
    return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

and it show up the following information

INFO: Started server process [18983]
INFO: Waiting for application startup.
INFO: Uvicorn running on http://0.0.0.0:4681 (Press CTRL+C to quit)

then I use ps -o nlwp 18983 to see how many threads this process (18983) is using.

However, everytime when I send a request to this service, the number of threads increase without being closed. To be more specific, when I send 1000 requests, this process ended up with 1000 threads running.

This is problematic because I tried to serve another more complicated applications, allocating arbitrary number of threads would finally get my machine out of resources.

Is there any thing I could have done wrong? Thanks in advance!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:19
  • Comments:31 (9 by maintainers)

github_iconTop GitHub Comments

24reactions
emarbocommented, Oct 22, 2019

Hello, I have configured the number of FastAPI threads setting the default thread pool executor as follows:

# main.py
from concurrent.futures import ThreadPoolExecutor
import asyncio

loop = asyncio.get_running_loop()
loop.set_default_executor(ThreadPoolExecutor(max_workers=5))

I’ve ended using this solution because Starlette run_in_threadpool uses the default executor when calls the loop.run_in_executor. I suppose it would be better if the executor could be configured explicitly in the Starlette or FastAPI configurations.

@lzhbrian do you think this could work for your project?

I am using the FastAPI Project Template with this environment:

Python 3.7.2
fastapi==0.42.0
starlette==0.12.9
uvicorn==0.9.0
15reactions
seahrhcommented, Sep 1, 2021

Taking @emarbo’s code example and stuffing it in a startup event worked for me.

main.py

@app.on_event("startup")
def set_default_executor():
    from concurrent.futures import ThreadPoolExecutor
    import asyncio

    loop = asyncio.get_running_loop()
    loop.set_default_executor(
        ThreadPoolExecutor(max_workers=5)
    )

fastapi==0.68.0 gunicorn==20.1.0 uvicorn[standard]==0.14.0

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI and Python threads - Stack Overflow
I have a little issue with FastAPI and additional threads spawning. Let's say i have an application that serves two endpoints. Other is...
Read more >
Server Workers - Gunicorn with Uvicorn - FastAPI
Let's check back those deployment concepts from before: Security - HTTPS; Running on startup; Restarts; Replication (the number of processes running); Memory ...
Read more >
Interview Questions for Senior FastAPI Developers - YouTube
This episode of the Turing Mock Interview series dives deeper into the concepts of FastAPI to understand what the technical interview for ...
Read more >
[Python] Thread problem in FastAPI - New Relic Explorers Hub
I use this command in docker compose: newrelic-admin run-program gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000 but ...
Read more >
How do Asynchronous Webserver (FastApi, Quart etc.) handle ...
How are they working different from webservers like Flask. I learned that Webservers start a thread for each connection and the thread then ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found