r/FastAPI • u/oatmeal_dreams • Apr 14 '23
Question Is it really advisable to try to run fastapi with predominantly sync routes in a real world application?
I worry the fastapi docs are misleading. It says “If you just don't know, use normal `def`.” and “in any of the cases above, FastAPI will still work asynchronously and be extremely fast.”
You also have people latching on to this guy scaremongering about async. To me it is a serious problem that fastapi’s docs don’t themselves take any stance on best practices, sync vs async. The docs just say magically everything will be fast and magically sync will “work asychronously”
https://www.reddit.com/r/Python/comments/wrt7om/fastapi_best_practices/
People afraid of async but who like fastapi otherwise will think that the framework is really ready to go in production with sync only routes.
The reality seems to be different. The starlette thread pool is shared across all threaded things including background tasks and things like this, so it’s easy to exhaust the threadpool. What about applying safe request timeouts which is an absolute necessity when using a sync approach? Why the don’t say anything about this either?
And all across github I am finding people close to fastapi recommending that people should use async rather than sync, if they don’t know any better. And yet the stupid docs say the exact opposite!
I am about ready to open a PR to modify the docs a bit. But I just want to hear it from someone who has more experience or has been following fastapi longer (for me I just started looking into this aspect of it in the past few days). Really, it would be nice for the devs or the part of the community really driving it, to take a stance on sync vs async. I can scarcely believe their claim that everything will be fine, whichever one you choose. I almost suspect they are just trying to make the framework seem magical to get people hooked and then they will worry about actually fixing things later (dishonest, not transparent, risky).
The reasons are:
In this thread, starlette people admitting they don’t have anywhere near the tuning features necessary for more heavily sync oriented people https://github.com/encode/starlette/issues/1724
Lack of docs explaining how to deal with configuring timeouts which is absolutely essential when using sync workers, and for example this absolute trainwreck of a discussion about configuring timeouts, which the lead dev / creator of fastapi fails to contribute to or offer any guidance
https://github.com/tiangolo/fastapi/discussions/7364The clear fact that the frameworks which do manage to be good at sync are either a) using async workers e.g. via gunicorn gevent patching or b) offer lots of tuning options and documentation for sync workers, not just a single threadpool and an absolute chaos on github.
If you can sense I’m frustrated, it’s because I work on a team who picked up fastapi because of its cool features, and then they got scared of async and read those lines of the docs which make fastapi sound magical at turning sync into async, and decided to throw out async and make all their routes sync, and now I’m having to try to wade through the absolute chaos of this framework not being able to convincingly take a stance on the issue.
3
u/serverhorror Apr 14 '23
Without looking, I’m pretty sure the following are true:
async will work better in FastAPI when getting into performance land
99 % of cases will never see enough usage to be remotely close to be seeing any kind difference
1
u/oatmeal_dreams Apr 14 '23
99 % of cases will never see enough usage to be remotely close to be seeing any kind difference
What I’m worried about is not necessarily even performance, it’s just that 40 is such a small number. If for some reason some request(s) made by the server itself are taking a long time, the thread pool will full up with threads that are just sitting and waiting very rapidly, and the service falls over. With async this is not a problem.
I’d be afraid about leaving the default threadpool size at 40 unless I could apply very aggressive timeouts. And I don’t even know if/how I can apply timeouts consistently. If it’s something I could configure on uvicorn or if I’d have to configure it on my urllib/requests libs in the app. Fastapi has no docs page on such tuning aspects.
1
u/Relative-Pitch9558 Aug 23 '25
One consideration to start with. A thread is executed only if there is a cpu core available, else it is just sitying in an OS queue. So without cores you won't go far even with a million threads. Then let's do the math. Let's assume a call takes 100ms of pure compute (which is alot). Each thread serves 10 hits/second. 40 threads can serve 400 hits/second, which is a pretty decent throughput for such heavy processes.
The issue with async is that it works only if all processes are fair and await without holding the thread for too long. That is because all async executions run on the main thread. If one async holds the thread for too long everything queues. If you run in container and you have your healthcheck as async, healthcheck will fail and your container will restart.
5
u/zazzersmel Apr 14 '23
very curious to see more experienced ppl chime in herebc as a layman, a lot of what youre saying doesnt exactly seem reflected in the source material you referenced
1
u/oatmeal_dreams Apr 14 '23
I’m very curious too. My experience of trying to answer this question in the last days has been terrible, and I think it’s because no important people (who *could* answer) connected to the project will take a stance, and many of the people using the framework are Machine Learning fanboy types who really don’t have the knowhow to answer, even though they may love the framework.
I’ve been reading dozens of different threads for a few days now and so I haven’t linked everything. That could be why you get that impression.
But the problem wouldn’t really be that my claims might be true. The problem is that *it’s hard if not impossible to get any confidence to the contrary*.
If you’re thinking about using only sync routes, you will find nothing in the docs, the lead dev is silent, and you can’t find any real projects or companies using the framework this way. So you are absolutely left guessing whether the framework is strong in this scenario or even production viable, because they won’t take a stance.
The lead dev being silent and jumping from project to project is part of the problem I guess. It seems like he’s just trying to strike it lucky with one of his projects and abandons the old ones as soon as they’ve reached enough adoption to serve as a marketing platform for his *new* project.
I mean TL;DR: people just looking at the framework should be able to quickly have their fears allayed, when someone comes along with a scaremongering post like I’m making. I feel I *have* to because I am going to have future production systems relying on this; if I can’t get a clear answer I will be left in uncertainty to find out the hard way.
2
u/zazzersmel Apr 14 '23
i would think looking to starlette would be the way to go, fastapi doesnt do anything different at its core, does it?
1
u/oatmeal_dreams Apr 14 '23
Correct. Yeah I’ve been trying to find stuff. It often circles back to the issue I linked (https://github.com/encode/starlette/issues/1724)
Here’s another maybe relevant thread https://github.com/tiangolo/fastapi/issues/5759
The problem is that most anybody who is using sync endpoints is doing so because of some old limitation with SQLAlchemy or SQLite or something like this, so the discussion tends to circle around just making it work. Rather than “should I really prefer to use async unless I have no choice.” Which is my beef with the fastapi docs, where they make it sound like no big deal which one you want to use.
Here’s someone (Netflix) not using SQLite or whatever, and they chose for some reason to use all sync routes. When someone asked them, they couldn’t even write a sentence saying why (unfortunate).
https://github.com/Netflix/dispatch/issues/1073
The application itself is a self-hosted internal slack notifier type thing, so it doesn’t give any confidence about a real world prod web application.
8
u/time4py Apr 14 '23
I have a decent amount of experience with flask in production and fastapi. I will try my best to answer your question and feel free to follow up with more. Sorry in advanced for the long post.
My background
My background is 9+ years of API development mostly in flask but i’ve also touched fastapi, django, tornado, nodejs, java springboot, and most recently go-chi. 2 years ago I co-led a project using FastAPI for an internal tool that is not latency sensitive. We chose FastAPI primarily because of its swagger generation and async support. We had hoped to implement more things in async over time but that never happened.
Threads don’t scale
Thread based python apis do not scale. This has nothing to do with the frameworks themselves (although it can be made worse) and more to do with how python threads are implemented.
It is easy to think of python threading as concurrent programming but it is actually cooperative programming. The oversimplified way to think of this is that when two threads are executing, thread 1 will run N number of instructions, stop, and let thread 2 run N of instructions. The stopping point could be anywhere in your code path and there is mostly no control over where it stops and how long. Also, python does not use I/O hints or any other “smarts” to decide where to stop.
Since the stopping and execution is somewhat arbitrary, python has a really hard time ensuring every thread gets some execution time at scale. There are some ways to make this better with locks and queues when doing the same task across 100s/1000s of threads but not with API endpoints where the framework author has no idea what the user is going to put in the route handler.
Our solution
Knowing we couldn’t rely on sync threads only, we decided early on to throw gevent at it. It worked well for the scale issue but I don’t recommend it. We subclassed the APIRouter and shimmed in a wrapper that would convert sync route handler functions to async by running them in greenlets wrapped in a future. This scaled way better and what we have run for the last 2 years.
Load testing
After some time, we found the development experience with gevent lacking because gevent messes with the PyCharm debugger. So at one point I set out to remove our special gevent hack. For reasons I didn’t agree with, we chose to run only 1 process per instance allowing gevent to do the heavy lifting. I load tested fastapi without gevent in sync only mode with some simple but effective scenarios: download a file from s3, calculate the square root of some numbers over and over, time.sleep, a dns lookup, etc. The S3 case is most interesting because it uses a lot of cpu and i/o. Anyway, fastapi did not scale well when constrained to a single process and default number of threads. It did better when bumping the number of threads allowed in the threadpool but still no where near as well as gevent. In the end, I needed to give fast api something like 10,000 threads in the pool for it to handle the same load with higher latencies. That approach was not going to work.
What we’re doing now
The developer spearheading the single process thing left and now we are re-evaluating the project holistically. So, our current solution is running 8 or 9 processes per instance with the current default in anyio of 40 threads. (Note we don’t use BackgroundTasks so those aren’t taking up space). I ran my same load tests and this worked really well for us. With time passing and that developer gone we focused on reaching the latency/load we actually have as opposed to an unneeded maximum performance. If we do end up having a use case that needs higher scale we will add more instances to server group. Right now we are ok with just 1. Reading this also has me thinking to bump up the number of threads in anyio. 100 sounds good but not sure what makes sense.
What I would do in the future
Honestly, I would much rather use flask with gevent and copy pasta over the pydantic auto-swagger generation code from FastAPI. I’ve also been following the starlite (now lite-star I think) project. If I needed something more like FastAPI I would try and push us to lite-star instead. This is because FastAPI has very limited integration points along the request lifecycle. Everything is done via middleware and that has consequences of ordering. I wish instead I could add response parsers and before request handlers like flask. Lite-star does have these. I want to like async but the ecosystem (internal to work especially but also out in public) is still not very mature. Gevent however, is tried and true and works well for most (sync) things. It is not without its quirks but nothing is for free.
Hope this helps!
1
u/conogarcia Sep 06 '24
hey! Is there a chance that you could share your gevent solution? or at least some basic instructions on what you did.
Thanks!
2
u/Vok250 Apr 14 '23
In the real world I'm never using static cloud resources. It's all serverless, containers, or horizontal auto-scaling. I let the infrastructure handle asynchronous scaling when needed. For FastAPI specifically I've used Mangum: https://mangum.io/ to provide the asynchronous invocation below the ASGI layer. Then all my FastAPI code can just be synchronous.
1
u/hackancuba Apr 14 '23
Oh no, FastAPI is an async framework, than can tolerate some sync routes and stuff, but not really. As w/ anything async, sync stuff will be detrimental. I'm not only referring to particular functions being sync, if they are fast enough, that's OK; I'm more referring to processes, such as fetching 1M objects from the DB and then doing heavy lifting inside a regular for loop: despite that function probably being named as async def, it would be very much sync, and blocking, and thus bad.
So yeah, sync/async is not as easy as it looks, and it is true, in a naive sense of simplicity, FastAPI tried to help devs on grasping async stuff, but maybe it didn't work as well :(
BTW, the magicality is basically running sync code wrapped in an async task, which is then run in the "background" by the loop. But it is pretty much sync still...
The SQLAlchemy project did a lot on this front, trying to get rid of "colours" (sync vs async), but that is a whole other story.
1
u/massive_elbow Apr 15 '23
Should you be using BackgroundTasks if there is a possibility that task is going to use up the entire threadpool? Might be better to farm those tasks out to a celery worker
0
Apr 14 '23
[deleted]
2
u/oatmeal_dreams Apr 14 '23
I also nearly chose FastAPI for a production application. Very glad we scrapped the project.
The more I look at it the more it starts to feel like more of a “toy” than something to go to production with.
So I have a question for you from the other side. I implemented an async view in Django (to proxy and cache some external requests). We don't use 4.2 and psycopg(3) yet so DB and middleware is still sync. Is there similar concerns for what I am doing here with going async in sync Django (with unicorn gunicorn workers) or do you think Django protects the user sufficiently?
Interesting scenario. I haven’t researched this yet and I can’t answer off hand. It’s a bit too complicated to figure out how this would behave from just a quick look at the docs or the code. For example, the WSGI->ASGI adapter is here
https://github.com/django/asgiref/blob/main/asgiref/wsgi.py
And the sync<->async wrappers are documented here and live in the same repo
https://docs.djangoproject.com/en/4.2/topics/async/
What would concern me /get me thinking is, the -> sync conversion defaults to thread_sensitive=True. I think this means that your sync views are going to be (per uvicorn worker) run in a single side-thread so to speak. So per uvicorn worker, sync views will run serially.
This means, I think, that you will have to think about the sync portion of your app as though it were like a “sync worker” kind of deployment of gunicorn WSGI. Namely, have to make sure there are enough workers to handle your traffic, and also take a look that a) you configure timeouts on uvicorn so if one of your sync views blocks/sleeps for a long long time, it doesn’t tie up a worker for too long and b) also just general awareness that your sync views are not going to block for too long (eg consider checking into configure timeouts globally for urllib/requests, assuming your views make any requests on the network).
This is perfectly livable but it just might be different than what some are used to, running sync django with gunicorn async worker (eg gevent patching) and a connection pooler (eg pgbouncer).
I hope that makes sense and I’m not making anything up. My production familiarity so far is only with that scenario I just described (sync django, gunicorn with gevent patching, pgbouncer).
I have run async Django a while back under daphne (ASGI), when the ORM was still fully sync, but it was a sort of toy project internal to a small research lab, so not “production” in any sense. But it worked.
I have quite a lot of faith though in Django, I think their effort to move to introduce async is going to succeed. I have watched some lecture from Andrew Godwin from 3 years ago, and it was encouraging how serious they are to make it work for everyone. Now I think inspired by your question / trying to understand, I will check this talk from him, particularly this last part, from looking at the chapter titles--
1
u/oatmeal_dreams Apr 14 '23
The lecture doesn’t answer the questions I thought based on the chapter titles
1
u/omg_drd4_bbq Apr 14 '23
The more I look at it the more it starts to feel like more of a “toy” than something to go to production with.
Why? At $lastco we ran it in production for two years. The only real issues were with really strange async conditions, like using APScheduler within a server process (wasn't my idea).
1
u/oatmeal_dreams Apr 15 '23
>Why?
It just doesn’t have the kind of lifespan or docs or community/adoption compared to something like Django. Doesn’t mean that it can’t run stably and stuff. The way the project is managed makes me think it might be dying in a few years, and kept alive only by random ML bros who pick it up for their rapid prototype things. The very few examples of major companies using it are all their ML teams building local server things, not big public facing web applications. Stuff like this. And like I linked in the thread, read this comment and the next one:
https://github.com/encode/starlette/issues/1724#issuecomment-1179070351
This stuff seems potentially high quality but it’s just not mature and it’s not going to come with any of the guarantees you get from running something that isn’t so “niche” or “fad.”
2
u/omg_drd4_bbq Apr 14 '23
Yeah, this is a python thing, not a FastApi thing. Python has somewhat less of a red/blue problem than other languages, since you can call sync from async methods, but if your sync call blocks, then your whole process' async stack grinds to a halt. If you have multi-worker with gunicorn you have some isolation against blocking bringing the whole app down, but it'll kill performance.
Mainly just don't mix async and sync (short running sync methods are fine, avoid cpu and IO bound sync methods).
1
u/oatmeal_dreams Apr 15 '23
I think the question is more about whether/how a deployment works, if there are enough people using sync views on uvicorn for it to be trusted and to be able to figure out how to configure it correctly. Just searching, I was unable to determine how it actually works. My guess is that probably sync views get pinned to the sync thread_sensitive thread created by sync_to_async wrapper, which means that sync views would run serialized *per worker* process, and because of thread_sensitive you wouldn’t be able to get them to take advantage of --threads supplied to gunicorn (talking about gunicorn with uvicorn workers, say). So you can only do horizontal scaling of the sync views via worker processes. Which is fine, but this is just a guess, and it would be nice if there were some official docs explaining whether it is a good idea to run this way and what some of the deployment considerations are.
6
u/omg_drd4_bbq Apr 14 '23 edited Apr 14 '23
If you are an experienced python developer, best practices with FastAPI is definitely
async def. If you aren't comfortable withasyncpatterns in python, use sync methods and scale horizontally. Synchronous endpoint methods are executed using the thread pool as mentioned, and IIRC each time an endpoint is called, it spawns a thread. This is "safer" if you don't really know how to use async well (which runs the risk of cpu-blocking or I/O blocking if you call into the wrong sync method or your IO isn't actuallyasync), but it does not scale as well to number of requests concurrently.From that link,
That's not just FastApi, that's async python in general.
At my last company, we ran FastAPI in prod, all async methods, behind gunicorn asgi runners, in containers in autoscaling groups. The only issues we ran into were when trying to bridge other async/sync stuff, like APScheduler for tasks. Imho we should not have put those in the server process at all, but that wasn't my call.
Also we started with SQLAlchemy in sync mode at first but then migrated to 1.4 with async and that was a huuuge win.
Don't fear the async... cowbell
From your other comment down thread
I think that is indeed a shortcoming of the docs. They are comparable up to a certain loading and within certain usage patterns. In production real-world apps, it's not hard to overstep load limitations, or do something goofy which breaks your metrics.
I highly recommend instrumenting your app so you can see when things go sideways. Opentelemetry-python is what I use.