Auto-Reloading
Relevant source files
The following files were used as context for generating this wiki page:
Auto-reloading is a development feature in Uvicorn that monitors source code changes and automatically restarts the server process. This ensures that modifications to the application code are reflected immediately without manual intervention. The system utilizes a supervisor-worker architecture where a parent "reloader" process manages a child subprocess running the actual ASGI application.
Sources: uvicorn/main.py:447-456, uvicorn/supervisors/basereload.py:30-33
Architecture and Core Logic
The auto-reload system is built upon a base class BaseReload which defines the lifecycle of the reloader process. When auto-reload is enabled, Uvicorn initializes a supervisor that wraps the server's execution.
The Supervisor Lifecycle
The supervisor follows a specific sequence:
- Startup: Registers signal handlers (SIGINT, SIGTERM) and starts the initial worker subprocess.
- Monitoring Loop: Iterates through a detection cycle to check for file changes.
- Restart: If changes are detected, it terminates the existing worker subprocess and spawns a new one using the same configuration and sockets.
- Shutdown: Closes sockets and terminates the worker when the supervisor is stopped.
Sources: uvicorn/supervisors/basereload.py:47-58, uvicorn/supervisors/basereload.py:80-91
Process Management Flow
This diagram illustrates how the reloader process manages the worker subprocess during a code change event.
Reload Strategies
Uvicorn implements two primary strategies for detecting file changes, selected based on environment capabilities and configuration.
StatReload
StatReload is a polling-based implementation. It periodically iterates through all .py files within the configured reload_dirs and compares their current modification time (mtime) against a cached value.
- Logic: It uses
path.resolve().rglob("*.py")to find files. - Limitation: It does not support
reload_includesorreload_excludespatterns directly; it strictly monitors Python files.
Sources: uvicorn/supervisors/statreload.py:28-48
WatchFilesReload
WatchFilesReload uses the watchfiles library for more efficient, event-driven monitoring. It is the preferred reloader when the watchfiles package is installed.
- Filter Logic: It uses a
FileFilterclass to determine if a specific file change should trigger a restart. - Pattern Matching: Supports complex glob patterns via
reload_includesandreload_excludes. - Default Excludes: Automatically ignores common patterns such as
.*,.py[cod], and~*.
Sources: uvicorn/supervisors/watchfilesreload.py:14-43, uvicorn/supervisors/watchfilesreload.py:69-80
Configuration and Directory Resolution
The Config class handles the complex task of resolving which directories to watch. It merges explicit directory paths with glob patterns to create a final set of unique, absolute paths.
| Option | Type | Default | Description |
|---|---|---|---|
reload | bool | False | Enables the auto-reload feature. |
reload_dirs | list[str] | [CWD] | Specific directories to watch for changes. |
reload_delay | float | 0.25 | Delay (in seconds) between change detection cycles. |
reload_includes | list[str] | [] | Glob patterns to include (requires watchfiles). |
reload_excludes | list[str] | [] | Glob patterns or directories to exclude. |
Sources: uvicorn/config.py:321-332, uvicorn/config.py:381-420
Directory Normalization
Uvicorn performs normalization on reload_dirs:
- Resolves all paths to absolute paths.
- Filters out non-existent directories.
- Removes redundant subdirectories (e.g., if watching
/app, it removes/app/srcfrom the list). - Adds directories derived from glob patterns in
reload_includes.
Sources: uvicorn/config.py:270-302, uvicorn/config.py:400-410
Implementation Details
Subprocess Spawning
The reloader does not run the application in its own thread; it uses uvicorn._subprocess.get_subprocess to create a completely separate OS process. This is necessary because Python cannot easily "unload" modules once they have been imported, making a process restart the only reliable way to apply code changes.
Sources: uvicorn/supervisors/basereload.py:77-78, uvicorn/main.py:452-456
Operating System Variations
- Windows: Relies on
signal.CTRL_C_EVENTto terminate the worker. There is a known workaround involving astdout.flush()to ensure the signal is processed. - Unix: Uses
process.terminate()for graceful worker shutdown.
Sources: uvicorn/supervisors/basereload.py:81-89, tests/supervisors/test_reload.py:230-240
Class Relationship Diagram
The following diagram describes the inheritance and interaction between the reload supervisor classes.
Conclusion
Uvicorn's auto-reloading system provides a robust mechanism for development environments by abstracting file system monitoring into interchangeable strategies (StatReload and WatchFilesReload). By managing the application lifecycle through a dedicated supervisor process, it ensures that code changes are applied cleanly via process isolation, while handling the complexities of directory resolution and cross-platform signal management.