#3149·uvicorn

--workers N loses TCP_NODELAY: every keep-alive request past the first costs ~43ms on Linux

Author: H00N24Created Sep 20, 2026Updated Sep 20, 2026

Summary

Config.bind_socket() creates the listening socket with proto left at 0. Accepted sockets inherit proto from the listener, and asyncio only enables TCP_NODELAY when the accepted socket reports proto == IPPROTO_TCP. So every code path that passes a pre-bound socket to the server leaves Nagle's algorithm on, and each keep-alive request after the first waits on the peer's delayed ACK.

That is --workers N (the multiprocess supervisor binds the socket and passes it down) and the gunicorn worker. The single-process --workers 1 path is unaffected, because uvicorn hands asyncio a host and a port there and asyncio builds the listener from getaddrinfo, which sets proto to 6.

Linux only. On macOS getaddrinfo also returns proto == 0, so both paths are equally affected and the difference does not show.

Reproduction

python
import asyncio
import http.client
import socket
import threading
import time

import uvicorn

BODY = b'{"ok":true}'
PORT = 8123


class Report(asyncio.Protocol):
    result = None

    def connection_made(self, transport):
        sock = transport.get_extra_info("socket")
        Report.result = (sock.proto, sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY))
        transport.close()


async def accepted_socket(use_bound_socket):
    loop = asyncio.get_running_loop()
    if use_bound_socket:
        sock = uvicorn.Config(app, host="127.0.0.1", port=PORT).bind_socket()
        server = await loop.create_server(Report, sock=sock)
    else:
        server = await loop.create_server(Report, "127.0.0.1", PORT)
    client = socket.create_connection(("127.0.0.1", PORT))
    while Report.result is None:
        await asyncio.sleep(0.01)
    client.close()
    server.close()
    await server.wait_closed()
    result, Report.result = Report.result, None
    return result


async def app(scope, receive, send):
    if scope["type"] != "http":
        return
    await send({"type": "http.response.start", "status": 200, "headers": [
        (b"content-type", b"application/json"),
        (b"content-length", str(len(BODY)).encode()),
    ]})
    await send({"type": "http.response.body", "body": BODY})


def keepalive_times(use_bound_socket):
    config = uvicorn.Config(app, host="127.0.0.1", port=PORT, log_level="error")
    server = uvicorn.Server(config)
    sock = config.bind_socket() if use_bound_socket else None
    thread = threading.Thread(target=lambda: asyncio.run(server.serve(sockets=[sock] if sock else None)))
    thread.start()
    while not server.started:
        time.sleep(0.02)
    conn = http.client.HTTPConnection("127.0.0.1", PORT)
    timings = []
    for _ in range(4):
        start = time.perf_counter()
        conn.request("GET", "/")
        conn.getresponse().read()
        timings.append(time.perf_counter() - start)
    conn.close()
    server.should_exit = True
    thread.join()
    if sock is not None:
        sock.close()
    return timings


if __name__ == "__main__":
    print(f"uvicorn {uvicorn.__version__}")
    for label, bound in (("host/port    ", False), ("bind_socket()", True)):
        proto, nodelay = asyncio.run(accepted_socket(bound))
        times = "  ".join(f"{t * 1000:6.2f}ms" for t in keepalive_times(bound))
        print(f"{label}  accepted proto={proto} TCP_NODELAY={nodelay}  keep-alive: {times}")

Output, uvicorn 0.53.0, CPython 3.14, Debian bookworm container, linux/arm64:

uvicorn 0.53.0
host/port      accepted proto=6 TCP_NODELAY=1  keep-alive:   0.95ms    0.33ms    0.22ms    0.19ms
bind_socket()  accepted proto=0 TCP_NODELAY=0  keep-alive:   0.78ms   44.55ms   42.21ms   43.36ms

Cause

uvicorn/config.py, in bind_socket():

python
sock = socket.socket(family=family)

socket.socket defaults proto to 0. CPython's asyncio.base_events._set_nodelay, which runs on each accepted socket, is guarded on it:

python
def _set_nodelay(sock):
    if (sock.family in {socket.AF_INET, socket.AF_INET6} and
            sock.type == socket.SOCK_STREAM and
            sock.proto == socket.IPPROTO_TCP):
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

The listener reports proto == 0, the accepted socket inherits it, the guard fails, and TCP_NODELAY is never set. The response goes out in two segments (headers, then body), and the second one waits for the client's delayed ACK.

Impact

Benchmarked with oha against a small ASGI application behind a Postgres query, both processes in one Linux network namespace, four workers against one:

concurrency 5 concurrency 32
--workers 1 1723 rps, p50 2.80ms 1576 rps, p50 19.7ms
--workers 4 113 rps, p50 44.1ms 469 rps, p50 44.2ms

Four workers serve 15 times fewer requests than one. The p50 pinned at 44ms in both columns is the signature: a fixed per-request stall rather than contention.

This is easy to miss when benchmarking on a Mac, because Docker Desktop's published-port forwarder terminates TCP on the host and coalesces the writes, which hides the stall completely.

Suggested fix

Pass the protocol explicitly:

python
sock = socket.socket(family=family, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)

Confirmed to restore sub-millisecond keep-alive responses on the bind_socket() path. The Unix domain socket branch above it is correctly unaffected, since TCP_NODELAY does not apply there.

Happy to open a pull request if the approach looks right.