Can four Uvicorn workers schedule work the way Go schedules goroutines?

June 26, 2025

I wanted my Python web service to handle requests the way a Go program handles goroutines. In Go, writing go makeReport() starts an independent piece of work. I can ask for a report without first choosing a thread to make it. Go by Example has a runnable example with a function that prints three lines. An ordinary call waits for all three, while a call prefixed with go lets the caller continue.1

The Python setup I was shown had four Uvicorn workers on a four-core machine. Each could handle new requests while it waited for a database. That sounded similar, until I asked what would happen if three workers were idle and the fourth had several reports ready to calculate.

The database has answered. Who gets to run the next line?

Follow one report. Worker 1 accepts a connection, sends a database query, and reaches await read_rows(). A worker process is a separate running instance of the program, with its own memory. This worker has an event loop that runs ready tasks. While the database is busy, the loop can handle another request. When the rows arrive, the task waiting for them becomes runnable on worker 1's loop.23

Now suppose worker 1 has started calculating another report when two things happen. A new customer connects, and the database sends back the rows. Idle worker 2 can accept the new customer's connection. The database reply arrives on the connection worker 1 already owns. The task that knows what to do with those rows is still waiting for worker 1's loop. Adding workers gave the server more places to accept new connections. Where an existing task can resume is a separate question.23

I originally asked about both WSGI and ASGI, two conventions for how a Python server calls an application. Consider report A, which is waiting for a query, and health check B, arriving on another connection. Here reports:app means the application named app in reports.py.43

DeploymentWho can answer B while A waits?
Gunicorn 23, a WSGI application, one default synchronous workerThis worker handles one request at a time. A synchronous database call occupies it, so B waits.
The same application with gunicorn -w 2 reports:appThe second worker can answer B if it is free. A still belongs to the first.
An ASGI application with uvicorn reports:app --workers 1 and an asynchronous database driverA suspends when it needs to wait. Its own event loop can answer B.

That led to my next question: “is this different from goroutine i think all async routines are allocatble between all threads in golang”. An operating-system thread executes instructions. Several threads in one Go process have access to the same memory. Go's runtime includes a scheduler that assigns runnable goroutines to threads. When a goroutine waits on a network connection through Go's standard network library, the thread can run another goroutine. Once the data arrives, the waiting goroutine can resume on the same thread or on another available thread. Starting a goroutine does not require creating a new thread for it.56

What if the first report is using the CPU?

Suppose report A has row after row of numbers to add. Report B has just received its rows. Its goroutine is ready. If there is another core and the runtime can execute Go code on it, B can run there while A keeps adding. Internally Go calls a goroutine a G, an OS thread an M, and the resource a thread needs to execute user Go code a P. Each P has a local run queue. An idle P can take runnable work from another P's queue, a technique called work stealing. A single loop inside A is still a single piece of work. The scheduler has two jobs to distribute here because the program started two goroutines.78

What if only one P is available? Go's release notes describe a second mechanism: “Goroutines are now asynchronously preemptible.” In Go 1.24.4 on Linux, the runtime can pause A at a safe point, give B a turn, and resume A later, even when A is in a tight computation loop. There is no promise that B runs the instant it becomes ready.95

In Python, a coroutine is an execution that can suspend and resume. Scheduling a coroutine on an asyncio event loop creates a Task. The Python 3.12 documentation puts the rule succinctly: “an event loop runs one Task at a time.” While Task A loops over integers on that thread, ready Task B waits until A suspends or returns. The operating system can interrupt the thread, but when that thread runs again it picks up inside A. Worker 2 has no operation for moving Task B to its own loop, even if B has yet to execute its first line. If the code that submits B to a pool also runs on A's loop, even that submission must wait.31011

Can a timer interrupt the calculation?

I scheduled a callback for 50 milliseconds later, then immediately started adding integers. The callback records when it actually runs. In Go I set GOMAXPROCS(1) so at most one thread can execute user Go code at a time. That rules out two cores happening to run both parts simultaneously.5

One local runTimer callback ran atCalculation finished at
Go 1.24.4, Linux/amd6459 ms590 ms
CPython 3.12.3, one asyncio event loop275 ms275 ms

The Go callback ran in the middle of the calculation. The Python timer was due long before the calculation finished, but its callback first ran when the main task reached await fired. The iteration counts differ. The comparison to make is within each row: did the callback execute before or after the calculation finished?

Save this as main.go and run go run main.go. When the timer expires, time.AfterFunc calls the function in its own goroutine. The buffered channel holds the elapsed time until the result is printed.12

package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	runtime.GOMAXPROCS(1)
	start := time.Now()
	fired := make(chan time.Duration, 1)
	time.AfterFunc(50*time.Millisecond, func() { fired <- time.Since(start) })

	var total uint64
	for i := uint64(0); i < 1_000_000_000; i++ {
		total += i
	}
	elapsed := time.Since(start)
	fmt.Println("timer:", <-fired, "loop:", elapsed, "sum:", total)
}

Save the Python version as demo.py and run python3 demo.py. To see what changes when the main task suspends, replace just the for loop with await asyncio.sleep(0.3), leaving total = 0 in place.

import asyncio
import time

async def main():
    loop = asyncio.get_running_loop()
    start = time.perf_counter()
    fired = loop.create_future()
    loop.call_later(0.05, lambda: fired.set_result(time.perf_counter() - start))

    total = 0
    for i in range(8_000_000):
        total += i
    elapsed = time.perf_counter() - start
    print("timer:", round(await fired, 3), "loop:", round(elapsed, 3), "sum:", total)

asyncio.run(main())

“how we can auto schedule coroutines between processes ?”

My first version of the question was “why cannot we implement an auto coroutine scheduler to do this excatly like in golang”. The answer I got started with the Global Interpreter Lock (GIL), which normally allows only one thread per CPython interpreter to execute Python bytecode at a time. That explains a limit on simultaneous computation. The timer experiment asks who can give B a turn even on one thread. That depends on the scheduler. A free-threaded CPython build can execute Python code on multiple threads with the GIL disabled. An ordinary asyncio.Task still belongs to the loop that created it.1337

So why couldn't a second process take over? Imagine what worker 1 would have to send: a suspended function call, its local variables, a live database connection and the registration that tells the loop which task to wake up. A report number alone conveys none of that. Instead, I can identify a step whose inputs and output can travel. Here score is an ordinary module-level function, rows a list of numbers, and pool a process pool created earlier.10

rows = await read_rows(report_id)
loop = asyncio.get_running_loop()
total = await loop.run_in_executor(pool, score, rows)

Worker 1 keeps the HTTP request and database connection. An available pool process starts at the first line of score(rows) and returns a number. Worker 1 resumes the original coroutine and sends its response. The pool chooses the process. I choose the function boundary and the data that crosses it. For large inputs that last choice can determine whether the pool pays off. What does it cost to pickle the arguments?1110

Can a Node.js worker resume the code after an await?

I asked much the same question about JavaScript: “can nodejs implement auto scheuler for async coroutines across threads”. A Node.js process can wait on many network connections. When await readRows() finishes, the code after the await runs in the original JavaScript execution environment. Node also uses a library called libuv, whose internal thread pool handles operations such as certain file-system calls. For a different thread to run my JavaScript calculation, I can create a worker_threads worker and send it a message.1415

Say worker 1 has finished the first 100 rows and its subtotal is 350. If I explicitly save { reportId: 7, nextRow: 101, subtotal: 350 }, worker 2 can fetch the same report and start at row 101. My function has defined exactly what “continue” means. A Node.js 22 message port can transfer data, but it has no operation for extracting the pending wait, locals and next instruction from an arbitrary suspended JavaScript function. Sending the ID alone starts a fresh handler on worker 2.16

This was why I went on to ask how to implement worker pools in both languages. A pool can pick a worker for the next job I submit. Go's runtime can also decide when to suspend a goroutine that has already started, and on which thread to resume it. For the Python service, the practical choice was whether to accept more connections or offload part of an existing request. For Node.js, I tried giving two threads three jobs to see which thread picked up the third.2

Footnotes

  1. McGranaghan, M., & Bendersky, E. (n.d.). Goroutines. Go by Example. Run the example with both kinds of call. ↩

  2. Uvicorn contributors. (2024). Deployment, v0.30.6. GitHub. Built-in multiprocess manager. ↩ ↩2 ↩3

  3. Python Software Foundation. (n.d.). Coroutines and Tasks. Python 3.12 Documentation. Quotation from Task Object, paragraph on cooperative scheduling. ↩ ↩2 ↩3 ↩4 ↩5

  4. Gunicorn contributors. (2024). Design, 23.0.0. GitHub. Sync workers. ↩

  5. The Go Authors. (n.d.). Effective Go. Go. Goroutines · runtime. Go Packages. GOMAXPROCS. ↩ ↩2 ↩3

  6. The Go Authors. (n.d.). netpoll.go. Go runtime. Network polling and waiting goroutines. ↩

  7. The Go Authors. (2025). Hacking on the Go runtime, go1.24.4. GitHub. Gs, Ms, Ps. ↩ ↩2

  8. The Go Authors. (2025). proc.go, go1.24.4. GitHub. stealWork and local run queues. ↩

  9. The Go Authors. (2020). Go 1.14 release notes. Go. Runtime, paragraph on asynchronous preemption. ↩

  10. Python Software Foundation. (n.d.). concurrent.futures. Python 3.12 Documentation. ProcessPoolExecutor and picklability. ↩ ↩2 ↩3

  11. Python Software Foundation. (n.d.). Event loop. Python 3.12 Documentation. Executing code in thread or process pools. ↩ ↩2

  12. The Go Authors. (n.d.). time. Go Packages. AfterFunc. ↩

  13. Python Software Foundation. (2024). What’s new in Python 3.13. Python Documentation. Free-threaded CPython. ↩

  14. Node.js contributors. (2024). Worker threads. Node.js v22.12.0 Documentation. Worker threads and message passing. ↩

  15. libuv contributors. (n.d.). Thread pool work scheduling. libuv Documentation. Operations that use the thread pool. ↩

  16. Node.js contributors. (2024). Worker threads. Node.js v22.12.0 Documentation. Values transferable over a message port. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-26). Can four Uvicorn workers schedule work the way Go schedules goroutines?. https://caiborui.com/blog/2025-06-26-en-asyncio-task-go-goroutine

@misc{borui2025-93d4b979,
  author = {borui},
  title = {{Can four Uvicorn workers schedule work the way Go schedules goroutines?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-26-en-asyncio-task-go-goroutine}
}