Skip to content

Operations

The CLI and serve() run a supervised worker pool on POSIX. On Windows, they run one worker in the current process. To run a server inside an existing event loop, use Server; see Embedding.

Examples use hello:app from the quickstart. The configuration reference lists all settings.

Configure the server

TOML config files

For anything more than a handful of flags, use a TOML file:

h2corn.toml
bind = ["127.0.0.1:8000"]
workers = 4

proxy_headers = true
trusted_peers = ["127.0.0.1", "::1", "unix"]
forwarded_fields = ["for", "proto"]

# Rolling worker recycling: each worker retires after handling
# 50_000–55_000 requests, so retirements stagger naturally.
max_requests = 50000
max_requests_jitter = 5000

# Restart workers if they stop sending health-check heartbeats.
timeout_worker_healthcheck = 30.0
h2corn hello:app --config h2corn.toml
# or
H2CORN_CONFIG=h2corn.toml h2corn hello:app

CLI flags override TOML values.

Worker pool

h2corn hello:app --workers 4

Workers share the listeners opened by the supervisor and accept connections directly.

Event loop

--loop selects the Python event-loop implementation:

h2corn hello:app --loop auto      # default
ValueBehavior
autoUse uvloop if it is installed, otherwise the stdlib asyncio loop.
asyncioAlways the standard-library asyncio loop.
uvloopAlways uvloop; errors at startup if it is not installed.

uvloop is an optional dependency; see Installation. Unlike a pure-Python server, h2corn runs its accept loop, framing, and socket I/O in Rust; the Python loop schedules the application's callbacks. Choose between asyncio and uvloop from measurements of the real application.

Free-threaded Python

On a free-threaded (no-GIL) CPython build, one worker can run the application on several event loops in parallel:

h2corn hello:app --loop-threads 4

See Python compatibility and wheels for supported free-threaded CPython versions and wheel families. Importing h2corn does not silently re-enable the GIL.

Requests are balanced across the loops round-robin, and each request runs entirely on one loop. Each loop runs a separate ASGI lifespan cycle and receives its own lifespan state dictionary. Applications using loop-bound resources should use an application factory for a separate application instance on each loop, and acquire asynchronous resources during lifespan startup. Without --factory (or factory=True in Python), the application object itself is shared across loops. Startup and shutdown side effects therefore run once per loop and must be safe to repeat.

On a regular (GIL) build loop_threads above 1 is a no-op — the GIL would serialize the loops anyway, so a single loop is used. Combine with --runtime-threads to scale the I/O side accordingly. Secondary loops require the built-in asyncio or uvloop factory; h2corn rejects multiple loop threads when embedded in an unknown custom loop rather than silently changing topology.

--loop-threads composes with --workers: each forked worker runs its own set of loop threads, so -w 4 --loop-threads 4 is 16 event loops. Loop threads share the process heap but require the application and its dependencies to support concurrent execution on free-threaded Python. Workers provide stronger isolation and independent application state. Choose the mix from application behavior and measured throughput, latency, and memory.

Reload and scale

Signals

The supervisor responds to these signals:

SignalEffect
SIGINT / SIGTERMGraceful shutdown. Workers stop accepting new work, drain in-flight requests, run lifespan shutdown, and then exit.
SIGHUPRolling application reload. The supervisor starts one replacement worker, waits for its lifespan and listener readiness, then retires the old worker.
SIGTTINScale up by one worker.
SIGTTOUScale down by one worker, but never below one target worker.

Live scaling changes the pool size without restarting:

# Add two workers
kill -SIGTTIN $(cat /var/run/h2corn.pid)
kill -SIGTTIN $(cat /var/run/h2corn.pid)

# Drop one worker
kill -SIGTTOU $(cat /var/run/h2corn.pid)

Use --pidfile /var/run/h2corn.pid so deployment tooling can find the supervisor reliably.

What SIGHUP reloads

SIGHUP re-imports the CLI target in each replacement worker. The supervisor keeps the listener file descriptors and resolved configuration while it rolls workers.

sequenceDiagram
  accTitle: h2corn rolling SIGHUP reload
  accDescr: SIGHUP queues every worker. The supervisor spawns a replacement, which runs lifespan startup and adopts the inherited listeners before reporting ready. Both workers then serve at once. Only after that does the supervisor retire the predecessor, which drains in-flight requests and runs lifespan shutdown, leaving the replacement serving. Serving capacity never drops to zero.
  participant S as supervisor
  participant A as worker (old)
  participant B as worker (replacement)

  activate A
  S->>S: SIGHUP queues every worker
  S->>B: spawn replacement
  B->>B: lifespan startup,<br>adopt inherited listeners
  B-->>S: READY
  activate B
  Note over A,B: both serving<br>capacity never drops
  S->>A: retire
  A->>A: drain in-flight,<br>lifespan shutdown
  A--)S: exited
  deactivate A
  Note over S,B: repeat for the next queued worker
  deactivate B
The replacement starts serving before its predecessor drains, keeping capacity available during the handover.
State or inputSIGHUP behaviorApply a change with
Python module and application stateRe-imported in each replacement workerkill -HUP <supervisor-pid>
TOML configuration (--config)Not re-readValidate, then restart the supervisor
H2CORN_* environment variablesNot re-readRestart with the new environment
--env-file application environmentNot re-read; the supervisor loads it once before forkingRestart with the replacement file
bind addresses, worker count, resource limitsNot re-readRestart, or use the documented scale signals for worker count only
TLS certificate, key, CA bundle, and ALPN choiceNot re-read; the acceptor is prepared onceReplace files atomically, then restart

For direct-TLS certificate rotation, see Direct TLS.

Shared ports across processes

h2corn hello:app --reuse-port

--reuse-port sets SO_REUSEPORT on the TCP listeners so another server process can bind the same port: start a new generation during a zero-downtime deploy and stop the old one, or run several independently managed processes behind one port. Workers of a single server always share its listener, so the kernel's shared accept queue lets any idle worker pick up a connection. TCP listeners only.

Worker recycling

Retire workers after a request budget to stagger memory growth and other long-tail process state:

h2corn hello:app \
  --workers 4 \
  --max-requests 50000 \
  --max-requests-jitter 5000

The supervisor adds up to --max-requests-jitter extra requests to each worker's budget, so retirements are spread out over time rather than firing at the same instant on every worker.

Health and shutdown

Resource limits and slow clients

The server separately limits connection count, concurrent ASGI tasks, HTTP/2 streams, request bodies and headers, request-body idle time, handshakes, keep-alive, response stalls, and WebSocket messages. Defaults, units, None (none on the CLI) disable semantics, and failure behavior are in the HTTP and resource limit options and Config. Slow clients consume connection and stream capacity until the relevant timeout; limit_connections and limit_concurrency bound a worker's admission, and a proxy request/body timeout must cover the application path it protects.

Health checks

Each worker emits a periodic heartbeat to the supervisor. If the supervisor does not see a heartbeat within --timeout-worker-healthcheck seconds, the worker is replaced. This protects against a worker getting wedged in a busy loop or a blocking syscall that never returns to the event loop.

Set --timeout-worker-healthcheck none (or timeout_worker_healthcheck=None in Python) to disable.

Crash backoff

Crashed workers are restarted with exponential backoff. A sustained crash loop stops the supervisor and reports the deployment failure, including when a previously healthy deployment loses all serving workers.

Shutdown budget

Shutdown has two request phases and one lifespan phase. Native request draining uses timeout_graceful_shutdown; cancellation-resistant request cleanup can use it again; lifespan shutdown starts after requests release. The supervisor's stop budget is:

2 * timeout_graceful_shutdown
+ timeout_lifespan_shutdown
+ margin for signal delivery and process reaping

With the defaults (30s and 30s), the formula is 90s plus signal and reaping margin; a 100s service-manager stop budget leaves a 10-second margin.

gantt
  accTitle: h2corn shutdown budget at the default timeouts
  accDescr: Request draining, cancellation-resistant cleanup, and lifespan shutdown each run for up to thirty seconds in sequence, totalling ninety seconds. Ten seconds of signal delivery and reaping margin bring the worker total to one hundred seconds, which is what the service manager stop budget must cover before it sends SIGKILL.
  dateFormat X
  axisFormat %M:%S
  todayMarker off
  section worker
    request drain — timeout_graceful_shutdown        :a1, 0, 30
    cancellation cleanup — timeout_graceful_shutdown :a2, 30, 60
    lifespan shutdown — timeout_lifespan_shutdown    :a3, 60, 90
  section supervisor
    signal delivery + reaping margin                 :a4, 90, 100
  section service manager
    TimeoutStopSec=100s, then SIGKILL                :crit, b1, 0, 100
Phases run in sequence, each bounded by its own timeout, so the service manager's stop budget has to cover all three plus margin. Setting it below the worker total truncates whichever phase is still running.

A worker that ignores cancellation can make an embedded call report a shutdown error while the generation still owns the listener. The supervisor kills a retiring worker at its phase deadline and logs the action. A shorter service-manager timeout can send SIGKILL before request or lifespan cleanup completes.

Deployment environments

Containers and Kubernetes

The container entrypoint must exec h2corn so it receives termination and owns its worker children:

configuration template
ENTRYPOINT ["/srv/app/.venv/bin/h2corn", "myapp.asgi:application", "--config", "/etc/myapp/h2corn.toml"]

If a wrapper is used, it must finish with exec. READY=1 is a systemd contract; Kubernetes does not consume it. Readiness therefore comes from an application route or ingress using the listener's protocol. Kubernetes HTTP probes use HTTP/1.1, so a listener started with --no-http1 needs a TCP probe, an HTTP/1.1-capable proxy endpoint, or a separate probe listener.

h2corn's internal readiness and worker heartbeats (timeout_worker_healthcheck) are not exposed as Kubernetes routes; add an application route (for example /healthz) for probes.

Kubernetes sends SIGTERM, removes a ready pod from endpoints asynchronously, then waits terminationGracePeriodSeconds before SIGKILL. The period must cover the combined shutdown formula and any preStop hook time. The default 30s request and lifespan settings require at least 100 seconds for h2corn's stop budget. h2corn's signal handler stops acceptance; a fixed sleep in preStop consumes the period before request and lifespan cleanup.

systemd readiness

Under a Type=notify unit (when NOTIFY_SOCKET is set), h2corn sends READY=1 after every worker is accepting connections and STOPPING=1 before shutdown draining begins. These notifications do not extend systemd's startup or shutdown timeouts.

Full systemd unit

Run the supervisor as the service user. ExecStartPre checks the TOML and TLS inputs before startup, ExecReload forwards systemctl reload as the app-only SIGHUP, and TimeoutStopSec covers the whole shutdown budget. The service user must be able to read the configured certificate and key. For a root-only key, run h2corn as a root-owned supervisor and use its --user/--group drop instead.

myapp.service (configuration template)
[Unit]
Description=myapp ASGI service
Wants=network-online.target
After=network-online.target

[Service]
Type=notify
NotifyAccess=main
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp
EnvironmentFile=/etc/myapp/h2corn.env
ExecStartPre=/srv/myapp/.venv/bin/h2corn --check-config --config /etc/myapp/h2corn.toml
ExecStart=/srv/myapp/.venv/bin/h2corn myapp.asgi:application --config /etc/myapp/h2corn.toml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2s
KillSignal=SIGTERM
TimeoutStartSec=75s
TimeoutStopSec=100s
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp

[Install]
WantedBy=multi-user.target

ExecReload reloads application code only; see What SIGHUP reloads.

Process identity

Drop privileges after binding to a low port:

sudo h2corn hello:app \
  --bind 0.0.0.0:443 \
  --certfile /etc/ssl/example/fullchain.pem \
  --keyfile /etc/ssl/example/privkey.pem \
  --user www-data \
  --group www-data

The supervisor binds the listeners as root, then resolves --user/--group and switches identity in the workers before the ASGI app is imported. Unix sockets created by the supervisor inherit the same ownership, with permissions controlled by --unix-permissions.

Everything that needs root is acquired before that switch. The private key may stay root:root mode 0600; the supervisor reads it once at startup and every worker inherits the material. A key the starting user cannot read fails startup immediately, naming the setting and the path, before any handshake.

Logs and metrics

h2corn emits logs. Metrics and tracing are application integrations.

Structured logs

--log-format json encodes h2corn logs on stderr — the startup banner, worker lifecycle, errors and access records — as one JSON object per line for log shipping.

illustrative output (values vary)
{"level":"info","event":"listening","pid":1200,"url":"http://127.0.0.1:8000"}
{"level":"info","event":"worker_started","pid":1200,"worker_pid":1234}
{"level":"info","event":"request","pid":1234,"client":"203.0.113.7:54321","method":"GET","target":"/items?q=1","protocol":"HTTP/2","status":200,"duration_ms":0.420,"rx_bytes":0,"tx_bytes":218}

Numeric fields remain numbers. Timestamps come from the log collector (journald, Docker, or Kubernetes), rather than from the record.

Reading records

Every record has level, event, and pid, identifying the emitting process. Worker lifecycle records also carry worker_pid for the affected worker. Lifecycle and access records use info; server and application failures use error. An HTTP error status remains an access record, not an extra error event. Ordinary client disconnects and malformed traffic do not generate error logs.

RecordUseful fields and meaning
starting, listeningServer version and bound url, respectively.
worker_started, worker_stoppedThe worker process was spawned or reaped. These are not application-readiness notifications.
requestclient, method, target, protocol, status, duration_ms, rx_bytes, tx_bytes.
websocket_closedThe same connection and payload fields, with close_code instead of HTTP status.
failedsubject identifies the failed operation; detail describes the error.
worker_failed, cli_errordetail contains the uncaught failure, including its Python traceback, exception chain, and notes.

For HTTP, status is the response status and duration_ms covers request handling after the request head has been read. Byte counts cover body payload, not headers or transport framing; tx_bytes counts response bytes accepted for output, not bytes acknowledged by the client. A partial response can retain its original status. For WebSockets, the handshake has an HTTP record, followed at session end by websocket_closed, with close_code, session duration, and payload counts. method retains the handshake's GET or CONNECT.

target includes the query string. Request headers and bodies are not recorded. Use Server.wait_started() or systemd readiness to observe readiness; a bound listener alone does not establish it.

Within a major release, event names and existing field types, meanings, and units remain stable. New events and fields may be added; consumers should ignore fields and events they do not use. An incompatible log change follows the upgrade policy.

--access-log and --log-format are independent — --no-access-log--log-format json keeps the diagnostics machine-readable while dropping the per-request records.

Application logging

The CLI and programmatic serve() use the same log configuration. Embedded Server instances retain their own formats, including diagnostics. Choose the same format for instances sharing stderr when a collector expects a uniform stream.

h2corn does not replace Python logging handlers, warning handlers, or exception hooks. Configure application and framework logging separately, using Python logging or a structured logger such as structlog. Embedded startup and shutdown exceptions propagate to the caller. Python runtime diagnostics, including sys.unraisablehook, remain under the host application's control.

Metrics and tracing

Use ASGI middleware for metrics, tracing, correlation IDs, and health routes:

NeedLibrary
Prometheus /metricsprometheus-fastapi-instrumentator (FastAPI) or starlette-prometheus (any Starlette/ASGI app)
OpenTelemetry tracesopentelemetry-instrumentation-asgi
Request correlation IDsasgi-correlation-id, which threads an ID through your application's own logging
Liveness / readinessA plain ASGI route — e.g. FastAPI @app.get('/healthz') — exposed to the orchestrator

For FastAPI, install prometheus-fastapi-instrumentator and instrument the application:

app.py
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator

app = FastAPI()
Instrumentator().instrument(app).expose(app)
h2corn app:app --workers 4
# Prometheus can scrape /metrics on this listener