Signal Handling
Relevant source files
The following files were used as context for generating this wiki page:
Signal handling in Uvicorn is a critical system responsible for managing the lifecycle of server processes, coordinating graceful shutdowns, and facilitating worker management in multiprocess and development (reload) modes. It ensures that Unix signals like SIGINT, SIGTERM, and SIGHUP are correctly intercepted and translated into internal state changes, such as setting exit flags or triggering process restarts.
The architecture differentiates between the supervisor level (which manages workers) and the protocol level (which handles individual connection lifecycles during shutdown). Recent updates have introduced cooperative signal handling and improved support for Windows-specific signals like SIGBREAK.
Sources: CHANGELOG.md:144, CHANGELOG.md:213, uvicorn/supervisors/basereload.py
Supervisor Signal Management
Supervisors, such as BaseReload and Multiprocess, utilize a signal_queue or internal event flags to manage process state. When a signal is caught, the supervisor typically sets a should_exit event or appends the signal to a queue for processing in the main loop.
Lifecycle Control Flow
The following diagram illustrates how a supervisor handles an exit signal to shut down the server process and its workers.
The supervisor's run() method continuously polls for restarts or exit signals. In BaseReload, the pause() method checks the should_exit event, which is triggered by the signal_handler.
Sources: uvicorn/supervisors/basereload.py:44-62, tests/supervisors/test_reload.py:276-291
Supported Signals
Uvicorn supports various signals depending on the operating system and the supervisor mode:
| Signal | Mode/Platform | Action |
|---|---|---|
SIGINT | All | Initiates graceful shutdown. |
SIGTERM | All | Initiates graceful shutdown; supervisors terminate processes before joining. |
SIGHUP | Multiprocess | Triggers restart_all() to refresh all worker processes. |
SIGTTIN | Multiprocess | Increases the number of active worker processes. |
SIGTTOU | Multiprocess | Decreases the number of active worker processes. |
SIGBREAK | Windows | Handled as an interrupt/shutdown signal on Windows platforms. |
SIGQUIT | Gunicorn Worker | Added to UvicornWorker for compatibility. |
Sources: CHANGELOG.md:144, CHANGELOG.md:213, tests/supervisors/test_multiprocess.py:108-164
Protocol-Level Shutdown Logic
When a supervisor triggers a shutdown, it calls the shutdown() method on active protocols (HTTP or WebSocket). This ensures that existing connections are handled gracefully rather than being abruptly terminated.
HTTP Protocol Shutdown
In the HttpToolsProtocol, the shutdown process checks the state of the current request-response cycle. If a cycle is active and incomplete, it sets keep_alive to False to ensure the connection closes after the current response is sent.
WebSocket Protocol Shutdown
WebSocket protocols must handle the handshake state during shutdown. If the handshake is complete, a close frame (often code 1012) is sent to the client.
- websockets-sansio: Sends a close frame with code
1012if the handshake is complete; otherwise, it sends a500 Internal Server Errorresponse before closing the transport. - wsproto: Similarly checks
handshake_completeand sends aCloseConnectionevent with code1012.
Sources: uvicorn/protocols/websockets/websockets_sansio_impl.py:126-136, uvicorn/protocols/websockets/wsproto_impl.py:133-141
Multiprocess Coordination
In multiprocess mode, the Multiprocess supervisor manages a collection of Process instances. Signal handling is used to stagger worker restarts or scale the worker pool dynamically.
- Worker Health Checks: The supervisor monitors worker PIDs. If a process is killed, the health check mechanism detects it and restarts the worker.
- Signal Propagation: Signals like
SIGTERMare propagated to child processes to ensure they exit. The supervisor terminates and then joins these processes to prevent zombie processes. - Scaling:
SIGTTINandSIGTTOUallow manual adjustment of the worker count without restarting the main supervisor.
Sources: tests/supervisors/test_multiprocess.py:80-94, tests/supervisors/test_multiprocess.py:138-164, CHANGELOG.md:329-330
Implementation Details
Signal Handlers in Non-Main Threads
Uvicorn includes logic to skip the installation of signal handlers when not running in the main thread. This allows Server instances to be used in multithreaded contexts without causing errors related to signal registration (which Python only allows in the main thread).
Sources: CHANGELOG.md:465-468
Reload Logic and Signals
The BaseReload class provides a common interface for StatReload and WatchFilesReload. It encapsulates the socket management and ensures that file descriptor fd=0 is treated as a valid descriptor during reload cycles.
Sources: uvicorn/supervisors/basereload.py
Conclusion
Signal handling in Uvicorn provides the glue between external OS commands and internal server lifecycle management. By implementing specific handlers for various Unix signals and Windows events, Uvicorn supports graceful degradation of connections, dynamic worker scaling, and robust development reloading. The system is designed to be "cooperative," ensuring that even under heavy load or during shutdown, protocols have an opportunity to finalize transactions.