I want to serve an falcon API that can handle multiple simultaneous user requests.
Each request triggers a long processing task therefore I used the ThreadPoolExecutor from concurrent.futures as follows:
import falcon
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=10)
class Resource:
def on_post(self, req, resp):
def some_long_task():
# here is the code for the long task
executor.submit(some_long_task)
resp.body = 'OK'
resp.status = falcon.HTTP_201
app = falcon.App()
resource = Resource()
app.add_route('/', resource)
# Serve...
I am using gunicorn to serve the API, with the following parameters: gunicorn main:app --timeout 10000.
When I execute 2 requests to the API successively, both long tasks are triggered in background in a row. However, as soon as the first long task launched is finished, it stops the execution of the second one. How can I avoid this?
By replacing your long running task with
time.sleep(10), I'm unable to reproduce your problem:As expected, all tasks are correctly run to completion:
Could the problem instead lie in your long task's code?
There are some non-trivial pitfalls to watch out for:
executoronly after forking.try... except, and log exceptions.