Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / server-lifecycle-and-deployment

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:

  1. Create an application or resolve an application factory.
  2. Set up an application runner.
  3. Run on_startup handlers and enter cleanup contexts.
  4. Freeze the application so its routing and lifecycle contracts do not change while it serves.
  5. Start one or more sites.
  6. 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 typeService endpointTypical deployment use
TCPSiteTCP host and portDirect HTTP or HTTPS service
UnixSiteUnix-domain socket pathLocal proxy or process supervisor
SockSiteExisting socketGunicorn or another socket owner
NamedPipeSiteWindows named pipeWindows 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.

SignalPurposeRelative position
on_startupOpen resources needed by handlersBefore the application serves requests
on_shutdownStop background work and begin service drainAfter sites stop and before connection wait ends
on_cleanupClose resources owned by the applicationAfter 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

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, and on_cleanup.
  • Changes to run_app binding inputs must stay aligned with CLI hostname, port, path, and extra-argument handling.
  • Changes to site creation must preserve SockSite use for pre-bound Gunicorn sockets and the one-server-to-many-sites model.
  • Changes to shutdown_timeout must 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/SIGTERM handling and Gunicorn-managed worker signals.

Important failure modes

TriggerConsequenceGuard
A site starts before runner setupSite creation or start fails because no request server existsCall runner.setup() before creating or starting a site
Startup hook or socket binding failsThe service does not become ready, but cleanup still unwinds started resourcesKeep resource release in lifecycle hooks or cleanup contexts
A Gunicorn worker fails before all sockets bindGunicorn sees a worker boot failure instead of a ready workerTreat readiness as reached only after runner setup and every SockSite starts
An active handler exceeds shutdown_timeoutThe handler is cancelled and its connection can close before its response completesSet a timeout that matches the work needed during deployment and make handlers stop cleanly
A cleanup context exit raisesCleanup reports the error; several errors are grouped in CleanupErrorTreat cleanup errors as release failures that need operational visibility
CLI entry value is not a valid module:function or the attribute is absentArgument parsing stops before the service startsExpose an importable factory with the required name
Worker application input is not an Application or an async factory returning an Application or AppRunnerWorker startup fails before it reports readinessUse one of the supported worker application forms
A worker abort signal is receivedThe worker exits with a failing status without graceful cleanupUse normal quit signals when active requests must drain
Signal handlers are requested on an event loop or platform without supportRunner signal registration is skippedUse supervisor-owned signals or call cleanup from the owning process

Key files

FileWhy to read it
aiohttp/web_runner.pyDefines runners, sites, signal registration, endpoint binding, and the shared shutdown order.
aiohttp/web_app.pyDefines application lifecycle signals, freezing, subapplication propagation, and cleanup contexts.
aiohttp/web.pyConnects local execution, site selection, event-loop ownership, graceful exits, and the aiohttp.web CLI.
aiohttp/web_server.pyDefines connection ownership and the server-side drain and shutdown boundary.
aiohttp/worker.pyShows how Gunicorn owns worker processes and sockets while aiohttp owns application startup, readiness, and cleanup.
tests/test_run_app.pyDemonstrates binding variants, signal exits, startup failure cleanup, task cleanup, and handler shutdown limits.
tests/test_web_runner.pyDemonstrates runner-site ownership, endpoint types, signal registration, and site state rules.
tests/test_worker.pyDemonstrates worker readiness, supported application forms, stop conditions, and worker signals.