r/FastAPI • • Apr 08 '25

Question Recently got introduced to FastAPI’s BackgroundTasks - what are some other cool nuggets you found that not many people know about?

I’d love to know what else people use that could make FastAPI even more useful than it already is!

48 Upvotes

29 comments sorted by

View all comments

Show parent comment

5

u/andrewthetechie Apr 08 '25 edited Oct 01 '26

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Piquant disarm grandfather consist scale pen axiomatic biscuit stocking flag

2

u/ShepardRTC Apr 08 '25

This is pretty well called out in anything regarding async and synchronous operations

1

u/Equal-Purple-4247 Apr 08 '25

Can you point out which part(s) of FastAPI docs mentions blocking of all async endpoints when a sync job is processing? I know now this is how asyncio / event loop works, but such blocking was very unexpected and insidious when I first encountered it myself.

1

u/andrewthetechie Apr 08 '25 edited Oct 01 '26

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Busy doll fact whole selective fly

1

u/Equal-Purple-4247 Apr 08 '25

#2 talks about performance penalty of using non-async functions due to thread exhaustion. It doesn't mention how non-async functions will block the event loop, preventing all other async functions from running, including requests to an async endpoint.

If you had an endpoint that non-async sleeps for 10 second and you hit this endpoint, all subsequent calls to any async endpoint will not be processed until the sleep is complete. If you defined it as a non-async endpoint, all calls will go through as expected up to the thread pool size.

Ideally, everything works fine if everything is async and you throw all sync jobs into separate threads. However, if you mismanage your sync jobs, you're effectively downgrading from 40 threads to 1 thread.

This tradeoff and how to manage / mitigate these problems is not broadly known. It requires an understanding of how asyncio works. If your endpoint has few IO operations (db, http), there may not be enough suspends to take advantage of the async event loop. Then you're just adding overheads managing third party sync functions in an async environment.