Shutdown event sometimes does not trigger when reloading (watchfiles) #2392
Unanswered
Blue9
asked this question in
Potential Issue
Replies: 2 comments
-
If anyone else is running into the reloading issue, I have a fork here with the first change, adding |
Beta Was this translation helpful? Give feedback.
0 replies
-
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.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Environment:
When running uvicorn with reloading, 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.py
and 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. For example, these are the logs I see when saving twice in quick succession:Server is shutting down
is not printed a second time. I believe this is because in Server._serve(), we eagerly return ifself.should_exit
is already set to True here. If I change this to the following:The shutdown event always runs when reloading and resources are cleaned up.
Happy to open a PR for the above if this is a welcome change. If not, is there another change we could make to fix this issue? This is important because I need to clean up resources in my shutdown event.
Another edge case is that any time two signals arrive in quick succession, if the second one is a SIGINT (so for example, save the above file and press Ctrl+C in your terminal immediately after), uvicorn interprets that as a force-exit and will not communicate the shutdown event. It should ideally check that both signals are SIGINTs (so a double Ctrl+C) to avoid falsely setting
force_exit
.Beta Was this translation helpful? Give feedback.
All reactions