Server lifecycle and deployment
The server lifecycle turns an Application into a running service and then closes it in a controlled order. Runners prepare the application and its request server. Sites expose that server on network or local endpoints. The local API, command-line entry point, and Gunicorn worker use the same lifecycle so that startup hooks run before traffic and cleanup hooks run after traffic stops.
Lifecycle model
Startup sequence
Startup prepares application state before the service accepts requests. aiohttp/web_runner.py uses AppRunner to freeze the startup signal, send the application startup signal, freeze the application, and create the request server. Sites then bind their endpoints to that server.
The main stages are:
- Create an application or resolve an application factory.
- Set up an application runner.
- Run
on_startuphandlers and enter cleanup contexts. - Freeze the application so its routing and lifecycle contracts do not change while it serves.
- Start one or more sites.
- Keep the event loop active while the server accepts requests.
This diagram shows the relationship between application preparation, endpoint binding, and request service.
flowchart LR
A[Application or factory] --> B[AppRunner setup]
B --> C[Startup signal]
C --> D[Application frozen]
D --> E[Site binding]
E --> F[Request server]
References: aiohttp/web_runner.py• L347-358 aiohttp/web_runner.py• L439-489 aiohttp/web_app.py• L279-399
Shutdown sequence
Shutdown stops new work and gives active work a bounded time to finish. The runner stops each site first. It then lets already accepted requests enter handling, closes idle connections at the server boundary, sends the application shutdown signal, waits for connection handlers up to shutdown_timeout, and runs application cleanup.
The order matters. on_shutdown is the point for work that must happen while the server still drains active requests. on_cleanup is the point for releasing resources after that drain. run_app also cancels remaining event-loop tasks and closes the loop after the runner finishes.
sequenceDiagram
participant S as Stop signal
participant R as Runner
participant T as Sites
participant H as Active connections
participant A as Application
participant L as Event loop
S->>R: Request graceful stop
R->>T: Stop accepting traffic
R->>H: Begin connection shutdown
R->>A: Send on_shutdown
R->>H: Wait up to shutdown_timeout
R->>A: Send on_cleanup
R->>L: Cancel remaining tasks and close loop
References: aiohttp/web_runner.py• L364-389 aiohttp/web_server.py• L116-123 aiohttp/web.py• L484-507
Runner and site management
Runner roles
A runner owns one request server and the set of sites that expose it. AppRunner connects an Application to the server and maps runner shutdown to application shutdown and cleanup. ServerRunner serves an already-created low-level Server when application lifecycle hooks are not part of the runner.
The runner is the shared coordination point for multiple endpoints. A site must be created after runner setup. Starting a site registers it with the runner, and runner cleanup stops all registered sites.
References: aiohttp/web_runner.py• L92-124 aiohttp/web_runner.py• L311-397 aiohttp/web_runner.py• L414-437 aiohttp/web_runner.py• L439-515
Binding options
Sites describe where the same request server listens. TCP sites serve host and port bindings. Unix sites serve a file-system socket. Socket sites adopt sockets supplied by another process manager. Named-pipe sites provide the Windows pipe form when the event loop supports it.
run_app can create several sites from host, path, or socket inputs. This lets one application serve more than one address without creating more than one application server.
| Site type | Service endpoint | Typical deployment use |
|---|---|---|
TCPSite | TCP host and port | Direct HTTP or HTTPS service |
UnixSite | Unix-domain socket path | Local proxy or process supervisor |
SockSite | Existing socket | Gunicorn or another socket owner |
NamedPipeSite | Windows named pipe | Windows local transport |
References: aiohttp/web_runner.py• L92-295 aiohttp/web.py• L303-386 tests/test_web_runner.py• L222-300
Application lifecycle signals
Lifecycle signals
An application exposes three ordered lifecycle signals for resource owners. Startup prepares shared resources. Shutdown tells those resources that request service is ending. Cleanup releases resources after the server has drained its connections.
Subapplications receive the same lifecycle phases through the parent application. The application freezes its lifecycle signals during preparation. This means lifecycle registration must be complete before the runner is set up.
| Signal | Purpose | Relative position |
|---|---|---|
on_startup | Open resources needed by handlers | Before the application serves requests |
on_shutdown | Stop background work and begin service drain | After sites stop and before connection wait ends |
on_cleanup | Close resources owned by the application | After connection shutdown |
References: aiohttp/web_app.py• L72-132 aiohttp/web_app.py• L214-250 aiohttp/web_app.py• L264-276 aiohttp/web_app.py• L319-365
Cleanup contexts
cleanup_ctx pairs resource setup with resource release in one lifecycle unit. Each context enters during startup and exits during cleanup in reverse order. This gives dependent resources a stack-like lifetime and also lets partially completed startup unwind safely.
If one or more cleanup exits fail, cleanup reports the failure. A single failure is raised directly. Several failures are grouped in CleanupError so callers can see that cleanup was not fully successful.
References: aiohttp/web_app.py• L125-133 aiohttp/web_app.py• L353-365 aiohttp/web_app.py• L412-450 tests/test_run_app.py• L845-861
Local entry points
run_app entry point
run_app is the self-managed entry point for local or simple production use. It creates or accepts an event loop, resolves an application value or awaitable factory, builds an AppRunner, creates the requested sites, and keeps the loop alive until a graceful exit or an error occurs.
Its binding inputs cover TCP hosts, Unix paths, and existing sockets. It also passes server settings such as keep-alive and shutdown timeouts into the runner. The default signal handling converts SIGINT and SIGTERM into a graceful exit, while the final loop cleanup handles pending tasks and asynchronous generators.
References: aiohttp/web.py• L279-399 aiohttp/web.py• L426-507 aiohttp/web_runner.py• L84-89 tests/test_run_app.py• L123-183 tests/test_run_app.py• L818-842
Command-line entry point
The aiohttp.web command-line entry point loads an application factory named by module:function. It passes unknown command-line arguments to that factory, maps hostname, port, and Unix path options to run_app, and reports invalid module or function names as command-line errors.
The command uses TCP on localhost:8080 by default. When only a Unix path is given, it runs without a TCP binding. The command exits with a stopped message after run_app returns.
References: aiohttp/web.py• L510-577 tests/test_web_cli.py• L10-69 tests/test_web_cli.py• L87-160
Worker deployment
Gunicorn worker
GunicornWebWorker adapts Gunicorn process management to the aiohttp runner model. Each worker creates its event loop after the process fork. It accepts an Application directly or an async factory that returns an Application or AppRunner. It binds the sockets supplied by Gunicorn through SockSite and passes Gunicorn's backlog and graceful-timeout settings into the aiohttp sites and runner.
The worker reports itself ready only after application startup and all socket bindings succeed. It keeps its boot state false during that preparation, so a startup or binding error is treated as a worker boot failure instead of a normal worker exit. After readiness, it sends periodic notices to Gunicorn while alive. A UV-loop variant selects the uvloop event-loop policy before normal worker setup.
References: aiohttp/worker.py• L33-123 aiohttp/worker.py• L251-255 tests/test_worker.py• L64-153
Worker stop conditions
The worker leaves its serve loop when Gunicorn asks it to stop, when it reaches its request limit, or when it detects that its parent process changed. It then calls runner cleanup so sites close and application shutdown hooks run within the configured graceful window. The worker finally shuts down asynchronous generators and closes its event loop.
Worker signals use Gunicorn callbacks for normal quit and abort paths. A normal quit marks the worker inactive and wakes its wait so cleanup starts without waiting for the next periodic notice. An abort sets a failing exit code and terminates at once. The worker also restores the default SIGCHLD behavior so subprocess exit codes from application code reach the expected owner.
References: aiohttp/worker.py• L125-216 aiohttp/worker.py• L251-255 tests/test_worker.py• L156-214 tests/test_worker.py• L230-273
Related server pages
The web server architecture page gives the parent view of accepted connections and application handlers. Read server request processing for the request path after startup. Read server routing and responses for route matching and response behavior.
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to runner shutdown order must preserve the contract between
on_shutdown, active connection draining, andon_cleanup. - Changes to
run_appbinding inputs must stay aligned with CLI hostname, port, path, and extra-argument handling. - Changes to site creation must preserve
SockSiteuse for pre-bound Gunicorn sockets and the one-server-to-many-sites model. - Changes to
shutdown_timeoutmust account for the Gunicorn worker's graceful-timeout budget. - Changes to accepted application forms must stay consistent across
run_app,AppRunner, the CLI factory, and the Gunicorn worker. - Changes to worker readiness must preserve the distinction between boot failure before socket binding and a normal exit after the worker becomes ready.
- Changes to signal registration must preserve the distinction between runner-managed
SIGINT/SIGTERMhandling and Gunicorn-managed worker signals.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A site starts before runner setup | Site creation or start fails because no request server exists | Call runner.setup() before creating or starting a site |
| Startup hook or socket binding fails | The service does not become ready, but cleanup still unwinds started resources | Keep resource release in lifecycle hooks or cleanup contexts |
| A Gunicorn worker fails before all sockets bind | Gunicorn sees a worker boot failure instead of a ready worker | Treat readiness as reached only after runner setup and every SockSite starts |
An active handler exceeds shutdown_timeout | The handler is cancelled and its connection can close before its response completes | Set a timeout that matches the work needed during deployment and make handlers stop cleanly |
| A cleanup context exit raises | Cleanup reports the error; several errors are grouped in CleanupError | Treat cleanup errors as release failures that need operational visibility |
CLI entry value is not a valid module:function or the attribute is absent | Argument parsing stops before the service starts | Expose an importable factory with the required name |
Worker application input is not an Application or an async factory returning an Application or AppRunner | Worker startup fails before it reports readiness | Use one of the supported worker application forms |
| A worker abort signal is received | The worker exits with a failing status without graceful cleanup | Use normal quit signals when active requests must drain |
| Signal handlers are requested on an event loop or platform without support | Runner signal registration is skipped | Use supervisor-owned signals or call cleanup from the owning process |
Key files
| File | Why to read it |
|---|---|
| aiohttp/web_runner.py | Defines runners, sites, signal registration, endpoint binding, and the shared shutdown order. |
| aiohttp/web_app.py | Defines application lifecycle signals, freezing, subapplication propagation, and cleanup contexts. |
| aiohttp/web.py | Connects local execution, site selection, event-loop ownership, graceful exits, and the aiohttp.web CLI. |
| aiohttp/web_server.py | Defines connection ownership and the server-side drain and shutdown boundary. |
| aiohttp/worker.py | Shows how Gunicorn owns worker processes and sockets while aiohttp owns application startup, readiness, and cleanup. |
| tests/test_run_app.py | Demonstrates binding variants, signal exits, startup failure cleanup, task cleanup, and handler shutdown limits. |
| tests/test_web_runner.py | Demonstrates runner-site ownership, endpoint types, signal registration, and site state rules. |
| tests/test_worker.py | Demonstrates worker readiness, supported application forms, stop conditions, and worker signals. |