asyncio Connect Stalls at 1 s, 3 s and 7 s: the Listen Backlog Is Full

Dark neon cover: a right-hand panel showing an accept queue with two completed connections inside it, red arrows stopping at its edge, and a rising staircase labelled queue, 1 s, 3 s and 7 s

TL;DR

  • A listening socket holds its reported backlog plus one connection: 16 clients fired at listen(1) produced 2 completed handshakes and 14 clients still waiting, while listen(4) produced 5.
  • A blocked loop behind a wide queue refuses nobody. 32 clients connected in 0.06 ms median and then waited 1,004 ms for the reply, because the kernel finished all 32 handshakes while the loop slept.
  • Behind a queue of two, the same block costs seconds after it ends: the slowest served client of the three trials finished 11,693 ms after its own first SYN, and 9 clients were still waiting for a reply when the 10 s reply deadline expired – none of them timed out in the handshake, so the connection existed and the answer did not.
  • Those completion times are the client’s retransmission timer, measured: 1,004 ms after a 500 ms block, 3,052 ms after 2,500 ms and 7,116 ms after 5,500 ms. The block decides whether a client waits; the timer decides how long.
  • Moving the same 50 ms onto a pool takes 32 requests from 870 ms median to 254.1 ms, and the worst loop wake-up from 1,606 ms to 1.9 ms – but the same pool moves 29.7 replies a second of pure arithmetic against 29.6 in the loop, because four threads do not compute more than one.

1. The host, the two clocks, and what the kernel grants

A client that says “your server is slow” reports two numbers it cannot tell apart: how long the connection took to open, and how long the answer took after it opened. They have different owners. The connection is completed by the kernel, in a queue that fills and empties whether or not Python is running; the answer is produced by the event loop, and it is late exactly when the loop is not running. Every measurement below separates the two on one host, with real sockets, one Python process, and no instrumentation inside the library: up to thirty-two clients at once, a scripted server in all of them, and a stopwatch on each side of the connection.

ItemMeasured valueHow it was read
Kernel6.12.8+ on x86_64platform.release()
CPUIntel(R) Xeon(R) Platinum 8488C, 2 vCPUs/proc/cpuinfo
Python3.12.16, CPythonplatform.python_version()
Open files per process1,024RLIMIT_NOFILE soft limit
perf_counter step111 nssmallest non-zero delta in a 200,000-call spin
TCP connect34 µs median, 0.06 ms p95100 connects to a listener that accepts at once
Request round trip49 µs median, 0.06 ms p95200 requests on one established connection
Socket pair echo, one thread2.5 µs100-byte echo, both ends on the calling thread
Socket pair echo, two threads37.8 µssame echo, the far end served by a thread that must be woken
One pool handoff45.6 µs median, 71.4 p95200 empty submit().result() calls
Loop wake-up on an idle loop0.12 ms median, 0.17 ms p95a task asking to wake every 2 ms, 200 samples
Table 1: The host and the five clocks the rest of the page leans on. A connect here is a fraction of a millisecond, so a connect that returns a thousand times slower cannot be the handshake: it is a retransmission. A loop wake-up here is 0.17 ms, so a request answered a second late is not scheduler noise.

The last three rows are the ones that make the article measurable. An echo on a socket pair with both ends on one thread costs 2.5 µs – two system calls and a copy – while the same echo with the far end on another thread costs 37.8 µs, because that thread has to be woken. That gap is the floor under every offloaded handler: moving work to a thread is not free, it is one wake-up, measured at 45.6 µs for an empty call through ThreadPoolExecutor. It is a rounding error against a handler that spends 50 ms, and it is the entire cost of a handler that does nothing – which is why pooling only ever pays for work that blocks.

The kernel grants a number no application controls. listen(n) is a request; the ceiling is /proc/sys/net/core/somaxconn. Asking for 5,000 and reading back the queue the kernel actually enforces returns 4,096 – a silent cap, with no error and no warning, that is invisible to any code that trusts its own argument. The same read shows the limit the rest of the page uses: 128 reported for listen(128), and 0 for listen(0), which is a legitimate request for a queue of one. The probe reads that value from ss, the kernel’s own view, instead of from the argument it passed.

"""Probe 00: the host, the kernel's queue limits, and the three clocks."""
from __future__ import annotations
import subprocess
import common
def ss_listen(port: int) -> dict:
    """The kernel's own view of one listening socket: queue limit and queue length."""
    out = subprocess.run(["ss", "-lntH", f"sport = :{port}"], capture_output=True, text=True)
    line = out.stdout.strip().splitlines()
    if not line:
        return {}
    fields = line[0].split()
    return {"recv_q": int(fields[1]), "send_q": int(fields[2])}
def backlog_reported(requested: int) -> int:
    """What ``ss`` calls Send-Q after ``listen(requested)``.

    The kernel silently caps the backlog at ``somaxconn`` (and, on some kernels, adds one
    slot), so the number the application asked for is not the number it got.
    """
    with common.listen_socket(requested) as server:
        return int(ss_listen(server.getsockname()[1])["send_q"])
SettingValue on this hostWhat it decides
net.core.somaxconn4,096the ceiling on every backlog, applied silently
net.ipv4.tcp_max_syn_backlog128how many half-open handshakes the kernel will track
net.ipv4.tcp_abort_on_overflow00 keeps a completed handshake alive when the queue has no room: the client retries, and a SYN that meets a full queue is dropped either way
net.ipv4.tcp_syn_retries6the retransmission budget of the doubling phase only, counted after the linear phase below: a dropped SYN spends that phase first and its timeouts are added to this value (section 4)
net.ipv4.tcp_syn_linear_timeouts4keeps the SYN timer at a second instead of doubling it, for the first few retransmissions; table 7 is what that produces
net.ipv4.tcp_syncookies11 lets the kernel answer a SYN its half-open queue cannot hold; it adds no room to the accept queue
Kernel timer HZ250the tick the timer wheel is built from (CONFIG_HZ in /proc/config.gz), not the proc interface’s clock: 4 ms a tick, and the bucket a 32 s retransmission lands in is 2,048 ms (section 4)
listen(0) reported as0a queue of nothing: one handshake still completes
listen(4) reported as4four queued, five completions in total
listen(5000)4,096capped at somaxconn
Table 2: The kernel is the half of this failure that Python cannot see, and every value here decides what a client experiences. The two SYN rows are one budget read in two parts: the retry count is what turns a dropped SYN into a visible stall rather than an error, because with no reset sent the client has nothing to report until its own timer expires, and the linear phase is what decides how long that timer stays at a second. Section 4 spends the whole budget on one socket.

Out of scope: One host, one Python process, loopback, two vCPUs. Absolute milliseconds belong to this machine; the ratios and the shape of each distribution are what transfers. The client threads share a CPU budget with the server, so a burst of simultaneous client threads adds a harness floor of its own – 21.3 ms in the widest arm – that every blocked figure must be read against. The kernel setting tcp_abort_on_overflow is 0 here, so every failure on this page is a dropped packet and a client that waits; the variant where the kernel resets instead was not measured, and the test of that setting is not whether the connect fails but which packet met the full queue.

2. What the queue holds when nobody accepts

The first experiment does nothing: it binds a socket, listens with a chosen backlog, and never calls accept. Sixteen clients then connect at the same instant through a barrier, each with its own twelve-second timeout, and the queue is read from ss a quarter of a second later, while it is full. The result is the capacity of the queue with the loop completely absent – no Python, no handler, no scheduler – which is the number everything else is compared against.

listen(n)Reported limitIn the queueHandshakes completedClients still waitingCompleted in
0011150.10 ms
1122140.40 ms
4455110.30 ms
1616161600.10 ms
128128161600.10 ms
Table 3: 16 clients per row, no accept call anywhere, queue read from ss at the moment it is full. “Completed in” is the median of the handshakes that finished. A client counted under “Clients still waiting” is not a client that was refused: its SYN was dropped and it sat inside one connect call until its own timeout expired, which is the only trace it leaves on either side.

Two facts come out of the table, and both are needed later. The first is that the queue holds one more than it reports: listen(1) completes two handshakes, listen(4) completes five, and listen(0) – a request for a queue of nothing – completes one. Linux’s fullness test compares the queue’s length with its limit using > rather than >= (sk_acceptq_is_full in include/net/sock.h), so one connection is admitted past the limit the socket reports. That extra slot is a fact about the comparison, not about the burst, and nothing should be sized against it. The second is what happens to the rest. They do not fail. Their SYN is dropped, no reset is sent, and connect blocks: each of the clients that timed out spent 12,012 ms inside one call, which is the whole of its client-side timeout and not a property of the server at all.

That asymmetry is the reason this failure is so often misread. An application that measures its own handler sees nothing – no error, no exception, no slow request – because the request never arrived. The client sees a connect that hangs, and the kernel’s retry schedule decides when, or whether, it ever returns. The next two sections put a running loop in front of the queue: one that is wide enough to hide a block, and one that is not.

3. A block the queue absorbs: instant connects, late bytes

Now the loop enters. The server is a normal asyncio echo server with listen(128), and one coroutine calls time.sleep(1) at the moment thirty-two clients connect. Nothing else changes between the arms: the same server class, the same handler, the same clients through the same barrier. The only difference is whether that one second is spent on the loop or not spent at all – the second arm is the control, and it is what says how much of the first arm belongs to the block rather than to thirty-two threads sharing two vCPUs.

ArmConnect p50Connect p95Reply p50Reply p95Loop lag maxIn the queueAccepted
no block0.35 ms1.4 ms21.3 ms22.7 ms15.3 ms—32
blocked 1,000 ms0.06 ms0.72 ms1,004 ms1,005 ms996.4 ms3232
blocked again15 µs0.52 ms1,005 ms1,007 ms996.3 ms3232
Table 4: 32 clients, listen(128), 1,000 ms of time.sleep on the loop. Connect and reply are measured separately in each client. “In the queue” is the accept queue read from ss while the loop was stopped: every client was already completed by the kernel at that moment.

The blocked row is the signature of a loop problem, and it is unambiguous. All 32 handshakes completed in 0.06 ms – a fraction of a millisecond, either way, because the kernel does not need Python to answer a SYN. The replies arrived at 1,004 ms, which is the block and nothing else: the 21.3 ms of the control arm is what this harness costs when the server is doing nothing, and every one of the 32 connections was sitting in the accept queue at once when the loop was stopped. The loop’s own watchdog, which asked to be woken every 5 ms, recorded a worst wake-up of 996.4 ms – 99.6% of the block, and 5,760 times the jitter of the same loop when it is idle. Nothing on the client side says “queue”; everything says “the loop was not running”.

What happens when the loop comes back is the part that is easy to miss in production. The kernel had 32 completed connections waiting, and the first of them was accepted 1.4 ms after the block ended; the last was accepted 0.09 ms after the first, a median gap of 2 µs between consecutive accepts. The drain is a burst, not a queue that clears slowly: an accept loop that was behind by a second catches up in less than a millisecond, and then every handler it starts runs on the same loop that just woke up. A block of one second is one second of latency, not one second of lost capacity – and that is true only while the queue is deep enough to hold the arrivals.

QuantityValueRead from
Accepted after the block32handler entry timestamps
Accept span, first to last0.09 msdifference between the first and last accept
Median gap between accepts2 µsthe same timestamps, consecutive pairs
p95 gap3 µssame
First accept after recovery1.4 msblock end to handler entry
Reply, earliest to latest1,002 ms to 1,006 msclient stopwatch
Control arm reply21.3 ms medianthe same clients, no block
Table 5: The recovery, measured from the server side. The drain is fast enough that a client cannot tell the difference between a queue of 32 and a single connection once the loop is running again; what it can tell is the second it spent waiting, and the accept queue depth it never saw.

A note on the control arm, because it bounds every comparison here. 32 client threads starting together on two vCPUs cost 21.3 ms median even with the server doing nothing slow, which is the price of the harness rather than the server. The blocked arm is 47.2 times that, so the block is not a marginal effect that could be confused with scheduling noise, and the second blocked arm landed at 1,005 ms on the same figure.

4. The same block behind a narrow queue: at least two timers, one staircase

Section 3 works because the queue was deep enough. This one shrinks the queue and lengthens the block: listen(1) holds two connections, the block is 2,000 ms, and the burst is 16 clients. Most of those clients therefore arrive at a queue that is already full, and what happens next is no longer the server’s decision: the attempt is dropped, and the client can only try again when its own retransmission timer fires. The two stages are given separate deadlines – 40 s for the handshake, 10 s for the reply – because a connection that never exists and a connection that never answers are different faults, and one number cannot report both.

"""Probe 04: the same block behind a queue that is too small.

``listen(1)`` holds two connections. Sixteen clients arrive during a two-second block, so
most SYNs find a full queue, and what comes back is a staircase rather than a delay: each
client can only finish when its own handshake completes, and a handshake that lost a packet
waits for a retransmission timer.

Two things make the staircase readable. The client measures its two stages in separate
``try`` blocks - the handshake (``connect``) and the reply (``recv``) - so a timeout names
the stage that timed out instead of collapsing both into one number. And each socket's own
``total_retrans`` (``getsockopt(TCP_INFO)``) is recorded once its handshake is done, beside
the kernel counters from ``/proc/net/netstat`` and a sampling of the listening port's queues
from ``/proc/net/tcp``: together they say whether the client was waiting for its SYN
retransmission or for the server to accept a connection that already existed.
"""
from __future__ import annotations
import socket
import time
import common
def ask_once(port: int, index: int) -> dict:
    """One client: the handshake, then the reply, each on its own deadline."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(CONNECT_TIMEOUT_S)
    started = time.perf_counter()
    record: dict = {"index": index, "start": started, "connect_end": None, "end": None}
    try:
        # Stage one. A timeout here is the client's retry budget running out, and it says
        # nothing about the reply.
        try:
            sock.connect(("127.0.0.1", port))
        except socket.timeout:
            record["outcome"] = "connect_timeout"
            record["connect_end"] = record["end"] = time.perf_counter()
            return record
        except (OSError, ConnectionError) as exc:
            record["outcome"] = "connect_" + type(exc).__name__
            record["connect_end"] = record["end"] = time.perf_counter()
            return record
        record["connect_end"] = time.perf_counter()
        record["tcp"] = common.tcp_info(sock)
        # Stage two. Once the connection exists, its deadline is a different question: a
        # connection that never answers is not a connection that never happened.
        sock.settimeout(REPLY_TIMEOUT_S)
        try:
            sock.sendall(b"ping\n")
            common.read_line(sock)
            record["outcome"] = "served"
        except socket.timeout:
            record["outcome"] = "reply_timeout"
        except (OSError, ConnectionError) as exc:
            record["outcome"] = "reply_" + type(exc).__name__
        finally:
            record["tcp_after"] = common.tcp_info(sock)
            record["end"] = time.perf_counter()
        return record
    finally:
        sock.close()
QueueServed, three trialsReplies that timed outFastest client, p50Slowest client, p50Median wait after the block
listen(1)16 / 13 / 1092,002 ms9,947 ms32.4 ms
listen(4)15 / 16 / 1612,001 ms2,239 ms33 ms
Table 6: 16 clients, a 2,000 ms block, three trials each, a 40 s handshake deadline and a 10 s reply deadline. “Replies that timed out” counts clients whose connection was established and whose reply never arrived: one deadline for both stages cannot name that state, and the stage a client timed out in is the whole diagnosis. The last column is a duration: each trial’s middle served client, measured from the moment the loop recovered.

Two clocks are visible in that table and they do not agree. Of the 39 clients that did get a reply, 6 had completed their handshake while the loop was still stopped and were answered within 3.1 ms of it waking up: there was nothing left for them to wait for but the accept loop. The other 33 had retransmitted their SYN, up to 2 times, and their connect returned tens of milliseconds after recovery rather than at it. Meanwhile 9 clients were still waiting for a reply when the 10 s deadline expired, with no connect timeout anywhere in the record: the connection existed, the answer did not.

The queue itself explains that split, because it was sampled from /proc/net/tcp every twenty milliseconds while the loop was stopped. The listening socket’s completed queue held 2 connections – exactly what listen(1) grants – and the kernel held 0 requests half-open, because with tcp_syncookies on it answers a SYN with a cookie instead of storing the request. So the kernel kept 42 cookie answers across the three trials and created no further child socket. A client that arrives in that state is not queued, not refused and not logged: it is dropped, and it waits.

That is what makes the rest of the numbers legible: a client that was dropped can only finish on its next retransmission, so its completion time is a property of the kernel’s timer rather than of the block. Probe 09 measures that timer directly. One socket is pointed at a listener whose queue never frees, and the kernel’s own view of that socket – its state, its retransmission count, and the timer field the proc file prints – is read every two milliseconds:

"""Probe 09: the retransmission ladder itself, measured at the socket.

The retry that releases a blocked ``connect`` is not a server number. It belongs to the
client's own TCP stack, which resends the SYN on a timer that starts at one second and
grows. This probe measures that timer twice:

  * ``trace_ladder`` watches one socket pointed at a queue that never frees, reading the
    kernel's own view (``/proc/net/tcp``: state, retransmission count, and the timer field it
    prints for the socket) every two milliseconds, for long enough that the socket runs
    out of retry budget: each retransmission is recorded with the state the socket was in,
    and the attempt's own ending - ``connect`` returning an error, or completing - is
    recorded with the time it took.
  * ``stall_arm`` holds one connection in the queue, then lets a burst arrive behind it, and
    records when each dropped client finally completes, for three block lengths - so the
    ladder steps the article names are shown as completion times, not derived from a
    formula.
"""
from __future__ import annotations
import os
import socket
import threading
import time
import common
def client_row(inode: int) -> tuple[str, int, int] | None:
    """State, retransmission count and the timer field for one client socket."""
    for line in open("/proc/net/tcp", encoding="utf-8").read().splitlines()[1:]:
        fields = line.split()
        if len(fields) > 9 and fields[9] == str(inode):
            timer = fields[5].split(":")[1]
            return fields[3], int(fields[6], 16), int(timer, 16)
    return None
def trace_ladder(seconds: float, limits: dict) -> dict:
    """One connect that never finds room: every retransmission, and how it ends."""
    server = common.listen_socket(0)
    port = server.getsockname()[1]
    filler = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    filler.settimeout(5)
    try:
        filler.connect(("127.0.0.1", port))       # the one slot this queue has
    except OSError:
        pass

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(seconds + 10)
    started: dict[str, float] = {}
    counters_before = common.netstat()

    def connect() -> None:
        started["at"] = time.perf_counter()
        try:
            sock.connect(("127.0.0.1", port))
            started["connected"] = time.perf_counter()
        except OSError as exc:
            started["failed"] = time.perf_counter()
            started["error"] = type(exc).__name__
            started["errno"] = exc.errno

    worker = threading.Thread(target=connect, daemon=True)
    worker.start()
    time.sleep(0.02)
    inode = os.fstat(sock.fileno()).st_ino
    origin = started.get("at", time.perf_counter())
    events: list[dict] = []
    last_retrans = -1
    deadline = origin + seconds
    while time.perf_counter() < deadline:
        row = client_row(inode)
        if row is not None:
            state, retrans, timer = row
            if retrans != last_retrans:
                events.append({
                    "retransmissions": retrans,
                    "at_ms": round((time.perf_counter() - origin) * 1000, 1),
                    "state": state,
                    "state_name": STATE_NAMES.get(state, state),
                    "next_timer_ms": round(timer * 10, 1),   # the field's unit: 10 ms (USER_HZ)
                })
                last_retrans = retrans
        elif not worker.is_alive():
            break
        time.sleep(0.002)
    elapsed = time.perf_counter() - origin
    counters_after = common.netstat()
    sock.close()
    filler.close()
    server.close()

    retries = events[1:] if events else []
    previous = 0.0
    for event in retries:
        event["interval_ms"] = round(event["at_ms"] - previous, 1)
        previous = event["at_ms"]
    # The attempt's ending, in the same units as the ladder: when connect returned, and
    # whether the socket was still SYN_SENT at that moment or had given up.
    ended = started.get("connected", started.get("failed"))
    final = {"outcome": "connected" if "connected" in started else
             ("failed" if "failed" in started else "still_open")}
    if ended is not None:
        final["at_ms"] = round((ended - origin) * 1000, 1)
    if "error" in started:
        final["error"] = started["error"]
        final["errno"] = started.get("errno", 0)
    final["retransmissions_at_end"] = retries[-1]["retransmissions"] if retries else 0
    final["state_at_last_retry"] = retries[-1]["state_name"] if retries else "unknown"
    return {
        "seconds": round(elapsed, 1),
        "limits": limits,
        "events": events,
        "retries": retries,
        "retry_count": len(retries),
        "first_retry_ms": retries[0]["at_ms"] if retries else 0,
        "last_retry_ms": retries[-1]["at_ms"] if retries else 0,
        "gaps_ms": [event["interval_ms"] for event in retries],
        "states": sorted({event["state_name"] for event in retries}),
        "final": final,
        "counters": common.counter_delta(counters_before, counters_after),
    }
RetransmissionWhen, since the first SYNGap since the previousSocket state at that instant
11,015 ms1,015 msSYN_SENT
22,042 ms1,027 msSYN_SENT
33,067 ms1,024 msSYN_SENT
44,091 ms1,024 msSYN_SENT
55,114 ms1,024 msSYN_SENT
67,127 ms2,012 msSYN_SENT
711,159 ms4,032 msSYN_SENT
819,351 ms8,192 msSYN_SENT
935,478 ms16,127 msSYN_SENT
1069,527 ms34,049 msSYN_SENT
Table 7: Every retransmission of one client whose SYN kept meeting a full queue, timed from the first SYN (probe 09): 10 retries, the last at 69,527 ms, then connect returned TimeoutError with errno 110 at 135.1 s.

Two columns of that table carry the diagnosis. The last one makes it readable as SYN retransmissions rather than anything else: the kernel reported SYN_SENT at every one of them, so each is a fresh SYN from a socket whose handshake never completed, not a segment resent on an established connection. And the attempt did not end in a reply: connect came back with errno 110, ETIMEDOUT, which is the kernel expiring the socket rather than a deadline the program set – the probe left the socket ten seconds beyond this trace window and the call still returned inside that margin.

The gap column is the timer itself, and it is not a neat doubling grid: a socket timer is armed in the kernel’s timer wheel (kernel/time/timer.c) in ticks of HZ 250 – 4 ms each – and an expiry that falls between two buckets is rounded up into the later one, so a step is never early and how late it can be is bounded by one bucket of the level it lands in. Every gap in the table fits that grid, the thirty-two-second one included; the wheel’s own table, the two clocks it is read with, and the check of every step are folded below:

Table 7 at HZ 250: the wheel’s own table, the two clocks, and every step checked

Linux arms the retransmit timer as a jiffies timer in the kernel’s timer wheel (kernel/time/timer.c), whose levels grow coarser as the expiry moves out, and which is built from the kernel’s own tick rather than from the clock the proc interface reports. This kernel was built with HZ 250: /proc/config.gz has CONFIG_HZ=250, CONFIG_HZ_250=y and every other HZ option unset, which probe 12 reads. At 250 Hz one tick is 4 ms, and the header table of timer.c gives the wheel’s first levels buckets of 4 ms, 32 ms, 256 ms and 2,048 ms, each level eight times coarser than the one below, with an expiry that falls between two buckets rounded up into the later one and never down. So a step is never early, and how late it can be is bounded by the bucket of the level its expiry lands in. getconf CLK_TCK prints 100 on this host and that number is not this tick: it is the C library’s clock, the unit /proc/net/tcp prints its timer field in, which is why probe 09 multiplies that field by ten – probe 12 times one timer from its full value to zero and gets 9.9 ms a unit. That field is the one place the two clocks look alike: it counts the C library’s hundred a second, while the wheel’s buckets are built from the tick, at 250 a second, and the table above is the tick’s.

The ladder fits that grid, step by step. The five one-second steps arm 1,000 ms – 250 ticks – and land in level 1, whose range is 256 ms to 2,047 ms with a bucket of 32 ms: measured, they came back at 1,024 ms, which is 256 ticks, six of them past the arm. The two-second step, 2,012 ms, is in the same bucket. The 4 s, 8 s and 16 s steps land in level 2, bucket 256 ms, and none of them ran more than 192.2 ms late. The last step is the clearest case: 32,000 ms is 8,000 ticks and lands in level 3, whose bucket is 2,048 ms – 6.4% of that arm – so one bucket past the arm is the latest that timer can fire. It fired at 34,049 ms: 2,049 ms, 6.4%, one bucket and the tick that serviced it. The same ladder traced again for this page (probe 11) put that step at 1,537 ms (4.8%) late instead: inside the same bucket, and the difference between the two traces is where in the bucket the arm fell, so the overshoot is a bound rather than a constant a program can subtract. The table prints the interval the socket actually took.

The shape is worth reading twice, because part of it is what RFC 6298 asks for and part of it belongs to this kernel. Linux starts the SYN retransmission timer at TCP_TIMEOUT_INIT, one second (include/net/tcp.h), and exponential backoff is meant to double it on every retry. What interrupts the doubling here is net.ipv4.tcp_syn_linear_timeouts, 4 on this host (table 2): since kernel 6.7 that setting holds the timer at one second for the first few retransmissions, and the kernel documentation gives the sequence it expects for a value of four as 1, 1, 1, 1, 1, 2 and 4 seconds. The measured ladder is that sequence to within a few tens of milliseconds; only after the linear phase does the timer double, which is why the last five gaps are 2,012 ms, 4,032 ms, 8,192 ms, 16,127 ms and 34,049 ms.

The two SYN settings are also why table 7 has 10 rows when tcp_syn_retries is 6. That value is the exponential budget only; a socket in SYN_SENT is given the linear phase on top of it, six plus four, and gives up on the timer that follows the last retransmission of that total. Measured, the attempt ended with TimeoutError and errno 110, which is ETIMEDOUT arriving from the kernel rather than from the caller: nothing in the probe set a connect deadline short enough to produce it, so the socket expired because its own stack ran out of retransmissions. It happened at 135.1 s, where the documentation’s arithmetic for these two values puts the final timeout at 131 s and the last retransmission at 67 s. So the retry count in table 2 and the row count in table 7 are not in conflict: one is the part of the budget that doubles, the other is the whole budget a dropped client spends. Nothing in that budget is a server behaviour – it is the client’s own stack, and it is why a full queue produces a stall measured in minutes instead of an error measured in microseconds.

The same ladder explains the three numbers in the title, and it does so on either side of that kernel change. Before the linear phase existed the timer doubles from the first retransmission and a client comes back at 1, 3, 7, 15, 31 and 63 s, and the attempt ends at 127 s. On this host the linear phase adds three retries at about two, four and five seconds before the doubling starts, so the same three instants arrive on the first, third and sixth retries instead of the first three – 1,015 ms, 3,067 ms and 7,127 ms. Which retry an instant belongs to is a kernel detail; the instants themselves are the client’s clock, and one second, three seconds and seven seconds after the first SYN was dropped are where a stalled connect actually returns, whichever kernel the client runs.

The next table puts a block in front of that grid. A listener with listen(0) is filled by one connection that is held open, two more clients then arrive at a queue with no room, and the accept loop stays stopped for a chosen time; when it starts, the dropped clients can only finish on their next retry. The held connection is what makes the three rows comparable: every client of every trial met a full queue, so what is timed is the timer and nothing else.

BlockClients blockedCompleted atRetransmissions
500 ms6/61,004 ms to 1,024 ms1
2,500 ms6/63,052 ms to 3,071 ms3
5,500 ms6/67,116 ms to 7,117 ms6
Table 8: 3 trials per block, 2 clients per trial, and every blocked client of every trial in one line. “Clients blocked” is that count as blocked of arrived: the queue already held one connection when the burst arrived, so no client of any trial got in before the loop restarted. “Completed at” is when its connect returned, from its own first SYN, and “Retransmissions” is the socket’s own total_retrans at that moment – the two columns are the same measurement seen from two sides.

This is where the title’s numbers come from. A client blocked for 500 ms came back at 1,004 ms; blocked for 2,500 ms, at 3,052 ms; blocked for 5,500 ms, at 7,116 ms. One second, three seconds and seven seconds after the first SYN was dropped are three instants a client really does stall at, measured rather than assumed – and they are the first, third and sixth retries of table 7, which is why half a second behind a full queue becomes one and two and a half seconds become three. The block decides whether the client waits; the timer decides how long.

There is at least a second timer underneath the first, and it is the reason a reply can be late even when the connect clock looks clean. A client whose handshake completed still has to get its request through: with the accept queue full, the final ACK creates no child socket, so the request itself is retransmitted on the established connection’s timer, which starts at the minimum RTO and doubles. One socket therefore carries two counts by the time its reply arrives – the SYN retransmissions the handshake spent before connect returned, and the retransmissions the request paid after it – and the three listen(1) trials, split by both counts, show what each client actually paid:

SYN retransmissionsData retransmissionsClientsEarliest replyLatest reply
0060.60 ms3.1 ms
201529.4 ms44.2 ms
217231.3 ms250.5 ms
226435.8 ms9,693 ms
233859.6 ms3,594 ms
2427,947 ms7,947 ms
Table 9: Every served client of the three listen(1) trials (39 of them), read from the moment the loop recovered and split by the two counts the socket carries when its reply arrives: the SYN retransmissions before connect returned and the data retransmissions after it.

The split is what the single count hid. The first row never retransmitted anything: those clients were connected while the loop was still stopped and the reply was waiting for it. The second row is the handshake and nothing else – 15 clients that resent their SYN twice and then sent a request that got through on its first attempt, answered within 44.2 ms of recovery. The data timer starts at the third row, where the data column becomes 1, and that row and the ones below it are the only ones that paid it.

From there the reply time follows the data column, but the count is not a clock. One data retransmission put the reply between 231.3 ms and 250.5 ms, two between 435.8 ms and 9,693 ms, three between 859.6 ms and 3,594 ms. The count records how often the established socket’s timer fired while the queue had no room, not when room appeared: one row here spans 435.8 ms to 9,693 ms for the same count, and the client at the top of that span took 11,693 ms from its first SYN, block included. That is why the table reports the range of each row instead of a single figure. None of those clients was ever refused, and none of them saw an error: they were connected, they sent a request, and the request was retransmitted until a child socket existed to receive it. That is the part a client-side trace shows as a slow server and a server-side trace shows not at all.

That spread is why the count cannot be the whole explanation: there are at least two timers, not two, and the tail of the table is still unresolved. Two data retransmissions armed from the minimum RTO – 200 ms on this kernel, 50 ticks – add up to a fraction of a second, not to the 9,693 ms of the 6-client row, so a third thing was waiting that this record does not name. What it does take off the list is a retransmission from the server’s end of the handshake. The queue sample held 0 half-open requests while the loop was stopped, which is what answering with a cookie means: the kernel stored no request to resend a SYN-ACK from. TCPSynRetrans does not put one back either: it counts SYN segments the host sent, both ends of this probe ran on that host, so the clients’ own retransmissions are inside it – 84 is exactly twice the 42 cookie answers, two SYN retransmissions for each connection that had to retry, and a server that stored no request had no SYN-ACK of its own to send again. So the honest reading is narrower than the one this table invited: the client’s own data timer is one of at least two timers, the count is a floor under what each client paid, and why the (2, 2) row waited 9,693 ms is left open rather than assigned a cause. The figure that survives either way is the reply each client actually received.

The kernel keeps its own record of the same three trials, and it is the number to put on a dashboard. ListenOverflows and ListenDrops moved by exactly the same amount – 189 each – because one dropped attempt is counted by both, which makes them a count of attempts that found no room rather than two independent failures. SyncookiesSent counted 42 and TCPSynRetrans 84, this host’s own SYN retransmissions. When a client reports a stalled connect, the interesting question is not whether the server was busy; it is whether these counters moved.

The listen(4) row is the same mechanism with fewer steps. Five slots for a burst of 16 still overflow, but 15 handshakes finished before recovery, 1 reply deadline expired across the three trials, and the slowest client finished at 2,246 ms, with the middle client of a trial finishing 33 ms after the block ended. A queue size that is “bigger than before” is not a fix until it is at least as large as the burst; section 5 measures where that line is.

What the reset flag does and does not change: A full accept queue does not answer with a reset, and the setting whose name suggests otherwise is narrower than it sounds. net.ipv4.tcp_abort_on_overflow is 0 here: when a handshake completes and the queue has no room for the child socket, Linux drops the final ACK and the client keeps retrying, which is the stall this page measures. The ip-sysctl documentation describes only the other branch of that decision – setting the flag to 1 resets those connections instead. Whether a dropped SYN is answered at all is decided earlier and elsewhere, in the kernel’s SYN-receive path: tcp_conn_request() in net/ipv4/tcp_input.c sends a request that finds sk_acceptq_is_full() to its own drop label, and that path never reads the flag. The counters agree with the source, which is why the claim is sourced to the implementation rather than to the document: ListenOverflows and ListenDrops moved by the same amount in section 4’s trials, one at the fullness test and one at the drop. The reset branch itself was not measured on this host; what is measured is the drop, and what the drop costs.

5. Sizing the queue to the burst

If a full queue is what turns a block into a stall, the first fix is arithmetic: make the queue at least as large as the number of connections that arrive while the loop is stopped. This arm holds the block at 1,000 ms and the burst at 32, and changes only the backlog, from four to sixty-four. Three trials per size, and the figure that matters is the slowest client: if the queue held the whole burst, the slowest client waited for the block and nothing more.

listen(n)ServedTimeoutsSlowest client, median of trialsSlowest client, best trialFinished within block + 50 ms
43202,688 ms2,252 ms13
163201,023 ms1,018 ms32
323201,008 ms1,007 ms32
643201,006 ms1,006 ms32
Table 10: 32 clients against a 1,000 ms block, 3 trials per queue size, 32 clients per trial. The two slowest-client columns are the median and the best of those 3 trials. Every arm served every client; the column that separates them is the tail, and a tail that lands on the block itself means the queue was deep enough.

The tail separates four slots from the rest and then stops separating. At listen(4) the slowest client took 2,688 ms in the median trial, and only 13 of 32 clients finished within the block plus 50 ms; at listen(16) the same burst cost 1,023 ms with all 32 of them inside that window, and at listen(32) and listen(64) it cost 1,008 ms and 1,006 ms. Sixty-four buys nothing over thirty-two, and sixteen is already indistinguishable from both.

That last sentence is the honest limit of this experiment, and section 4 explains it. Sixteen slots are half the burst, so half the clients must have been dropped – and a dropped client’s first retransmission lands at one second, which is exactly when this block ends. The retry grid therefore hides the difference between a queue that was big enough and one that was half big enough, as long as the block is one second long. Four slots were too small for the grid to hide: those clients needed a later step and paid 2,688 ms. Size the queue to the burst, and verify the size with a block that is not a whole multiple of the retry grid.

Two qualifications keep this from becoming a rule as simple as “ask for a thousand”. The first is the cap: anything above somaxconn, 4,096 here, is granted as 4,096 without an error, so the number in the code and the number in the kernel can differ by a factor of ten and nothing will say so. The second is that arrivals do not stop while the loop accepts: a deploy that starts a hundred clients and a queue of exactly a hundred will overflow on the connections that keep arriving while the first hundred are accepted. The headroom in the sizing helper exists for that, not for the block itself.

from __future__ import annotations
def backlog_for(burst: int, headroom: float = DEFAULT_HEADROOM,
                cap: int | None = None) -> int:
    """The backlog to request so that a burst of ``burst`` connections is not refused.

    ``headroom`` covers the connections that arrive while the first ones are still being
    accepted - a deploy that starts a hundred clients at once does not have a hundred
    connections pending, it has a hundred and some that keep arriving. The result is capped
    by the kernel, because asking for more than ``somaxconn`` hides the ceiling from the
    operator who reads the log line.
    """
    return effective_backlog(backlog_asked(burst, headroom), cap)

That function is the whole arithmetic – headroom first, then the kernel’s ceiling on the way to the socket – and listen.py in the appendix carries the rest of it: the cap read from somaxconn, the requested value kept beside the grant for the log line, and the socket that listens with both.

Sizing the queue is also where the reasoning usually stops, and that is the wrong place to stop. A queue deep enough to hold the burst converts a stalled connect into a slow reply – the change from section 4 to section 3 – and it does not shorten a single handler. The next measurement moves the same blocking work to a thread and shows what the queue cannot do.

6. Where the fifty milliseconds goes

Four placements of the same 50 ms, the same 32 clients arriving through one barrier, and the same reply line. The handler content is identical in all four: the only question each arm answers is who waits while it runs. With the work on the loop, every client pays for all the work ahead of it; with the work in a pool, only the clients whose turn has not come pay, and the ones already running pay nothing extra; with a bound in front of the pool, the excess is answered almost at once with “not now” instead of being made to wait.

PlacementServedRefusedReply p50Reply p95Refusal p50Loop lag maxThroughput
in the loop320870 ms1,523 ms—1,606 ms19.6 / s
to_thread, 4 threads320253.8 ms404.4 ms—1.5 ms77.7 / s
pool, bound 8824103.6 ms104.1 ms4.8 ms0.90 ms73.5 / s
pool, bound 32320254.1 ms404.4 ms—1.9 ms77.8 / s
to_thread, default320154.9 ms254.8 ms—1.1 ms103.5 / s
Table 11: 32 clients, 50 ms of blocking work per request. The first four rows are a controlled comparison and every pool in them runs 4 threads – including the to_thread row, whose default executor this probe pins at four, because a row measured against a differently sized pool is not a measurement of placement. The last row is the same one-line call with the executor the interpreter makes for it, min(32, cpu + 4) threads, which is 6 here: what a developer who changes nothing else actually gets. Throughput is served replies divided by the arm’s wall time; the refused arm moves fewer requests in less time, which is the trade a bound makes on purpose.

The first row is the mistake in its natural state. With the 50 ms on the loop, the loop is busy for the sum of all 32 handlers, so each client waits for the ones ahead of it: the median reply is 870 ms, the 95th percentile is 1,523 ms, the largest 1,623 ms, and the watchdog saw the loop stop for 1,606 ms. Throughput is 19.6 replies per second, which is one loop doing sequential work – the arithmetic of a single-threaded server with no way to overlap anything.

The second row is the smallest change that works. asyncio.to_thread hands the call to the default executor, the loop goes back to moving bytes, and the median reply falls to 253.8 ms with the loop’s worst wake-up at 1.5 ms. Throughput is 4.0 times the first row, because four handlers now run at the same time instead of one. What it does not say is what happens when the arrivals keep coming: the default executor has a queue, the queue has no limit, and a handler that is slower than the arrival rate turns that queue into the same unbounded backlog the listen socket had – just on the other side of the loop.

The last two rows are that sentence measured. With the pool bound at 8, eight clients were served at 103.6 ms median and the other 24 were told so in 4.8 ms – 21.6 times faster than being served, which is the entire value of a refusal. With the bound at 32, nothing was refused and the median rose to 254.1 ms: the same work, a longer queue, and a client that cannot tell a queued request from a slow one. The loop stayed free in both (1.9 ms and 0.90 ms of lag), which is the point: past a certain load, the loop’s health and the client’s latency stop being the same question.

The bottom row is the number a reader can reproduce without changing anything else. asyncio.to_thread uses the loop’s default executor, and a program that never installs one gets the executor CPython creates at min(32, cpu + 4) threads – 6 on this host – so that row runs the same call on the pool a developer is handed for free: the median reply is 154.9 ms against 253.8 ms for the four-thread row, and throughput is 103.5 replies a second against 77.7, 1.3 times more, because two more handlers are in flight while the burst arrives. The pin in the rows above is what makes them a measurement of placement rather than of pool width; the bottom row is what the smallest possible change is actually worth.

from __future__ import annotations
class Overloaded(RuntimeError):
    """Raised instead of queueing a call once ``max_in_flight`` is reached."""
def has_room(in_flight: int, max_in_flight: int) -> bool:
    """Whether the pool can take one more call: the whole bound is this comparison.

    It is a function rather than a condition inline in ``run`` so the decision has one
    place and one name: a pool that admits the call it should have refused is the failure
    this module exists to prevent, and it is decided here, not in the bookkeeping around it.
    """
    return in_flight < max_in_flight

The bound is one comparison and the refusal is one exception, which is why a server can answer busy in 4.8 ms instead of holding the call. The counting around that comparison – the in-flight figure, the per-call deadline, and the finally that keeps the counters honest when a handler raises – is run() in offload.py in the appendix.

The same question, asked of arithmetic instead of sleep, has a different answer, and it is the one that keeps this advice from becoming “move everything to a thread”. These arms run 16 requests of 40 ms of pure Python arithmetic each – a fixed number of loop iterations, calibrated once so both arms do exactly the same work – in the loop and on the same four-thread executor.

Placement of the arithmeticReply p50Reply p95ThroughputLoop lag maxCPU time
in the loop295.7 ms485 ms29.6 / s401.1 ms0.54 s
four-thread pool526.6 ms533.5 ms29.7 / s160.4 ms0.55 s
Table 12: 16 requests of 40 ms of arithmetic each, three trials, 4 threads in the pool. The CPU time column is the check that the two rows did the same work: 0.54 s against 0.55 s. What the pool bought was not throughput.

Threads are not parallelism, and this is what that costs: Offloading only helps work that blocks, and the two tables above are the measurement of that sentence. With 40 ms of arithmetic per request, the four-thread pool moved 29.7 replies a second against 29.6 in the loop – a ratio of 1.00, because CPython’s GIL lets one thread run bytecode at a time and four threads therefore compute nothing more than one. What the pool did buy is the loop’s own health: its worst wake-up fell from 401.1 ms to 160.4 ms, 2.5 times better, while the client’s median reply got worse – 295.7 ms to 526.6 ms, 1.8 times – because the work now queues behind the GIL instead of behind the loop. Threads buy back waiting – a socket, a file, a lock, time.sleep – not computing. For CPU-bound handlers the unit of concurrency has to be a process, and the queue in front of it has to be bounded too.

7. Two hundred requests, in the loop and off it

The last measurement is the ordinary case rather than the burst: 200 requests, 8 in flight, 20 ms of blocking work each. Nothing overflows in either arm – the accept queue is deep enough and the connect clock will say so – so the only difference left is what each request waits for once it is accepted. This is the arm that decides whether the previous sections describe a production shape or an artificial burst.

PlacementServedReply p50Reply p95Reply maxLoop lag maxThroughputWall time
in the loop200163.2 ms164 ms164.7 ms161 ms48.9 / s4.088 s
four-thread pool20040.3 ms40.9 ms42.5 ms5.9 ms197 / s1.015 s
Table 13: 200 requests at 8 in flight, 20 ms per request. Connect p50 was 44 µs in the loop arm and 48 µs in the pooled one: by the connect clock alone the two arms are identical, and that is the point of measuring both clocks.

On the reply clock they are not identical at all. The loop arm answers at 163.2 ms median, which is 8 requests in a line, each behind the 20 ms of the one before it; the pooled arm answers at 40.3 ms, two waves of four threads. The ratio is 4.1 at the median and 4.0 in throughput, and the whole workload finishes 3.07 s sooner. The loop’s worst wake-up tells the same story in one number: 161 ms against 5.9 ms.

For capacity planning the useful reading is the shape of the two distributions. The loop arm is a staircase, not a tail: its p50 and its maximum are 163.2 ms and 164.7 ms, because every request waits for a fixed number of turns on the same thread. The pooled arm has a tail – 40.9 ms at p95 against 40.3 ms at p50 – because which of four threads picks a request up is not deterministic. A latency SLO set from the loop arm’s numbers will be missed by every request the moment one handler takes longer than the others; an SLO set from the pooled arm has to be a percentile, and the pool’s limits have to be part of it.

8. The guard: what each module decides

The measurements above are three decisions, and the package in the appendix makes each of them in one place so a server cannot get them separately wrong. Six modules, 560 lines, and a suite of 75 tests in 6 files. None of them is clever; each exists because the default behaviour of the thing it wraps is unbounded in a way that only shows up under a burst.

ModuleThe decision it ownsWhat it is measured against
listenhow many pending connections to ask for, and what the kernel will actually granttables 2, 3 and 10
laghow late the loop is waking its own timers, held in a ring of the last samplestables 1, 4 and 11
offloadhow many blocking calls may be in flight, and the refusal that replaces the queue behind themtables 11 and 12
serverwhich of four lines a client gets, and that the handler never runs on the looptables 11 and 13
reportwhich of the two clocks to open first when a client complainssection 10
Table 14: One decision per module, and the measurement that fixes its default. The numbers are not tuning parameters pulled from a blog post; each is the value this host produced, and each module takes its limit as an argument so a different host can supply its own.

The four reply lines are the part a client depends on. pong means the handler returned, busy means the pool was at its bound and the call was refused rather than queued, timeout means the handler was still running when its deadline passed, and error means it raised. Those four are distinguishable on the client in a way that a stalled connection and a slow handler are not, and the refusal is only worth anything if it is fast: 4.8 ms against 103.6 ms for a served request in the same arm.

from __future__ import annotations
def first_clock(connect_ms: float, first_byte_ms: float, lag_p95_ms: float = 0.0,
                queue_floor_ms: float = QUEUE_FLOOR_MS) -> str:
    """Which clock is slow: the queue's, the loop's, or neither.

    The queue is named first: a full queue also delays the first byte, so a rule that looked
    for latency first would send an operator with a full queue off to profile handlers. This
    is the decision on its own; ``diagnose`` is the same decision with the sentence each
    verdict prints beside it.
    """
    if connect_ms >= queue_floor_ms:
        return QUEUE
    if first_byte_ms >= max(queue_floor_ms, lag_p95_ms * 2):
        return LOOP
    return CLEAN

The three branches are the rule; what each verdict prints as its reason, and the one-line log that carries the backlog, the pool peak and the loop’s p95 together, are report.py in the appendix.

What a timeout does not do: A timeout in the pool does not stop the thread. When a call passes its deadline the coroutine stops waiting and the client gets timeout, but the function keeps running until it returns, and its worker stays busy until then. The bound therefore counts calls in flight, not calls that will be quick, and a handler that ignores its own deadline will hold a worker for as long as it likes. Pass deadlines into the blocking function – socket timeouts, lock timeouts, subprocess timeouts – rather than relying on the wrapper to end the work.

The suite tests the boundaries rather than the happy path: the kernel cap against a request above it and the request value kept beside the granted one, the ring discarding its oldest sample, the pool refusing at its limit and counting the refusal, a cancelled caller leaving the pool without being counted as a failure, the server answering error for a line above MAX_LINE and for a handler that raises, the monitor seeing a deliberate block, and the diagnosis naming the queue before the loop when both clocks are slow. The oversized-line test is the one that holds a boundary together: MAX_LINE is passed to start_server as the stream limit, so the constant in the code is the number that decides, and the test serves a line one byte under it and refuses one above it rather than comparing the constant with a line the stream had already rejected.

9. Deploy order

Each step makes the next one possible, and each is verified by the clock it moves. Doing them in this order means every change has a before and an after on the same host, rather than four settings found on the same Tuesday.

  1. Record both clocks before changing anything. A client probe that writes connect time and first-byte time as separate fields. Section 7 is the reason: the connect clock read 48 µs in both arms while the reply clock differed by 4.1 times, so a metric that merges them cannot tell the two failures apart.
  2. Size the listen backlog to the peak burst, with headroom. For a burst of 32 the tail separated four slots from the rest and then stopped: 2,688 ms at listen(4), 1,023 ms at sixteen and 1,008 ms at thirty-two. Log the value you asked for next to the kernel’s ceiling, and keep them apart in the code: the shipped line prints both, backlog=96/4,096 in the refused arm of section 6, because a request above the ceiling is granted as the ceiling in silence.
  3. Move blocking handlers off the loop. Start with asyncio.to_thread if the handlers already block: it is one line and it took the median from 870 ms to 253.8 ms in section 6 with a four-thread pool, and to 154.9 ms on the executor a program gets when it installs none. Then replace it with a pool whose size you chose, because the default executor’s queue is unbounded.
  4. Bound the pool, and answer the refused call. 8 served and 24 refused in 4.8 ms is a healthier arm than 32 served at 254.1 ms: the client learns something it can act on. The bound belongs to the pool, not to the accept queue.
  5. Alert on the listen socket’s own counters, not only on request latency. ListenOverflows and ListenDrops are the queue’s count of attempts that found no room: they moved by 189 each in section 4’s three trials, in lockstep, because one dropped attempt is counted once at the fullness test and once when the request is discarded. Put them beside the loop’s lag: a blocked loop and a full backlog both raise request latency, only the second moves those two counters, and only the first drives the monitor’s worst wake-up to the 1,606 ms that section 6’s blocked arm recorded. That number belongs to this experiment, not to a dashboard: an alert threshold is set from the service’s own latency budget – a p95 target of, say, 50 to 100 ms for an interactive API, of which the loop may spend a fraction – and this host’s figure would be an outage, not a warning. Lag p95 is the signal that arrives while the queue is still absorbing the burst, which is the only window in which a deploy can still be rolled back cheaply.

10. Reading the two clocks in production

Three cases cover almost every report of a slow server, and they are separated by two numbers rather than by a profile. In the queue case the connect sits orders of magnitude above the 34 µs a loopback handshake costs – section 4 showed the staircase it produces – and the reply is late only because the connection was late. The loop case has a connect at the same 48 µs as a healthy server and a reply at 1,004 ms, which is a block and not a load. The clean case has both clocks at the level a loopback request costs, and a client that still complains is complaining about something the server never saw.

The order of the checks matters, because one case masks the other. A full backlog is named first: when connects are slow, the accept queue is the answer, and a queue that is full also delays the first byte – the request cannot be read from a connection the server has not accepted. Only when the connect clock is clean does the loop become the suspect, and then the monitor’s lag is the evidence. That is the rule diagnose applies, with a queue floor of 100 ms: a handshake this package measures costs 34 µs on loopback, so a connect above the floor is one the loop cannot account for. That floor is the one number in the diagnosis that belongs to the deployment rather than to the package, and it is an argument for that reason: across a region a healthy connect is a round trip, and a hundred milliseconds there would name the queue for every connection, so pass a few times the connect time the deployment considers normal.

The usual cause: A backlog that is genuinely too small for the traffic is rare; a backlog that is smaller than a deploy’s own burst is common. Scale-out events, restarts and cron jobs all open many connections within a second, and each of them is a burst a queue of 1 cannot hold. Size the bound for the burst, not for the average, and keep the pool’s limit separate from it: the queue absorbs arrivals, the pool absorbs work, and neither one should be allowed to grow without a number.

Frequently asked questions

Why does connect hang instead of failing with a connection error?

Because a full accept queue does not refuse the handshake, it drops the SYN. On this host net.ipv4.tcp_abort_on_overflow is 0, so no reset is sent and the client keeps retrying on the timer table 7 measures. The clients in section 2 sat for 12,012 ms – their own timeout – without an error, because there was nothing to report yet.

Is a bigger backlog enough on its own?

It is enough to stop the stall and not enough to make the server fast. With listen(32) the slowest of 32 clients waited 1,008 ms, which is the block itself, so the connections were fine; the handlers behind them still ran on one loop, and section 6 shows what that costs. A bound on the pool is a separate decision from the size of the queue.

Why do connects arrive at about one second, three seconds and seven seconds?

Those are instants of the client kernel’s SYN retransmission timer, not server timings. Measured on this host, one socket waiting at a full queue retransmitted 10 times, the first at 1,015 ms and the last at 69,527 ms (table 7), and a client resumes at the first of those instants after the queue frees: a 500 ms block ended at 1,004 ms, a 2,500 ms block at 3,052 ms and a 5,500 ms block at 7,116 ms. The timer fires about once a second five times before it doubles, because tcp_syn_linear_timeouts is 4 here; a kernel without that setting doubles from the first retry, at 1, 3, 7, 15, 31 and 63 s. The three numbers in the title are the instants both ladders share: the first three there, the first, third and sixth here.

Why does the queue hold one more connection than the backlog says?

listen(n) sets the accept queue’s limit, and the kernel’s fullness test compares the queue’s length with that limit using > rather than >= (sk_acceptq_is_full in include/net/sock.h), so one connection is admitted past it. Measured here: 2 completed handshakes at listen(1), 5 at listen(4), and 1 at listen(0), which is a legal request for a queue of one.

Does asyncio.to_thread fix a blocked event loop?

For work that waits, yes: the same 50 ms of time.sleep moved the median from 870 ms to 253.8 ms and the loop’s worst wake-up from 1,606 ms to 1.5 ms. For work that computes, no: 40 ms of arithmetic per request on the same four threads came to 29.7 / s against 29.6 / s in the loop, because the GIL lets one thread run bytecode at a time; only the loop’s own wake-up improved, from 401.1 ms to 160.4 ms. Offloading moves waiting, not arithmetic. The width of that executor matters for the first case and not the second: the same one-line change against the interpreter’s own executor, 6 threads here, answered at 154.9 ms instead of the 253.8 ms a four-thread pool gave.

How do I tell a full queue from a blocked loop in one graph?

Plot connect time and first-byte time as two series. Section 3 is the loop case: connect at 0.06 ms and reply at 1,004 ms. Section 4 is the queue case: connect times in the seconds. When both are slow, the queue is the one to name first, because it also delays the reply.

What backlog should I ask for?

The largest burst of new connections the process must survive, times a headroom, capped by 4,096 on this kernel. Thirty-two arrivals needed more than listen(4) and stopped improving above listen(32): 1,008 ms against 2,688 ms at four slots. Log the requested value and the granted one, since a request above the cap is granted as 4,096 in silence.

Why does the server look idle while clients wait?

Because a dropped SYN never reaches the application. There is no request to log, no handler to time, and no exception to catch: the queue was full and the kernel discarded the attempt. Section 2 is that state exactly – nothing calling accept, 11 clients waiting, an application with nothing to report.

Does a load balancer or keep-alive pool hide this?

Keep-alive hides it while it lasts: a reused connection never touches the queue, so a pooled client sees none of the staircase. It exposes it on the day the pool is invalidated – a deploy, a timeout, an idle sweep – when every client opens a new connection at once. That is the burst the backlog has to hold, and the reason section 5 measures thirty-two arrivals rather than an average rate.

What should I alert on?

Five signals in three groups. The host’s kernel counters are the first pair: ListenOverflows and ListenDrops count attempts that found no room at the accept queue – 189 each in section 4’s three trials, always in lockstep – and because both are counted per host rather than per socket, the whole network namespace adding to one number, they need ss -lnt beside them: the listening socket’s Recv-Q against its Send-Q is what names the listener whose accept queue is full. The client’s metric stands alone as the second group: the connect p95 the caller sees, the only one of the five measured outside the host, and the one that says the stall reached a client at all. The server’s two are the third group: the loop’s lag p95, which rises when the loop is blocked, and the pool’s refused count, which rises when a bound does its job. Read as three groups they separate the two causes – only the kernel counters move for a full queue, only lag moves for a blocked loop, and the refused count says whether a refusal is a fault or the design – while a request-latency alert alone fires for both causes and names neither.

Reproducing this

Every figure on this page comes from one of the probes below, run in order on the host in table 1. Each writes a JSON record to results/, and the build reads only those records, so a number that is not in a file cannot appear in the text.

  1. 00_host.py – the stack, the kernel limits, and the five baselines of table 1.
  2. 01_lag.py – four placements of one 50 ms block, with a 5 ms watchdog on the loop.
  3. 02_queue.py – five backlog sizes, 16 clients each, and no accept call anywhere (table 3).
  4. 03_wide.py – 32 clients against 1,000 ms on a deep queue, with the free arm as the control (tables 4 and 5).
  5. 04_narrow.py – the same block behind listen(1) and listen(4), 3 trials each, with the handshake and the reply on separate deadlines (tables 6 and 9).
  6. 09_syn.py – the retransmission grid read from one socket’s own state, and the same socket in front of three block lengths (tables 7 and 8).
  7. 11_ladder_repeat.py – the same ladder traced a second time, 80 s of it, which is where the second figure for the last step’s overshoot comes from (section 4).
  8. 12_proc_tcp_unit.py – the kernel’s own HZ from /proc/config.gz, and one pending timer read from /proc/net/tcp beside the wall clock, so the proc field’s unit can be told apart from the tick the timer wheel is built from (section 4).
  9. 05_sizing.py – four queue sizes against one burst (table 10).
  10. 06_fix.py, 07_endtoend.py and 10_cpu.py – the four placements of a blocking call, the 200 requests, and the same arithmetic in two places (tables 11, 12 and 13).
  11. 08_tests.py – the package suite, whose count is the one printed in section 8.

TechBobby Engineering writes one reproduced production failure per article, with the probe behind every number. The queue arithmetic, the lag monitor and the bounded pool ship as the acceptguard package in the appendix, with its 75-test suite.

Appendix: the package

The sections above print the one decision each file makes; here the files themselves are, each exactly as it ran – the same text the probes imported – folded so they do not interrupt the article. The limits are arguments, not constants, because the numbers in this article belong to this host.

The backlog arithmetic and the socket it produces: listen.py
"""The listen backlog: what the kernel grants, and what a burst needs.

``listen(n)`` is a request. Linux caps it at ``/proc/sys/net/core/somaxconn`` and, in
practice, admits one more connection than the limit reports: the fullness test compares the
accept queue's length with the limit using ``>`` rather than ``>=``, so the queue holds
``n + 1``. Both facts were measured on the host the article describes; the code here reads
the cap instead of assuming it.
"""
from __future__ import annotations

import math
import os
import socket

SOMAXCONN_PATH = "/proc/sys/net/core/somaxconn"
DEFAULT_SOMAXCONN = 4096
DEFAULT_HEADROOM = 1.5


def somaxconn(path: str = SOMAXCONN_PATH) -> int:
    """The kernel's ceiling on a listen backlog.

    A kernel that does not expose the file is treated as ``SOMAXCONN`` (4096), which is the
    value every current Linux default ships; the fallback is a value, not a measurement, and
    the caller can pass its own path to make it one.
    """
    try:
        with open(path, encoding="utf-8") as handle:
            return int(handle.read().strip())
    except (OSError, ValueError):
        return DEFAULT_SOMAXCONN


def effective_backlog(requested: int, cap: int | None = None) -> int:
    """What ``listen(requested)`` will actually enforce on this kernel.

    Negative requests raise rather than being clamped to zero silently: ``listen(-1)`` is a
    programming error, while ``listen(0)`` is a legitimate "one connection at a time".
    """
    if requested < 0:
        raise ValueError(f"backlog must not be negative: {requested}")
    ceiling = somaxconn() if cap is None else cap
    return min(requested, ceiling)


def backlog_asked(burst: int, headroom: float = DEFAULT_HEADROOM) -> int:
    """The backlog to request for a burst, before the kernel's ceiling is applied.

    ``backlog_for`` answers what the kernel will enforce; this answers what the code asked
    for. The two differ silently whenever the request is above ``somaxconn``, and a log line
    that prints only the effective value throws the difference away: a burst of five
    thousand asks for 7,500, is granted 4,096, and "backlog=4096/4096" tells the operator
    nothing about the shortfall. Both numbers belong in the line.
    """
    if burst < 0:
        raise ValueError(f"burst must not be negative: {burst}")
    if headroom < 1.0:
        raise ValueError(f"headroom must be at least 1.0: {headroom}")
    return max(1, math.ceil(burst * headroom))


def backlog_for(burst: int, headroom: float = DEFAULT_HEADROOM,
                cap: int | None = None) -> int:
    """The backlog to request so that a burst of ``burst`` connections is not refused.

    ``headroom`` covers the connections that arrive while the first ones are still being
    accepted - a deploy that starts a hundred clients at once does not have a hundred
    connections pending, it has a hundred and some that keep arriving. The result is capped
    by the kernel, because asking for more than ``somaxconn`` hides the ceiling from the
    operator who reads the log line.
    """
    return effective_backlog(backlog_asked(burst, headroom), cap)


def listen_socket(host: str, port: int, burst: int, headroom: float = DEFAULT_HEADROOM,
                  cap: int | None = None) -> socket.socket:
    """A listening TCP socket whose queue is sized for ``burst``.

    The socket is returned bound and listening, with ``SO_REUSEADDR`` set so a restart does
    not wait out ``TIME_WAIT``. It is put in non-blocking mode, which is a timeout of zero:
    ``accept`` raises ``BlockingIOError`` instead of waiting, so the caller decides how often
    it looks for a shutdown signal.
    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if hasattr(socket, "SO_REUSEPORT") and os.environ.get("ACCEPTGUARD_REUSEPORT") == "1":
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    server.bind((host, port))
    server.listen(backlog_for(burst, headroom, cap))
    server.setblocking(False)
    return server
The loop’s own lateness, in a ring of samples: lag.py
"""Event-loop lag, measured from inside the loop.

A blocked loop cannot be seen from a client: the kernel answers the handshake, the request
sits in a buffer, and the first byte arrives late. It can be seen from a task that asks to
be woken on a short interval and records how late the wake was. That lateness is the floor
under every request's latency for as long as the block lasts, so it is the number to alert
on - a request timer tells you the symptom, this tells you when it started.

The monitor holds at most ``window`` samples in a ring, so a long-running server keeps a
fixed memory footprint and a percentile that follows the last few seconds rather than the
whole process lifetime.
"""
from __future__ import annotations

import asyncio
import time
from collections import deque


class LagMonitor:
    """Sample how late ``asyncio`` wakes a timer, and keep the last ``window`` samples."""

    def __init__(self, interval_ms: float = 5.0, window: int = 2048) -> None:
        if interval_ms <= 0:
            raise ValueError(f"interval_ms must be positive: {interval_ms}")
        if window < 1:
            raise ValueError(f"window must be at least one sample: {window}")
        self.interval_s = interval_ms / 1000
        self.samples: deque[float] = deque(maxlen=window)
        self.started = 0
        self.stopped = False

    async def run(self, stop: asyncio.Event | None = None) -> None:
        """Sample until ``stop`` is set, or until cancelled.

        Each sample waits one interval and records how much later than intended the loop
        ran it. Lateness that happened before the monitor existed cannot be recovered, so
        the first sample lands one interval in - starting the monitor is not a measurement.
        ``stopped`` is set on every way out, cancellation included, so a caller can tell a
        monitor that is still sampling from one that has ended.
        """
        try:
            while stop is None or not stop.is_set():
                intended = time.perf_counter() + self.interval_s
                await asyncio.sleep(self.interval_s)
                self.started += 1
                self.samples.append(max(0.0, (time.perf_counter() - intended) * 1000))
        finally:
            self.stopped = True

    def snapshot(self) -> dict:
        """Count, median, p95 and maximum of the samples held, in milliseconds."""
        ordered = sorted(self.samples)
        if not ordered:
            return {"n": 0, "p50_ms": 0.0, "p95_ms": 0.0, "max_ms": 0.0, "late": 0}
        p95 = ordered[min(len(ordered) - 1, int(round(0.95 * (len(ordered) - 1))))]
        return {
            "n": len(ordered),
            "p50_ms": round(ordered[len(ordered) // 2], 3),
            "p95_ms": round(p95, 3),
            "max_ms": round(ordered[-1], 3),
            "late": sum(1 for value in ordered if value >= self.interval_s * 1000 * 2),
        }

    def exceeds(self, budget_ms: float) -> bool:
        """True when the worst sample held is over ``budget_ms``.

        A budget of twice the sampling interval is the smallest one that cannot fire on an
        idle loop: below that, ordinary scheduler noise trips the alarm.
        """
        return bool(self.samples) and max(self.samples) > budget_ms
The counted pool and the refusal: offload.py
"""A bounded thread pool in front of blocking work, with load shedding.

``asyncio.to_thread`` moves one call off the loop but says nothing about how many calls are
already waiting, so under load the queue in front of the default executor becomes the new
backlog: the loop stays free and the latency still grows without a limit. This wrapper
counts the calls it has submitted and not yet finished, and refuses the next one as soon as
that count reaches ``max_in_flight`` - a refusal the server turns into an immediate answer a
client can act on, instead of a timeout it cannot tell apart from a slow handler.
"""
from __future__ import annotations

import asyncio
import concurrent.futures

DEFAULT_MAX_WORKERS = 4
DEFAULT_MAX_IN_FLIGHT = 8
DEFAULT_TIMEOUT_S = 5.0


class Overloaded(RuntimeError):
    """Raised instead of queueing a call once ``max_in_flight`` is reached."""


def has_room(in_flight: int, max_in_flight: int) -> bool:
    """Whether the pool can take one more call: the whole bound is this comparison.

    It is a function rather than a condition inline in ``run`` so the decision has one
    place and one name: a pool that admits the call it should have refused is the failure
    this module exists to prevent, and it is decided here, not in the bookkeeping around it.
    """
    return in_flight < max_in_flight


class Offloader:
    """Run blocking callables on a fixed pool, counting what is in flight."""

    def __init__(self, max_workers: int = DEFAULT_MAX_WORKERS,
                 max_in_flight: int = DEFAULT_MAX_IN_FLIGHT,
                 timeout: float = DEFAULT_TIMEOUT_S,
                 thread_name_prefix: str = "acceptguard") -> None:
        if max_workers < 1:
            raise ValueError(f"max_workers must be at least one: {max_workers}")
        if max_in_flight < max_workers:
            raise ValueError(
                f"max_in_flight {max_in_flight} is below max_workers {max_workers}: "
                "the pool could never be fully used")
        if timeout <= 0:
            raise ValueError(f"timeout must be positive: {timeout}")
        self.max_workers = max_workers
        self.max_in_flight = max_in_flight
        self.timeout = timeout
        self.pool = concurrent.futures.ThreadPoolExecutor(
            max_workers=max_workers, thread_name_prefix=thread_name_prefix)
        self.in_flight = 0
        self.peak_in_flight = 0
        self.submitted = 0
        self.completed = 0
        self.rejected = 0
        self.timed_out = 0
        self.failed = 0

    async def run(self, function, *args):
        """Await ``function(*args)`` on the pool, or refuse if the pool is already full.

        The in-flight count is incremented before the call is submitted and decremented in a
        ``finally``, so a handler that raises, a call that times out and a call that returns
        all end at the same count. A timed-out call keeps its worker until the function
        itself returns; the coroutine stops waiting, the thread does not.
        """
        if not has_room(self.in_flight, self.max_in_flight):
            self.rejected += 1
            raise Overloaded(f"{self.in_flight} calls in flight, limit {self.max_in_flight}")
        self.in_flight += 1
        self.submitted += 1
        self.peak_in_flight = max(self.peak_in_flight, self.in_flight)
        loop = asyncio.get_running_loop()
        try:
            future = loop.run_in_executor(self.pool, function, *args)
            result = await asyncio.wait_for(future, timeout=self.timeout)
        except asyncio.TimeoutError:
            self.timed_out += 1
            raise
        except asyncio.CancelledError:
            # The caller went away - a client closed the connection, the loop is shutting
            # down. That is not a handler failure, and counting it as one would put it in
            # the log line beside the errors an operator has to act on.
            raise
        except BaseException:
            self.failed += 1
            raise
        else:
            self.completed += 1
            return result
        finally:
            self.in_flight -= 1

    def snapshot(self) -> dict:
        """The counters an operator needs, with the pool's own queue depth if it has one."""
        return {
            "max_workers": self.max_workers,
            "max_in_flight": self.max_in_flight,
            "in_flight": self.in_flight,
            "peak_in_flight": self.peak_in_flight,
            "submitted": self.submitted,
            "completed": self.completed,
            "rejected": self.rejected,
            "timed_out": self.timed_out,
            "failed": self.failed,
        }

    async def aclose(self, wait: bool = True) -> None:
        """Stop accepting work and end the worker threads.

        ``wait=False`` cancels the futures that have not started; a call already running
        cannot be interrupted from here, and the pool's threads are daemonised by the
        interpreter's shutdown anyway.
        """
        self.pool.shutdown(wait=wait, cancel_futures=not wait)
The four reply lines and the counters: server.py
"""A line server that keeps its queue wide and its loop free.

Each connection is answered with exactly one line, chosen from four:

``pong``    the handler returned;
``busy``    the pool was already at ``max_in_flight`` and the call was refused;
``timeout`` the handler did not return within ``timeout`` seconds;
``error``   the handler raised, or the request line was longer than ``MAX_LINE``.

The distinction matters at the client: a ``busy`` line is a load shed the client can retry
with backoff, while a connection accepted and then answered a second late reads as a slow
server and sends the operator to the wrong graph. The server never queues work beyond
``max_in_flight``: the accept queue absorbs bursts, the pool sheds what it cannot run, and
nothing waits in an unbounded executor queue in between.
"""
from __future__ import annotations

import asyncio
import time

from acceptguard.lag import LagMonitor
from acceptguard.listen import backlog_asked, backlog_for, somaxconn
from acceptguard.offload import Offloader, Overloaded

# The request line's ceiling, and the stream's own buffer limit: the server passes this to
# ``start_server``, so a line longer than this is refused by ``readline`` itself.
MAX_LINE = 64 * 1024


class GuardedServer:
    """The server's own record: counters, pool, monitor, and the listener it wraps."""

    def __init__(self, offloader: Offloader, monitor: LagMonitor | None, burst: int) -> None:
        self.server: asyncio.AbstractServer | None = None
        self.offloader = offloader
        self.monitor = monitor
        self.burst = burst
        self.monitor_task: asyncio.Task | None = None
        self.connections = 0
        self.served = 0
        self.busy = 0
        self.timeouts = 0
        self.errors = 0
        self.started = time.perf_counter()

    @property
    def port(self) -> int:
        """The port actually bound, which is what a test or a probe connects to."""
        sockets = (self.server.sockets if self.server else None) or []
        if not sockets:
            raise RuntimeError("server has no listening socket")
        return int(sockets[0].getsockname()[1])

    def snapshot(self) -> dict:
        """Everything the article's log line prints, in one dict."""
        return {
            "burst": self.burst,
            # What the code asked for, what the kernel enforced, and the ceiling between
            # them: a request above the ceiling comes back as the ceiling without an error,
            # so a line that printed only one of the three would hide the difference.
            "backlog_asked": backlog_asked(self.burst),
            "backlog": backlog_for(self.burst),
            "backlog_cap": somaxconn(),
            "connections": self.connections,
            "served": self.served,
            "busy": self.busy,
            "timeouts": self.timeouts,
            "errors": self.errors,
            "pool": self.offloader.snapshot(),
            "lag": self.monitor.snapshot() if self.monitor else {"n": 0},
            "uptime_s": round(time.perf_counter() - self.started, 3),
        }

    async def aclose(self) -> None:
        """Close the listener, stop the monitor, then end the pool."""
        if self.server is not None:
            self.server.close()
            await self.server.wait_closed()
        if self.monitor_task is not None:
            self.monitor_task.cancel()
            try:
                await self.monitor_task
            except asyncio.CancelledError:
                pass
        await self.offloader.aclose()


async def serve(host: str, port: int, handler, *, burst: int = 64,
                max_workers: int = 4, max_in_flight: int = 8, timeout: float = 5.0,
                lag_interval_ms: float = 5.0) -> GuardedServer:
    """Start the server. ``handler`` is a blocking callable taking and returning bytes.

    The handler runs on the pool, never on the loop: that is why a handler that sleeps for a
    second does not delay the next connection's accept. Each reply is written before the
    connection is closed, and ``drain`` runs first so a client cannot read a partial line.
    """
    offloader = Offloader(max_workers=max_workers, max_in_flight=max_in_flight, timeout=timeout)
    monitor = LagMonitor(interval_ms=lag_interval_ms) if lag_interval_ms > 0 else None
    guarded = GuardedServer(offloader, monitor, burst)

    async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
        guarded.connections += 1
        try:
            try:
                line = await reader.readline()
            except ValueError:
                # The stream's limit is MAX_LINE, passed to ``start_server`` below, so a
                # request longer than that is refused here: ``readline`` raises before any
                # length check in this function could see the line. Both paths answer the
                # same word, which is what the client is told.
                guarded.errors += 1
                writer.write(b"error\n")
                await writer.drain()
                return
            if not line:
                return
            try:
                answer = await offloader.run(handler, line.strip())
            except Overloaded:
                guarded.busy += 1
                reply = b"busy\n"
            except asyncio.TimeoutError:
                guarded.timeouts += 1
                reply = b"timeout\n"
            except Exception:                       # noqa: BLE001 - reported as a line
                guarded.errors += 1
                reply = b"error\n"
            else:
                guarded.served += 1
                reply = answer if answer.endswith(b"\n") else answer + b"\n"
            writer.write(reply)
            await writer.drain()
        finally:
            writer.close()
            try:
                await writer.wait_closed()
            except (ConnectionError, OSError):
                pass

    guarded.server = await asyncio.start_server(handle, host, port,
                                                backlog=backlog_for(burst), limit=MAX_LINE)
    if monitor is not None:
        guarded.monitor_task = asyncio.create_task(monitor.run())
    return guarded
The log line and the two-clock diagnosis: report.py
"""The log line, and which of the two clocks is slow.

Two numbers separate the failure modes a client reports as "the server is slow":

``connect``  - time to complete the handshake. The kernel does this without the loop, so a
               connect that takes hundreds of milliseconds points at the accept queue, not
               at Python;
``first byte`` - time from the request to the reply. Once the connection exists, this is the
               loop's own lateness: the accept queue cannot help, because there is nothing
               left for the kernel to do.

The verdict is not a diagnosis of the code - it says which graph to open first.
"""
from __future__ import annotations

from dataclasses import dataclass

QUEUE = "queue"
LOOP = "loop"
CLEAN = "clean"

# A connect this slow cannot be explained by the loop: the kernel completes the handshake
# without it, and on loopback a handshake costs microseconds. This is a **baseline for
# loopback**, not a universal constant: on a real network the healthy connect is the round
# trip, so pass the deployment's own figure - a few times the connect p99 it sees when
# nothing is wrong - as ``queue_floor_ms``. It is set below the one second at which Linux
# first retransmits a SYN, so that on loopback it marks the line where the queue, and not
# the client's retry timer, is the graph to open first.
QUEUE_FLOOR_MS = 100.0


@dataclass(frozen=True)
class Verdict:
    """What one pair of client-side clocks says about the server."""

    verdict: str
    reason: str
    connect_ms: float
    first_byte_ms: float
    lag_p95_ms: float


def first_clock(connect_ms: float, first_byte_ms: float, lag_p95_ms: float = 0.0,
                queue_floor_ms: float = QUEUE_FLOOR_MS) -> str:
    """Which clock is slow: the queue's, the loop's, or neither.

    The queue is named first: a full queue also delays the first byte, so a rule that looked
    for latency first would send an operator with a full queue off to profile handlers. This
    is the decision on its own; ``diagnose`` is the same decision with the sentence each
    verdict prints beside it.
    """
    if connect_ms >= queue_floor_ms:
        return QUEUE
    if first_byte_ms >= max(queue_floor_ms, lag_p95_ms * 2):
        return LOOP
    return CLEAN


def diagnose(connect_ms: float, first_byte_ms: float, lag_p95_ms: float = 0.0,
             queue_floor_ms: float = QUEUE_FLOOR_MS) -> Verdict:
    """Name the bottleneck behind one connection's two clocks, with the reason to log.

    ``queue_floor_ms`` is the one number here that belongs to a deployment rather than to
    this package. Its default is a loopback baseline: a handshake on the measuring host
    costs tens of microseconds, so a hundred milliseconds cannot be the kernel's own work.
    Across a network the healthy connect is a round trip - tens of milliseconds - where the
    default would name the queue for every connection; pass the floor that deployment has.
    """
    clock = first_clock(connect_ms, first_byte_ms, lag_p95_ms, queue_floor_ms)
    if clock == QUEUE:
        return Verdict(QUEUE, ("the handshake took longer than the loop can explain: "
                               "the kernel completes it without the loop, so the accept "
                               "queue is the graph to open first"),
                       connect_ms, first_byte_ms, lag_p95_ms)
    if clock == LOOP:
        return Verdict(LOOP, ("the handshake was immediate and the first byte was not: "
                              "the loop was not running when the request arrived"),
                       connect_ms, first_byte_ms, lag_p95_ms)
    return Verdict(CLEAN, "both clocks are below the floor for either failure",
                   connect_ms, first_byte_ms, lag_p95_ms)


def summarize(snapshot: dict) -> str:
    """One line, in the shape a log aggregator can group and an operator can read.

    It prints what the server asked for against the kernel's ceiling, the pool's peak
    against its limit, and the loop's worst lag: the three numbers that decide which of the
    two clocks will move next.
    """
    pool = snapshot.get("pool", {})
    lag = snapshot.get("lag", {})
    asked = snapshot.get("backlog_asked", snapshot.get("backlog", 0))
    return (
        f"connections={snapshot.get('connections', 0)} "
        f"served={snapshot.get('served', 0)} busy={snapshot.get('busy', 0)} "
        f"timeout={snapshot.get('timeouts', 0)} error={snapshot.get('errors', 0)} "
        f"backlog={asked}/{snapshot.get('backlog_cap', 0)} "
        f"burst={snapshot.get('burst', 0)} "
        f"pool_peak={pool.get('peak_in_flight', 0)}/{pool.get('max_in_flight', 0)} "
        f"pool_rejected={pool.get('rejected', 0)} "
        f"lag_p95_ms={lag.get('p95_ms', 0)} lag_max_ms={lag.get('max_ms', 0)}"
    )
The test that makes a blocked loop visible: test_lag.py
"""Tests for the lag monitor: the sampling, the ring, and the one block it must catch."""
from __future__ import annotations

import asyncio
import time

import pytest

from acceptguard.lag import LagMonitor


def test_interval_must_be_positive() -> None:
    with pytest.raises(ValueError):
        LagMonitor(interval_ms=0)


def test_window_must_hold_at_least_one_sample() -> None:
    with pytest.raises(ValueError):
        LagMonitor(window=0)


def test_empty_snapshot_reports_zero_samples() -> None:
    snapshot = LagMonitor().snapshot()
    assert snapshot == {"n": 0, "p50_ms": 0.0, "p95_ms": 0.0, "max_ms": 0.0, "late": 0}


def test_empty_monitor_never_exceeds_a_budget() -> None:
    assert LagMonitor().exceeds(1.0) is False


def test_monitor_samples_until_the_stop_event() -> None:
    async def scenario() -> LagMonitor:
        monitor = LagMonitor(interval_ms=2)
        stop = asyncio.Event()
        task = asyncio.create_task(monitor.run(stop))
        await asyncio.sleep(0.05)
        stop.set()
        await task
        return monitor

    monitor = asyncio.run(scenario())
    assert monitor.started >= 3
    assert monitor.stopped is True
    assert len(monitor.samples) == monitor.started


def test_snapshot_order_is_consistent() -> None:
    async def scenario() -> dict:
        monitor = LagMonitor(interval_ms=1)
        stop = asyncio.Event()
        task = asyncio.create_task(monitor.run(stop))
        await asyncio.sleep(0.03)
        stop.set()
        await task
        return monitor.snapshot()

    snapshot = asyncio.run(scenario())
    assert snapshot["p50_ms"] <= snapshot["p95_ms"] <= snapshot["max_ms"]


def test_the_ring_keeps_only_the_window() -> None:
    monitor = LagMonitor(interval_ms=1, window=5)
    for value in range(20):
        monitor.samples.append(float(value))
    assert len(monitor.samples) == 5
    assert monitor.snapshot()["n"] == 5


def test_a_blocked_loop_is_visible_in_the_samples() -> None:
    async def scenario() -> float:
        monitor = LagMonitor(interval_ms=5)
        task = asyncio.create_task(monitor.run())
        await asyncio.sleep(0.02)
        time.sleep(0.05)
        await asyncio.sleep(0.02)
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
        return monitor.snapshot()["max_ms"]

    assert asyncio.run(scenario()) >= 30.0


def test_a_cancelled_monitor_still_reports_that_it_stopped() -> None:
    async def scenario() -> bool:
        monitor = LagMonitor(interval_ms=5)
        task = asyncio.create_task(monitor.run())
        await asyncio.sleep(0.02)
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
        return monitor.stopped

    assert asyncio.run(scenario()) is True


def test_exceeds_fires_above_the_budget() -> None:
    monitor = LagMonitor(interval_ms=5)
    monitor.samples.append(1.0)
    monitor.samples.append(80.0)
    assert monitor.exceeds(50.0) is True
    assert monitor.exceeds(200.0) is False


def test_late_counts_samples_over_twice_the_interval() -> None:
    monitor = LagMonitor(interval_ms=5)
    monitor.samples.extend([1.0, 4.0, 11.0, 40.0])
    assert monitor.snapshot()["late"] == 2

Take the next step


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.