patx/mrhttp-asgi

An experimental ASGI server in C (fork of mrhttp)

$ git clone https://gitman.io/git/patx/mrhttp-asgi

MrHTTP-ASGI

An HTTP/1.0, HTTP/1.1, and WebSocket ASGI server with a C HTTP transport and asyncio application handling. Requires Python 3.10+ on Unix x86_64 with AVX2 and BMI2. WebSocket framing uses wsproto. The legacy MrHTTP router and cache clients remain available separately.

Install and run

python -m pip install .
mrhttp myapp:app --host 127.0.0.1 --port 8080 --workers 4 --lifespan on
# myapp.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def index():
    return {"hello": "world"}

For programmatic process management, use an import string:

import mrhttp

if __name__ == "__main__":
    mrhttp.run("myapp:app", workers=4, lifespan="on")

--factory treats the imported attribute as a no-argument application factory. Import-string workers use fresh Python interpreters. Direct Python callables, including local functions, are also supported through Unix fork; restarting those workers refreshes their processes but does not re-import changed application code. Importing MrHTTP does not change the process-wide event-loop policy. Managed workers use uvloop; embedded servers use their caller's running loop.

Streaming and flow control

The C parser dispatches an application as soon as request headers are complete. receive() delivers decoded body chunks with more_body=True until the final chunk. Applications must consume messages until more_body=False; one call to receive() is not guaranteed to return the complete upload.

Incoming data pauses at the configured buffer watermark and resumes as the app consumes messages. Expect: 100-continue is acknowledged when the application calls receive(). An application can reject a request before reading its body; the response is sent and the connection closes without consuming the upload.

Response chunks flush directly to the transport. send() waits for socket write backpressure. HTTP pipelined responses remain in request order. Duplicate request headers are preserved and lifespan state is shallow-copied per request.

mrhttp.run(
    "myapp:app",
    max_body_size=16 * 1024 * 1024,   # cumulative decoded bytes per request
    max_header_size=65536,          # request head; also at most 100 fields
    read_buffer_size=65536,         # queued body bytes plus waiting request heads
    max_pipeline_requests=1024,
    max_connections=1000,           # per worker
    timeout_request=30,             # incomplete request deadline
    timeout_keep_alive=5,
    timeout_graceful_shutdown=10,
)

A native body chunk is at most 16 KiB; the Python watermark can overshoot by one chunk or request head. The native staging buffer is capped at the header limit plus 1 MiB. The body limit applies cumulatively to fixed-length and chunked uploads, without retaining the full body. Invalid framing and oversized requests return HTTP 400 and close when an error response is still possible. Once a response has started, a protocol failure closes the connection instead of appending another HTTP response. Active streaming responses have no arbitrary duration limit.

Worker supervision and shutdown

The supervisor replaces crashed workers and kills/replaces workers whose event loops stop sending heartbeats. Startup readiness follows lifespan startup and listener creation. Startup failure exits nonzero; repeated failures stop the supervisor instead of creating an unlimited restart loop.

mrhttp myapp:app --workers 4 \
  --timeout-worker-healthcheck 5 --timeout-worker-startup 30 \
  --limit-max-requests 10000 --limit-max-requests-jitter 1000

The request limit requests a rolling replacement; it is a soft recycling target, so a worker may finish additional requests while its replacement starts. Jitter staggers recycling. It is disabled by default.

Send SIGHUP to the supervisor PID to restart workers one at a time. A replacement must become ready before the old worker stops accepting connections and drains in-flight work. Import-string workers load fresh application code. SIGINT/SIGTERM stop acceptance, drain requests for the configured grace period, cancel remaining applications, and then run lifespan shutdown. WebSockets receive a 1001 close on server shutdown. Processes that exceed their shutdown deadline are killed.

lifespan=auto permits apps without lifespan support; on makes startup failures fatal; off disables lifespan events.

Logs, request IDs, health, and metrics

mrhttp myapp:app --workers 4 \
  --access-log --access-log-format json \
  --health-check-path /healthz --metrics-path /metrics

Access logs contain request ID, method, decoded path, client, status, response-body bytes, and duration. Query strings are not logged. A valid incoming X-Request-Id is reused; otherwise the server generates one. The ID is available as scope['request_id'] and is added to responses. --request-id-header changes the header name. Application errors include the request ID.

Health and metrics routes are opt-in and handled before the application. Health returns 200 after worker startup. /metrics exposes Prometheus text counters for requests, decoded input bytes, response bytes, protocol errors, a duration histogram, and connection/active-request gauges. Managed workers share counters; scrapes aggregate all worker slots and are approximate concurrent snapshots. Worker death resets its gauges without discarding counters. No request-path or request-ID labels are used. Restrict the metrics path through deployment routing if it should not be public.

WebSockets

ASGI applications receive websocket.connect, complete text/binary messages, and websocket.disconnect with close code/reason. Subprotocol negotiation, fragmented messages, ping/pong, close handshakes, and transport backpressure are supported. Closing before acceptance returns HTTP 403; invalid handshakes return HTTP 400.

mrhttp myapp:app --ws-max-size 16777216 --ws-max-queue 32 \
  --ws-ping-interval 20 --ws-ping-timeout 20 --ws-close-timeout 5

The message-size limit applies across fragments. The receive queue pauses input at its watermark. Set --ws-ping-interval 0 to disable server pings. Compression extensions are not negotiated. An upgrade cannot follow an active pipelined HTTP request on the same connection.

Proxies and deployment sockets

Forwarded headers are ignored by default. Enable them only for configured trusted immediate peers; the client address is selected from the right of the forwarded chain, skipping trusted proxy hops:

mrhttp myapp:app --proxy-headers --forwarded-allow-ips '127.0.0.1,::1,10.0.0.0/8'
mrhttp myapp:app --host ::1 --port 8080
mrhttp myapp:app --uds /run/myapp.sock --workers 4
mrhttp myapp:app --fd 3 --workers 4

X-Forwarded-For and X-Forwarded-Proto update ASGI client and scheme metadata; Forwarded and X-Forwarded-Host are not interpreted. * explicitly trusts every peer. IPv6 listeners are IPv6-only. Unix paths must not already exist, and paths created by the server are removed on shutdown only if their inode still matches. Inherited descriptors are duplicated; the caller retains ownership of its FD. --backlog sets the listen backlog. --root-path supports mounted applications. All limits and timeout settings above are also available as CLI flags; use mrhttp --help for the complete configuration.

For an existing event loop, use await server.start_server(host=..., port=...) (or uds=... / fd=...) and await server.shutdown() on an ASGIServer instance.

Validation and remaining scope

python -m pip install '.[test]'
./runtests

CI runs the HTTP, WebSocket, FastAPI, proxy, socket-binding, observability, and supervisor suites on Python 3.10–3.14 and under AddressSanitizer/UndefinedBehaviorSanitizer. The launcher propagates failures; benchmarks are separate (./runtests --benchmarks).

HTTP/2, HTTP/3, direct TLS, WSGI, response trailers, WebSocket compression, and file-watching development reload are not implemented. Use a reverse proxy for TLS. The legacy router, multipart parser, serializers, and external cache/session backends are outside this ASGI validation scope; their tests need extra packages and services. Load and soak validation for a deployment's workload remains necessary. Historical benchmark results do not describe this implementation.