FastAPI: Why async def Made Your API Slower

Outline

Transcript

0:00 Imagine a payments API built on FastAPI. A team marks one endpoint async def, because async is supposed to be faster. Inside it sits one ordinary call to a synchronous client library. Under load, every request stalls, and the health check starts failing too, so the load balancer pulls every instance out of rotation. To be fair, most of us would have made that change. From the dashboards alone, I think I'd blame overload, or a slow database. Add workers and move on, right? That's the usual reasoning, and here it misses.

0:33 People assume async def makes an endpoint concurrent no matter what's inside it. In the run we'll trace, 50 requests, each taking a second, took about 50 seconds in total, and a health check waited the whole time. As plain def, about 2 seconds. Hold on. Plain def was the fast one? By a mile, in that run. The reason comes straight from the source code of FastAPI and the two libraries under it, their official docs, and a small app I actually ran. Source links are in the description. Okay, let's hear it. Walk me through the run.

1:06 So, the setup. One FastAPI app, one worker, and one job that takes a second. 50 requests arrive at once, while a small prober hits the health check every 50 milliseconds. And I wrote that 1-second job four ways. Four? Start with the one that froze. Async def with time dot sleep, our stand-in for that sync client, a call that blocks. That one took 50 seconds, one request after another, with the health check stuck behind them. I'm guessing the second one awaits asyncio dot sleep instead, a wait that lets go of the loop.

1:41 I'd bet that one wins. You'd win that bet. About 1 second for all 50. 3rd, plain def with that blocking sleep: roughly 2 seconds. 4th, async def that hands that sleep to a threadpool: 2 seconds again. So the same time dot sleep is fine in plain def but deadly in async def? Same reaction I had after the run. Two questions: where did 50 seconds come from, and why two instead of one? The 50 I can take. A uvicorn worker, the server process running your app, runs one event loop on one thread, shared by every async def endpoint in that worker.

2:18 It only switches requests at an await, and time dot sleep never awaits. So it just sits on that thread for a full second, 50 times in a row. Okay, picture a grandmaster playing 50 boards at once, moving on to the next board while each opponent thinks. Yeah, and that sleep is the opponent who grabs the grandmaster's arm until the game's over. The other 49 boards just wait. Grim. And the health check is one of those boards, stuck in line behind the payments it's supposed to vouch for. And from outside, a stuck health check looks exactly like a dead server.

2:53 Meanwhile the balancer, doing its job, pulls a server that was only busy. Async def is really a promise that you'll never block. Break it once, and every request on that worker pays for it. Then why did plain def survive the same blocking call? FastAPI didn't magically make time dot sleep async. No, it moved it. FastAPI decides once, when it builds the route, not on every request. If your endpoint is async def, it gets awaited right on the event loop. If it's plain def, every call goes to a threadpool instead.

3:26 Huh, so it only reads the keyword, never what's inside. And the loop stays free because the blocking happens on some other thread. Yep. Dependencies, the helper functions FastAPI injects with Depends, follow that rule too. Even the dependencies. I'll admit, I always treated plain def as the legacy option you use until you get around to async. Yeah. Code review pushes that way too. Suppose a reviewer comments "why isn't this async?" on the pull request, and the author just flips it to async def, sync client and all. 1 keyword, and that's the freeze.

4:00 Right, and it sails through any test that sends one request at a time, because a lone request still comes back in roughly a second. So for a synchronous library, plain def is actually the safe one. So you're converted. Plain def everywhere, then? Not with your 2 seconds. Let's say every request got its own thread: all 50 would have finished together. So what's rationing the threads? A limiter. Starlette, the toolkit FastAPI is built on, hands the call to AnyIO, the library that runs its threads, and every call borrows a token.

4:34 40 by default. Sampled half a second in, the limiter read 40 borrowed, 10 waiting. Then 40 finish near 1 second, and the 10 waiting finish near two. What did your health check do meanwhile? Yep, that's the 2 seconds. And I timed the health check: it stayed fast, because the loop was free and the health check route itself was written as async def. Make it plain def too, and it waits for a token like everyone else. Oh, nice, so the async def route is the hero this time. Can't you just raise the limit?

5:07 Tempting. At 100 tokens, all 50 finished in about a second. But every extra token can mean another operating system thread. Take a 20-connection database pool behind those calls: only 20 of the 50 threads work at a time, and the rest just queue for a connection. So I think of the 40 as a budget, not a bug. And that frozen loop isn't just a lab trick. Shippo's engineering team published a write-up about the same failure. Their billing webhook handler was declared async def, then made a synchronous call to send a message to a queue.

5:42 Let me guess. Their load test fell over. Pretty much. They aimed 500 requests a second at it and got only about 42 requests a second through. Moving the queue call to the threadpool and raising the thread limit only nudged it. Honestly, I'd have stopped right there and blamed the queue. Fair. They kept profiling, though, and found another blocking call hiding in a dependency, one of those Depends helpers, that created a new queue client on every request. Their own profile shows it running right on the loop, no threadpool in sight, so that helper must have been async def.

6:19 Reusing one client took them to 150 requests a second, more than triple. Oh, so the call they could see was the small one. Right. Then they gave it far more threads and turned the handler into plain def. Now that the loop was clear, the bigger limit finally paid off: about 195 a second, about four and a half times where they started, and every request succeeded. So free the loop first, then size the threads. Now, in a real service, how do I even find a hidden call like that? Python's asyncio has a debug mode you switch on with 1 environment variable.

6:57 Run a load test or staging with it on, and anything that holds the loop for more than 100 milliseconds gets logged. That points you at the culprit instead of a guess. Then the fix depends on, well, what you're calling. If there's an async version of the library, for example an async HTTP client or an async database driver, use it and await it. And if it's synchronous... ...declare the endpoint plain def and let the threadpool carry it. And for a single slow call in an otherwise async endpoint, wrap just that call in Starlette's run in threadpool helper and await it.

7:32 Why not Python's own asyncio dot to thread? It's built in. It is, but it uses a separate thread pool, your CPU count plus four, capped at 32. On a two-core machine that's six threads, and raising the 40 won't touch it. Six. That's tighter than the 40. Okay, two separate budgets. And if you do raise AnyIO's limiter, set it once when the app starts, sized against whatever those threads wait on downstream, like that 20-connection pool. Past that, you've only moved the line. And my add-more-workers guess from the start?

8:07 I mean, it buys throughput, but each worker is its own loop with its own 40. One blocking call still freezes whichever worker it lands on, health check included. More grandmasters, then, and any one of them can still get an arm grabbed. Exactly. If async made your API slower, something blocked the loop. Keep blocking calls out of async def, and remember the 40. Thanks for listening to Learning Podcasts.