Multiprocessing Manager
Relevant source files
The following files were used as context for generating this wiki page:
The Multiprocessing Manager is a core component of Uvicorn responsible for managing multiple worker processes to handle concurrent HTTP and WebSocket connections. It implements a supervisor pattern where a parent process orchestrates the lifecycle of several child "worker" processes, ensuring high availability through health checks and signal-based scaling.
This system is primarily utilized when the workers configuration is set to a value greater than one. It enables Uvicorn to utilize multiple CPU cores by distributing the application load across independent Python processes, bypassing the limitations of the Global Interpreter Lock (GIL) for CPU-bound tasks.
Sources: uvicorn/supervisors/multiprocess.py:1-12, README.md:1-50, CHANGELOG.md:120-125
Architecture and Components
The multiprocessing architecture consists of two primary classes: Multiprocess (the supervisor) and Process (the worker wrapper).
The Multiprocess Supervisor
The Multiprocess class maintains the desired state of the worker pool. It handles signal propagation from the operating system to the workers and monitors their health.
Sources: uvicorn/supervisors/multiprocess.py:84-105
The Process Wrapper
The Process class acts as a high-level abstraction over multiprocessing.Process. It facilitates communication between the parent and child via a multiprocessing.Pipe to perform "ping-pong" health checks.
Sources: uvicorn/supervisors/multiprocess.py:27-45
The following diagram illustrates the relationship between the Supervisor and its managed Worker processes:
This diagram shows the hierarchical management structure where the supervisor controls wrappers that in turn manage the actual OS-level subprocesses.
Sources: uvicorn/supervisors/multiprocess.py:32-35, uvicorn/supervisors/multiprocess.py:94-98
Process Lifecycle and Health Monitoring
The supervisor ensures that the configured number of workers are always running. If a child process dies or becomes unresponsive, the supervisor detects this during its main loop and restarts the process.
Health Check Mechanism (Ping-Pong)
To detect hung processes (where the process is still "alive" in the OS but not processing events), the manager uses a bidirectional pipe:
- The parent sends a
b"ping"message. - The child process runs a dedicated daemon thread that listens for pings and immediately returns a
b"pong". - If the parent does not receive a response within the
timeout_worker_healthcheckperiod, the process is considered dead and is killed.
Sources: uvicorn/supervisors/multiprocess.py:37-55, uvicorn/supervisors/multiprocess.py:141-158
The sequence diagram details the synchronous health check performed on a 0.5-second interval.
Sources: uvicorn/supervisors/multiprocess.py:129-135, tests/supervisors/test_multiprocess.py:48-58
Signal Handling and Dynamic Scaling
The Multiprocessing Manager responds to various OS signals to manage the cluster without restarting the parent process.
Supported Signals
| Signal | Handler | Action |
|---|---|---|
SIGINT / SIGTERM | handle_int / handle_term | Graceful shutdown of all workers and exit. |
SIGHUP | handle_hup | Restarts all worker processes sequentially. |
SIGTTIN | handle_ttin | Dynamically increases the worker count by one. |
SIGTTOU | handle_ttou | Dynamically decreases the worker count by one (minimum 1). |
SIGBREAK | handle_break | Windows-specific graceful shutdown. |
| Sources: uvicorn/supervisors/multiprocess.py:16-24, uvicorn/supervisors/multiprocess.py:175-205 |
Dynamic Scaling Logic
When SIGTTIN is received, the supervisor increments self.processes_num and immediately spawns a new Process instance. Conversely, SIGTTOU removes the last process from the self.processes list, terminates it, and joins it.
Sources: uvicorn/supervisors/multiprocess.py:192-205, tests/supervisors/test_multiprocess.py:126-155
Configuration Options
The behavior of the Multiprocessing Manager is dictated by several attributes within the uvicorn.Config object.
| Parameter | Type | Default | Description |
|---|---|---|---|
workers | int | 1 (or $WEB_CONCURRENCY) | Number of worker processes to maintain. |
timeout_worker_healthcheck | float | 5.0 | Seconds to wait for a "pong" response before restarting a worker. |
limit_max_requests_jitter | int | 0 | Used to stagger worker restarts when request limits are reached. |
reset_contextvars | bool | False | Isolates ASGI request context between tasks. |
| Sources: uvicorn/config.py, CHANGELOG.md:100-110, uvicorn/supervisors/multiprocess.py:144 |
Implementation Details
Process Target Wrapping
The Process.target method is a wrapper around the user-provided application target. It performs two critical setup tasks:
- Windows Signal Compatibility: Since Windows does not support
SIGTERM, the wrapper mapsSIGBREAKtosignal.raise_signal(signal.SIGTERM)to ensure consistent shutdown logic across platforms. - Pong Thread: It starts the daemon thread responsible for responding to the supervisor's health checks.
Sources: uvicorn/supervisors/multiprocess.py:51-64
def target(self, sockets: list[socket] | None = None) -> Any:
if os.name == "nt":
signal.signal(
signal.SIGBREAK,
lambda sig, frame: signal.raise_signal(signal.SIGTERM),
)
threading.Thread(target=self.always_pong, daemon=True).start()
return self.real_target(sockets)
Sources: uvicorn/supervisors/multiprocess.py:57-64
Termination Logic
Termination differs by platform. On Unix, os.kill(pid, signal.SIGTERM) is used. On Windows, os.kill(pid, signal.CTRL_BREAK_EVENT) is sent because TerminateProcess (used by process.terminate()) does not allow for graceful cleanup in the child.
Sources: uvicorn/supervisors/multiprocess.py:70-80, tests/supervisors/test_multiprocess.py:84-95
Summary
The Multiprocessing Manager provides Uvicorn with a robust, scalable execution model. By decoupling the supervisor from the workers and implementing a proactive health-check mechanism, it ensures that application instances remain available and can be dynamically scaled or rotated via standard OS signals. This module is essential for production deployments where performance and reliability are paramount.
Sources: uvicorn/supervisors/multiprocess.py:120-135, CHANGELOG.md:120-125