Shutdown event sometimes does not trigger when reloading (watchfiles) #2392
Replies: 5 comments
-
|
If anyone else is running into these issues, I have a fork here with the changes, adding |
Beta Was this translation helpful? Give feedback.
-
|
I am really interested in a solution to this. The current implementation seems like it did not consider the shutdown event being used to clean up resources. Is there a way the uvicorn recommends cleaning up resources prior to shutdown instead? |
Beta Was this translation helpful? Give feedback.
-
|
Also, a custom signal handler will not work because uvicorn overrides them before re-raising any signals: https://github.com/encode/uvicorn/blob/0.32.0/uvicorn/server.py#L327. Maybe this block of code should only reset the signal handlers if they are |
Beta Was this translation helpful? Give feedback.
-
|
I'm running into this as well, could someone take a look? |
Beta Was this translation helpful? Give feedback.
-
|
This would be great to have |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Environment:
Per ASGI spec, is it expected that if a server sends a
lifespan.startup.completeevent (it has completed startup), it should always send a correspondinglifespan.shutdownon shutdown? I'm noticing that this is not the case when running with reloading enabled with watchfiles.Specifically, the shutdown lifespan event will not run if there are multiple reloads in quick succession (for example if you save a file twice when using WatchFiles). I haven't observed this behavior with StatReload.
Below is a minimal reproducible example:
Save as
main.pyand runuvicorn --reload main:app(also make sure uvicorn is using watchfiles).Then, in your code editor, save the file two times quickly (you can increase the
asyncio.sleep()duration to make this easier). You should see that the shutdown event is not run when reloading the second time even thoughlifespan.startup.completeis printed. For example, these are the logs I see when saving twice in quick succession:Server is shutting downis not printed a second time. I believe this is because in Server._serve(), we eagerly return ifself.should_exitis already set to True here. If I change this to the following:The shutdown event always runs when reloading and resources are cleaned up.
Another case is if you press ctrl-C twice in succession, that sets force_exit to true here, and we skip the shutdown event here. I understand if that is expected behavior but that can lead to resource leakage if people rely on the shutdown event to clean up resources, as is suggested by FastAPI in their docs.
Beta Was this translation helpful? Give feedback.
All reactions