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 / web-server

Web server architecture

aiohttp turns a configured application into an asynchronous web service. It accepts connections through one or more listening sites, converts HTTP data into requests, passes each request to the application, and manages response delivery and orderly shutdown. The main path is the Application handled by an AppRunner; lower-level users can provide a Server and use a ServerRunner instead. See request processing, routing and responses, and application lifecycle and deployment for the child views of this architecture.

Server architecture

The server is a layered path from a listening socket to an application handler. A site owns the external endpoint, a runner connects that endpoint to a server factory, and a request handler owns the connection while it serves one or more HTTP requests.

This diagram shows how an accepted connection reaches the application and returns a response.

flowchart LR
    Client[HTTP client] --> Site[Listening site]
    Site --> Protocol[Request handler]
    Protocol --> Server[Server]
    Server --> App[Application handler]
    App --> Response[HTTP response]
    Response --> Client

The site layer supports TCP, Unix sockets, named pipes on supported Windows event loops, and already-open sockets. The runner can attach more than one site to the same server, so one application can serve several endpoints while sharing request handling and shutdown rules. References: aiohttp/web_runner.py• L92-118, aiohttp/web_runner.py• L126-295

Listening sites

Listening sites translate deployment endpoints into asyncio servers. They bind a host and port, Unix path, named pipe, or supplied socket, then ask the runner's server factory to create a protocol for each accepted connection. TLS is applied at this boundary when the site receives an SSL context.

The site choices map to deployment needs:

SiteEndpoint role
TCPSiteNetwork HTTP or HTTPS endpoint
UnixSiteLocal Unix-domain endpoint
NamedPipeSiteWindows named-pipe endpoint
SockSiteEndpoint backed by a socket supplied by another process or service manager

Each started site registers with its runner. Stopping a site prevents new connections from that endpoint while the shared server remains available through other registered sites. References: aiohttp/web_runner.py• L92-123, aiohttp/web_runner.py• L126-295

Connection ownership

The Server is the connection manager between asyncio transports and request handlers. It creates a RequestHandler for each accepted connection, keeps track of active connections, builds request objects, and exposes the application callable that processes them.

The server also provides the boundary for shared connection policy. It carries request-handler settings such as keep-alive behavior and access logging, counts handled requests, and closes or waits for connections during shutdown. References: aiohttp/web_server.py• L32-75, aiohttp/web_server.py• L77-142

Request processing

The request handler is the per-connection protocol that turns incoming bytes into application work. It parses HTTP messages, queues requests that arrive on the same connection, creates a request object, and awaits the configured application handler.

This sequence shows the main request path; routing and response behavior are described in server routing and responses.

sequenceDiagram
    participant C as Client
    participant H as Request handler
    participant A as Application
    participant R as Response writer

    C->>H: HTTP bytes
    H->>H: Parse request and payload
    H->>A: Request object
    A-->>H: Stream response
    H->>R: Prepare and write response
    R-->>C: HTTP response bytes
    H->>H: Keep alive or close connection

The handler isolates each application call in an asyncio task. It converts protocol errors and application failures into HTTP error responses when possible, records access information, and treats a broken connection as a reason to stop response work. It bounds the queue of parsed pipelined messages and pauses transport reads when a busy handler reaches that bound. Reading resumes after the queue drains to its low-water mark. If a protocol upgrade is not accepted, bytes held after its boundary return to the HTTP parser so later pipelined requests remain part of the normal request flow. References: aiohttp/web_protocol.py• L477-624, aiohttp/web_protocol.py• L690-732, aiohttp/web_protocol.py• L734-819, aiohttp/web_protocol.py• L895-930

Connection reuse

Keep-alive lets one connection carry more than one request. After a response, the handler follows the response's keep-alive decision and starts an idle timeout; a close request, an incomplete payload, a client disconnect, or a server shutdown ends the connection instead.

The handler drains unread request data for a limited lingering period before closing. This protects the next connection state from leftover bytes while avoiding an indefinite wait for a client that does not finish its payload. Body draining can also expose bytes held after a deferred protocol upgrade, which the handler then returns to HTTP message processing when the upgrade does not take effect. References: aiohttp/web_protocol.py• L565-624, aiohttp/web_protocol.py• L626-688, aiohttp/web_protocol.py• L823-887

Application integration

An Application is the service-level handler that gives requests access to routing, middleware, sub-applications, and application state. The AppRunner prepares that application before it creates the shared Server, so accepted connections reach a stable application graph.

The application handler resolves a request, attaches the match result to the request, applies middleware, and invokes the selected route handler. The application can also forward requests into sub-applications selected by a path or domain. This page treats that work as the application boundary; see server routing and responses for request-to-route and route-to-response details. References: aiohttp/web_app.py• L72-132, aiohttp/web_app.py• L217-253, aiohttp/web_app.py• L278-312, aiohttp/web_app.py• L371-399, aiohttp/web_runner.py• L426-476

Application state

Application state provides shared service context for handlers and lifecycle hooks. Middleware and sub-applications extend the request path without changing the transport layer, while the application freeze step marks the handler graph as ready for serving.

Freezing locks routes, middleware, sub-application links, and lifecycle signals before traffic starts. The application then uses startup, shutdown, cleanup, and response-preparation signals so service resources follow the same lifetime as the server. Cleanup contexts pair resource setup with reverse-order release and report cleanup errors to the service owner. References: aiohttp/web_app.py• L122-135, aiohttp/web_app.py• L156-178, aiohttp/web_app.py• L217-253, aiohttp/web_app.py• L311-365, aiohttp/web_app.py• L424-450

Service lifecycle

The runner coordinates the service from setup through cleanup. Setup creates the server and prepares application startup; sites then bind endpoints. Cleanup stops sites first, begins server shutdown, waits for active connection work, and releases application resources.

This diagram shows the order from application creation to graceful service exit.

flowchart LR
    Create[Create application] --> Setup[Runner setup]
    Setup --> Startup[Application startup]
    Startup --> Freeze[Freeze serving graph]
    Freeze --> Bind[Start one or more sites]
    Bind --> Serve[Accept and process requests]
    Serve --> Stop[Stop sites]
    Stop --> Shutdown[Close active connections]
    Shutdown --> Cleanup[Application cleanup]

The ordered shutdown matters. Sites stop accepting new connections before the server closes active ones, and active request handlers get a chance to finish within the configured timeout before the server forces closure. The cleanup path yields to the event loop after sites stop so requests already admitted can begin handling before connection shutdown proceeds. See application lifecycle and deployment for lifecycle hooks, signals, and deployment modes. References: aiohttp/web_runner.py• L298-399, aiohttp/web_runner.py• L426-501

Local process serving

run_app provides a process-level entry point for local or direct deployment. It creates an event loop when needed, builds an AppRunner, chooses sites from host, path, or socket inputs, starts them, and keeps the loop alive until a graceful exit or interruption triggers cleanup.

This mode can serve TCP and Unix endpoints and can use TLS, access logging, socket reuse, and signal handling. The command-line entry point loads an application factory in module:function form before passing it to the same serving path. References: aiohttp/web.py• L279-399, aiohttp/web.py• L426-507, aiohttp/web.py• L510-574

Managed worker serving

The Gunicorn worker adapts a managed process to the same runner and site model. Each worker creates its event loop, obtains an application or runner, sets up the runner, attaches the sockets passed by Gunicorn, and reports readiness only after binding succeeds.

The worker stays alive while Gunicorn considers it healthy and wakes on its periodic notify cycle. It leaves that loop when it receives a stop signal, exceeds its request limit, or detects that its parent process changed; runner cleanup then performs the normal shutdown path. References: aiohttp/worker.py• L33-140, aiohttp/worker.py• L163-214

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to the Server request factory or handler contract must remain compatible with both AppRunner and ServerRunner.
  • Changes to site registration or cleanup order must preserve the rule that sites stop before active connections are shut down.
  • Changes to application startup, sub-application linking, or freeze behavior must keep the full application graph ready before a site accepts traffic.
  • Changes to middleware composition or route resolution must preserve the application handler contract expected by the request protocol.
  • Changes to worker socket setup or readiness reporting must preserve the distinction between a failed boot and a normal worker exit.
  • Changes to keep-alive, pipelining back-pressure, protocol-upgrade handling, or shutdown timeouts must be checked against both direct serving and managed worker graceful time limits.

Important failure modes

TriggerConsequenceGuard
A site is created before runner setupSite creation fails because no server factory existsComplete runner setup before creating sites
The application graph changes after freezeThe change is rejected and the running service keeps its existing graphAdd routes, middleware, state, and sub-applications before startup
A request handler returns no response or an invalid objectThe server creates an internal-server-error response; a response that already sent bytes can force a connection failureReturn a response object from every application handler
Request parsing failsThe request is represented as a bad-request error and the connection is closed after error handlingUse valid HTTP input and keep request limits aligned with clients and proxies
Pipelined requests fill the per-connection message queueTransport reading pauses until request handling drains the queue to its resume thresholdKeep request handlers responsive and avoid blocking the event loop
A protocol upgrade is rejected while later bytes are already bufferedThose bytes could be lost or misread instead of becoming later HTTP requestsLet the request handler replay the buffered tail through the HTTP parser
A request payload remains incomplete after the lingering periodThe connection closes and does not accept another requestRead or discard the request body before returning
Runner setup or socket binding fails in a managed workerThe worker exits before readiness and the process manager treats it as a boot failureValidate application startup and all worker sockets before serving
Shutdown exceeds its timeoutActive handlers or connections are force-closedMake cleanup and request work fit the configured graceful timeout

Key files

FileWhy to read it
aiohttp/web_server.pyDefines the server boundary that owns request factories, connections, and shutdown.
aiohttp/web_protocol.pyShows how an accepted connection becomes parsed requests, application calls, responses, bounded pipelining, protocol upgrades, and keep-alive decisions.
aiohttp/web_runner.pyConnects applications and low-level servers to sites and coordinates setup and cleanup.
aiohttp/web_app.pyDefines the application boundary, route and middleware preparation, sub-application links, lifecycle signals, and application handler.
aiohttp/web.pyShows the direct serving entry point and its endpoint selection.
aiohttp/worker.pyShows how Gunicorn-managed processes reuse the runner and socket model.