“how to use Uvicorn to manage a process pool and offload queued jobs to idle process” was my starting question. One person wants to generate a report. Another opens /health and expects a quick answer. The report might take half a second in either case. What matters to the second person is what the server is doing during that half second.
If the route is async, why would anyone else have to wait?
Start with one Uvicorn web worker, a process that accepts connections and runs the application. Inside it an event loop runs code for requests that can make progress. If the report is waiting for an asynchronous database driver, the driver sends the query and the handler suspends at await while it waits for rows. The first client is still waiting, but the event loop can answer /health.1
Now replace the database wait with half a second spent calculating a score. A Python loop always has another instruction to execute. Other tasks on the event loop have to wait until it gives up control. Declaring the route async def does not insert a pause into the calculation. And time.sleep() would make a poor CPU experiment: it blocks the thread but spends that time sleeping.
Move the same calculation into a child process. Who gets a response first?
I kept three versions of the report route. /waiting suspends on an asynchronous timer. /inline executes return calculate() on the event-loop thread. /pooled submits that same function to a pool of separate processes and awaits the result. The original report request stays open in all three cases.2
Save this as web.py and run python -m uvicorn web:app --workers 1 in an environment with FastAPI and Uvicorn installed. The pool belongs to the application's lifespan: it is created at startup and shut down when the worker exits. The calculation is a module-level function so that the child process can import it.23
import asyncio
from concurrent.futures import ProcessPoolExecutor
from contextlib import asynccontextmanager
from multiprocessing import get_context
from fastapi import FastAPI
def calculate():
return sum(i * i for i in range(8_000_000))
@asynccontextmanager
async def lifespan(app):
with ProcessPoolExecutor(max_workers=1, mp_context=get_context("spawn")) as pool:
app.state.pool = pool
yield
app = FastAPI(lifespan=lifespan)
@app.get("/health")
async def health():
return {"ok": True}
@app.get("/waiting")
async def waiting():
await asyncio.sleep(0.5)
return {"ok": True}
@app.get("/inline")
async def inline():
return calculate()
@app.get("/pooled")
async def pooled():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(app.state.pool, calculate)
I used two independent local HTTP connections and warmed the pool by calling /pooled once. In a test copy, each report route wrote a marker as soon as it started. The second client waited for that marker before requesting /health. Otherwise a healthy response could simply mean that the health request got there first. These are observations from one run with FastAPI 0.111.1, Uvicorn 0.30.6 and CPython 3.12.3. The timings include local client overhead.
| First client requested | Second client's wait for /health | State of the first request when the health response arrived |
|---|---|---|
/waiting | 21 ms | Still waiting for its 0.5-second timer |
/inline | 390 ms | Calculation already finished |
/pooled | 20 ms | Still waiting for the child process to finish |
The important measurement is the order of the two responses. Even a much longer asynchronous wait leaves the loop available. An ordinary helper function called directly from an async def route executes on the caller's thread. If the route itself is declared with ordinary def, FastAPI runs that route in a thread pool. Threads can help with blocking I/O. On conventional CPython, the Global Interpreter Lock (GIL) limits simultaneous execution of Python bytecode in one interpreter, which is why separate processes are useful for these pure-Python calculations on multiple cores.1
What does each kind of worker pick up?
| Approach | What an idle worker can take | What the client sees |
|---|---|---|
| Add Uvicorn web workers | A web worker accepts a connection and handles its requests. Other processes may still accept new connections while one process is occupied. | The original request keeps calculating in its original process. If every worker is busy, a light request may still wait. |
Await a local ProcessPoolExecutor | A compute process runs an explicitly submitted function with serializable inputs. Submissions can queue when the pool is busy. | The HTTP request waits for its result, but the event loop can answer other requests. |
| Submit to an independent job queue | An independent worker claims an enqueued job. The service can return HTTP 202 and a status URL once submission succeeds. | The client can disconnect and look up the result later. The service defines retries, duplicate handling and result expiry.4 |
I ran the service again with two web workers. A test-only route returned the process ID, so I could deliberately select two persistent HTTP connections handled by different workers. While A was running /inline, B returned /health in about 0.5 ms. That demonstrates what the other worker can do. It doesn't predict typical latency when incoming connections land on arbitrary workers.
Uvicorn offers no API to submit an arbitrary Python function to an idle web worker. There's also a multiplication to do before enabling both kinds of pool: each of four web processes runs its own startup code. Four local compute slots per web worker can mean sixteen compute children plus the web processes. CPU, memory and database connections have to fit the total.35
With the GIL, how could the tutorial say “on par with Go”?
The phrase that caught my attention was “most of the tested NodeJS frameworks and on par with Go”. My reaction was “this is wrong since no paralism with GIL in py”. The link in the FastAPI 0.111.1 tutorial points to a specific experiment: TechEmpower Round 17 (2018), physical hardware, Multiple queries. The main chart reports HTTP requests completed per second when each request performs 20 database queries. The URL selects test=query. The separate single-query test is called db.67
The measured Python implementation was Starlette. It used Starlette 0.1.6, Uvicorn 0.2.9 and asyncpg 0.16.0. For each request it looked up 20 random records in PostgreSQL, one query at a time, then encoded the result array as JSON. Gunicorn 19.9.0 started multiple Uvicorn workers. One worker could run other requests while waiting for PostgreSQL, and multiple processes could use separate cores. Each interpreter still had its own GIL.8
| Round 17 implementation | Database | HTTP requests per second, 20 queries per request |
|---|---|---|
Express (express-mysql) | MySQL | 4,612 |
Koa (koa) | MongoDB | 7,930 |
Fastify (fastify) | MongoDB | 9,470 |
hapi (hapi) | MongoDB | 20,456 |
Starlette (starlette) | PostgreSQL | 14,516 |
Go standard library (go-postgres) | PostgreSQL | 9,935 |
Go chi router (chi) | PostgreSQL | 24,769 |
For “most”, I counted each NodeJS framework with a nonzero result once, using its fastest valid database configuration. The raw data also lists a standalone Node.js baseline. Both Sails entries completed zero requests at this query count. The rates above use whole requests per second, dropping the fractional part. Starlette completed 217,752 requests in 15 seconds, or 14,516.8 per second before truncation. The implementations used different drivers and, in several cases, different databases.78
In that selection, Starlette finished ahead of three of the four JavaScript frameworks. Its rate fell between the two Go/PostgreSQL entries. That gives the tutorial's wording a specific workload and comparison group. There is no FastAPI row here, and this experiment never timed a pure calculation in Python against the same calculation in Go.76
What if the user wants to close the page and come back for the report?
That changes the API. In /pooled the result is tied to the open HTTP request. A downloadable report needs an identity that survives that request. The service now handles two separate actions.
- Submit. The browser sends
POST /reports. A web worker registers report 42 and enqueues a job carrying its ID. Once accepted, the server returns HTTP 202 and the ID. If all compute workers are busy, the job waits. An available worker claims it, builds the report and stores the status and download URL under ID 42. With Celery, a separate service called a message broker holds and forwards job messages.4 - Retrieve. Later, the browser sends
GET /reports/42. Any web worker with access to the report store can look up its status: queued, complete with a URL, or failed. If the service promises recovery across restarts, the queue, status and results need appropriate persistence. A job delivered twice also needs defined behavior, such as recognizing that its report already exists.4
My query service ultimately started one Uvicorn worker. For a future calculation whose caller needs the answer immediately, I'd first measure how much it costs to send the function's inputs to a local pool. For a report the caller wants to collect tomorrow, the first design decision is where to store the job ID and result.
Footnotes
-
FastAPI. (n.d.). Concurrency and async / await. FastAPI Documentation. Path operation functions and utility functions. ↩ ↩2
-
Python Software Foundation. (n.d.). Event loop. Python 3.12 Documentation. Executing code in thread or process pools. ↩ ↩2
-
Uvicorn contributors. (n.d.). Deployment. Uvicorn. Built-in multiprocess manager. ↩ ↩2
-
Celery contributors. (n.d.). Tasks. Celery Documentation. Task acknowledgement, retries and idempotence. ↩ ↩2 ↩3
-
Uvicorn contributors. (n.d.). Lifespan. Uvicorn. Lifespan and multiple workers. ↩
-
FastAPI contributors. (2024). Concurrency and async / await, v0.111.1. GitHub. Quotation and benchmark link in Burger conclusion, line 245. ↩ ↩2
-
TechEmpower. (2018, October 30). Framework Benchmarks Round 17. Multiple queries on physical hardware · Round 17 Final Citrine data: queryIntervals, duration and rawData.query. ↩ ↩2 ↩3
-
TechEmpower contributors. (2018). Framework Benchmarks, Round 17. GitHub. Starlette implementation and deployment · JavaScript implementations · Go implementations. ↩ ↩2