Skip to content

Server entrypoints

Use serve() to run a standalone server, or Server to control one inside an existing event loop. For startup, readiness, and shutdown examples, see Embedding.

serve

serve(
    app: Application,
    config: Config | None = None,
    *,
    factory: Literal[False] = False,
) -> None
serve(
    app: ApplicationFactory,
    config: Config | None = None,
    *,
    factory: Literal[True],
) -> None
serve(
    app: Application | ApplicationFactory,
    config: Config | None = None,
    *,
    factory: bool,
) -> None
serve(
    app: Application | ApplicationFactory,
    config: Config | None = None,
    *,
    factory: bool = False,
) -> None

Start the server. This is the primary programmatic entrypoint and matches the behavior of the h2corn CLI. For an in-process lifecycle, use Server.

On Unix, the call goes through the multi-worker supervisor, even for workers=1, so signal handling, inherited listeners, and worker lifecycle stay identical to the CLI. On Windows, a single in-process worker is used.

Blocks until the server is asked to shut down via one of:

SignalEffect
SIGINT / SIGTERMGraceful shutdown
SIGHUPRolling worker reload
SIGTTINScale workers up by one
SIGTTOUScale workers down by one

Parameters:

NameTypeDescriptionDefault
appApplication | ApplicationFactory

An ASGI 3 application callable, or its synchronous zero-argument constructor when factory=True.

required
configConfig | None

Server configuration. Defaults to Config() (one worker, bound to 127.0.0.1:8000).

None
factorybool

Treat app as a synchronous zero-argument application factory. Each effective request loop constructs and starts its own instance while that loop is running, on every worker generation. Without this flag the supplied app is shared across request loops.

False

Raises:

TypeDescription
ValueError

If TLS PEM material, native configuration, or the configured user/group is invalid.

OSError

If reading TLS files, creating the pidfile, or binding a listener socket fails.

NotImplementedError

If a configured option (such as workers > 1, unix: listeners, user/group, or loop='uvloop') is unsupported on this platform.

ModuleNotFoundError

If config.loop == 'uvloop' without uvloop installed.

RuntimeError

If workers fail to start or exit repeatedly during supervision, or if lifespan startup/shutdown fails in-process.

Examples:

examples/embedded.py shows the Server alternative: one worker inside an event loop you already own, rather than the supervisor this starts.

Server

Server(
    app: Application,
    config: Config | None = None,
    *,
    factory: Literal[False] = False,
)
Server(
    app: ApplicationFactory,
    config: Config | None = None,
    *,
    factory: Literal[True],
)
Server(
    app: Application | ApplicationFactory,
    config: Config | None = None,
    *,
    factory: bool,
)
Server(
    app: Application | ApplicationFactory,
    config: Config | None = None,
    *,
    factory: bool = False,
)

In-process, single-worker ASGI server.

Use this when you want to embed h2corn inside an existing event loop — for example, inside a test harness, a custom CLI, or an application that manages its own process model. For ordinary deployments, prefer serve, which goes through the multi-worker supervisor and matches the h2corn CLI.

The configured bind listeners are opened, lifespan startup runs, then the server processes requests until shutdown() is called or the surrounding task is cancelled.

workers must be 1. Supervisor-only options (max_requests, max_requests_jitter, and timeout_worker_healthcheck) are ignored with a warning.

With factory=True, app is a synchronous zero-argument constructor. Each effective request-serving loop calls it while running, once per serve generation, then starts that instance's ASGI lifespan on the same loop. Acquire asynchronous resources in lifespan and use lifespan="on" when startup acknowledgement is required. Factory errors always fail startup. Without the flag the supplied app is shared across request loops, so it must support their concurrent use.

Raises:

TypeDescription
TypeError

If config is not None and not a Config instance when validated on serve().

Examples:

examples/embedded.py runs one worker on an ephemeral port, sends a request through it, and shuts it down.

addressesproperty

addresses: tuple[str, ...]

Resolved listener addresses, in Config.bind string form.

Empty until serve() has bound the listeners. Unlike Config.bind, these carry the port the kernel actually assigned — bind to port 0 and read the address back from here:

Partial example:

server = Server(app, Config(bind=('127.0.0.1:0',)))
serving = asyncio.create_task(server.serve())
await server.wait_started()
print(server.addresses)

is_drainingproperty

is_draining: bool

Whether a previous serve() is still draining and releasing application resources.

A startup failure or an expired graceful budget can settle serve() while cancellation cleanup still owns the application and its loops. The same Server cannot serve() again until this becomes false. Lifespan shutdown follows actual request settlement, and private loop cleanup finishes before the generation releases.

serveasync

serve() -> None

Run the server until shutdown.

Binds the configured listeners, runs ASGI lifespan startup, processes requests, then runs lifespan shutdown after the native drain has fully released the application.

One lifecycle at a time, reusable afterwards: once a serve() call has fully finished, the same Server can serve() again with fresh shutdown state, while a second concurrent call raises RuntimeError. Cancelling the serve() task does not abort in-flight work — it triggers the same bounded graceful drain as shutdown() and re-raises the cancellation once that drain finishes or its budget runs out.

Cooperative asynchronous requests cannot hold the caller waiting past the drain budget. An application that catches CancelledError and never finishes may still retain the server after serve() raises RuntimeError; lifespan shutdown runs after those requests release, and the same Server cannot serve() again until then. A synchronous Python call that blocks the event-loop thread cannot be preempted in-process; use supervised workers when a hard kill bound is required.

The original serving or startup error remains the public failure if rollback also fails. A later cleanup failure is reported through the owning event loop's exception handler.

Raises:

TypeDescription
NotImplementedError

If Config.workers is not 1, or an enabled option (such as unix: listeners or user/group) is unsupported on this platform.

ValueError

If Config.pidfile is combined with user/group, TLS PEM material or native configuration is invalid, or a user or group cannot be resolved.

OSError

If reading TLS files, creating the pidfile, or binding a listener socket fails.

RuntimeError

If this Server already has an active or draining serve() call, lifespan startup/shutdown fails or times out, or requests outlive the graceful shutdown budget.

shutdown

shutdown() -> None

Initiate a graceful shutdown of an in-flight serve() call.

Safe to call from any thread or coroutine. Native acceptance stops immediately and cooperative tasks receive up to Config.timeout_graceful_shutdown seconds to finish. Arbitrary synchronous Python code cannot be preempted in-process; use supervised workers when a hard kill bound is required.

wait_startedasync

wait_started() -> None

Wait until this server is accepting connections.

Resolves once listeners are bound, lifespan startup has completed, and the server is accepting connections.

If startup fails, raises the startup error. Raises RuntimeError if the server is already shutting down.

A failure is delivered to callers waiting for that startup. A later call waits for the next serve generation rather than repeating a previous generation's error.

Raises:

TypeDescription
RuntimeError

If the server is already shutting down, or if lifespan startup fails.

BaseException

Any startup error raised while binding listeners, preparing TLS, or running lifespan startup.

Partial example:

serving = asyncio.create_task(server.serve())
await server.wait_started()

SendAfterCloseError

Bases: builtins.OSError

Raised when an application sends on a stream the server has already closed.