getaddrinfo Stalls: 56 ms Loop Freezes, 33 ms Search Paths, 6 Threads

Dark neon cover: lookup bars for 9.4 ms with no search path, 17.5 ms for one domain, 24.2 ms for two and 33 ms for three, beside the 56 ms an event loop stops for when eight lookups block it and the 255.5 ms six cancelled lookups still cost the next caller, with 6 executor threads, 64 threads collapsing to 1 query and 140.1 ms of lookups becoming 46 µs of cache hits

1. A lookup that costs 7 ms, and a request that costs 56

A name resolution looks free next to the query it precedes. On this host one call to getaddrinfo for a name with no search path costs 6.8 ms – 1,170 times less than the 8,000 ms a resolver file of this shape allows a failing lookup to spend (section 2). The cost is not the average; it is the multipliers a deployment stacks on it without counting: a search path that turns one lookup into four, a request path that resolves the same name on every call, an event loop that stops while libc works, and an executor whose size nobody chose.

Each multiplier below was measured on one two-CPU Linux host, one at a time, with 1.1.1.1 and 1.0.0.1 in /etc/resolv.conf and no search domain of its own; every arm ran 5 times and kept its median and range. One host and five runs rank mechanisms, not populations. Table 1 is the denominator: one lookup, by name and family.

CallMedianRangeAddressesFamilies
getaddrinfo("example.com", 443)6.8 ms6.5 ms – 7.4 ms4inet, inet, inet6, inet6
getaddrinfo("techbobby.com", 443)7.5 ms6.6 ms – 56.9 ms4inet, inet, inet6, inet6
same name, AF_INET only6.1 ms5.9 ms – 6.5 ms2inet
same name, AF_INET6 only6.3 ms6.2 ms – 7.9 ms2inet6
a name that does not exist8.4 ms7.7 ms – 9.2 ms0none
Table 1: one getaddrinfo call, 5 runs per row, median and range. A refusal is not free: an NXDOMAIN is answered in 8.4 ms, a little more than a name that exists, because the refusal also travels. The widest range here – one answer of 56.9 ms for techbobby.com inside five runs – is a single slow resolver answer, which is why every argument below quotes the median and prints the range beside it.

Two details matter later. The order of the answer: libc returned IPv4 before IPv6 here, and a connect loop walks the list in that order, which is what section 9 prices. And a failure costs what a success costs: an NXDOMAIN is a round trip with a shorter answer.

TL;DR – the four multipliers, measured

  • The search path. The same unqualified name costs 9.4 ms with no search domain and 33 ms with three: 23.5 ms more per lookup.
  • No cache. 20 lookups of one name cost 140.1 ms; the same 20 through a TTL cache cost 46 µs and 1 query, where the uncached arm issued 20 per batch.
  • The blocked loop. Eight lookups called directly inside a coroutine stop the event loop for 56 ms; the same eight awaited through loop.getaddrinfo leave the loop’s worst gap at 1 ms for the same total time.
  • The pool behind it. loop.getaddrinfo runs libc on a default executor of 6 threads here, so 24 concurrent lookups take four waves and 48 take eight – while six cancelled lookups still cost the next caller 255.5 ms.

Production SRE Note: Every figure below is loaded from the probe output that produced it, and each table prints its range beside the median. The 6.8 ms baseline is this host’s distance to its resolver: a pod beside its CoreDNS answers in a fraction of that, and pays the same multipliers.

2. What getaddrinfo does with a name

Python has no DNS client. socket.getaddrinfo is a thin wrapper around libc’s stub resolver, and everything expensive happens on the other side of that call. The stub resolver reads /etc/resolv.conf once per process, decides which names to try, in which order, how long to wait and how many times to repeat, then hands back a list of addresses and nothing else: no TTL, no server name, no query count. Time is what is left to measure.

The file on this host is short enough to quote as conditions. nameserver lines name 1.1.1.1 and 1.0.0.1, there is no search line, and options timeout:2 attempts:2 sets the rest. Those directives decide how many queries a name becomes and how long a bad minute lasts.

ConditionThis hostWhat it decides
nameserver1.1.1.1 and 1.0.0.1how many servers are tried, in order, before a lookup fails
searchnonewhich domains an unqualified name is expanded into
ndots1how many dots a name needs before it is tried absolutely first
timeout2 show long one server is waited on before the next is tried
attempts2how many rounds of the server list are made before giving up
glibcglibc 2.41the resolver whose behaviour this page measured
Python3.12.16the wrapper and its executor
Table 2: the resolver conditions this host ran under, parsed from its own /etc/resolv.conf. The search path was varied per child process, not by editing this file, so the table describes every number below except the rows filed under another search path.

The directives compose. ndots sets the dot count at which a name is tried absolutely first; below it, the name is expanded with each search domain and asked absolutely last. timeout and attempts compose into the worst case one call can spend, and the man page’s limits belong beside that arithmetic:

The resolver’s ceiling: what the directives add up to, and what the man page refuses to promise

resolv.conf(5) defines timeout:n as the wait before retrying a query “via a different name server”, default 5 seconds and capped at 30; attempts:n as “the number of times the resolver will send a query to its name servers before giving up”, default 2 and capped at 5. A nameserver list holds up to 3 entries. Multiplying what this host configures – 2 s, 2 attempts, 1.1.1.1 and 1.0.0.1 servers – gives 8,000 ms: 1,170 times the healthy lookup in table 1.

That product is a ceiling, not a schedule. The man page warns that the timeout “may not be the total time taken by any resolver API call”, because glibc applies its own caps and a slow answer is not a lost one. Measuring it needs a nameserver that blackholes queries, and this host’s two answer, so the ceiling is documentation arithmetic, printed apart from every measurement.

The Kubernetes case matters because it is the one most readers meet. A pod’s generated /etc/resolv.conf carries one nameserver, three search domains and options ndots:5 – the Kubernetes documentation prints exactly that file. At five dots, api.example.com with two is expanded against every search domain before the absolute query, so a name that looks fully qualified costs four queries. The multiplier in section 3 is the default, not a misconfiguration.

3. The search path: four queries for one name

To measure the search path without editing a system file, each configuration runs in its own child interpreter: glibc reads the resolver configuration once per process, so two arms in one process would measure the first arm twice, and LOCALDOMAIN sets the search path per process in place of the file’s search line. Each arm resolves the same unqualified name five times, in fresh interpreters.

"""One getaddrinfo call, measured, plus the resolver conditions it ran under.

libc's stub resolver is not a DNS client you can instrument from Python: ``getaddrinfo``
returns addresses and nothing else. No TTL, no server that answered, no query count, no
retry count. What it does leave behind is the time the call took, and that is the number
every runbook built on it starts from.

``parse_resolv_conf`` exists because the time only makes sense beside the conditions: a
lookup of an unqualified name costs one round trip in a file with ``ndots:1`` and no search
domains, and four in a Kubernetes pod with ``ndots:5`` and three of them.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class Conditions:
    """The resolver settings that decide how many queries one lookup becomes."""

    nameservers: tuple[str, ...] = ()
    search: tuple[str, ...] = ()
    ndots: int = 1
    timeout_s: float = 5.0
    attempts: int = 2

    @property
    def search_attempts(self) -> int:
        """How many queries a single-label name costs: one per search domain, plus itself.

        The final absolute query is issued whether or not a search domain answered, unless
        one of them resolved, so this is the ceiling rather than the count on every path.
        """
        return len(self.search) + 1

The conditions object carries the search list and the dot threshold together, because neither answers alone: a name’s price is the number of domains it is expanded into, and that number exists only relative to ndots. search_attempts prints the ceiling for a single-label name – one query per domain, plus the absolute query asked last.

ConfigurationNameQueries (ceiling)MedianRange
no search domainapi19.4 ms9.2 ms – 128.8 ms
one domainapi217.5 ms17.2 ms – 18.4 ms
two domainsapi324.2 ms21.9 ms – 145.9 ms
three domainsapi433 ms29.5 ms – 34.6 ms
three domains, ndots:5api.example.com435.9 ms30.2 ms – 41 ms
no domain, ndots:5api.example.com18.3 ms7.2 ms – 9.9 ms
Table 3: one lookup, 5 runs per row, a child process per arm. Each search domain that does not answer adds a query and a round trip: 7.8 ms per domain here. The last row is the Kubernetes shape, where a dotted name meets a five-dot threshold and pays 27.6 ms more than the same name without a search path (4.34×). The 128.8 ms maximum in the first row is one slow resolver answer among five; the medians are what the argument uses.
The arithmetic behind the per-domain cost

The medians climb in steps of one query: 9.4 ms with one query, 17.5 ms with two, 24.2 ms with three and 33 ms with four. The increments are not identical – the resolver’s scheduling, the two-server list and the client’s spare threads all move a millisecond – but their average, 7.8 ms, is one round trip to the resolver, which is what an NXDOMAIN from a search domain costs.

Two consequences are operational. The failures are sequential: glibc tries the domains in order and cannot know that none will answer, so a wrong namespace is paid in full on every lookup, in every process, until the configuration changes. And a name that resolves through the last domain still pays the queries before it. The man page warns that the process “may be slow and will generate a lot of network traffic if the servers for the listed domains are not local”.

Three levers remove the multiplier, and they are not interchangeable. Fewer domains: a namespace-scoped search path is cheaper than three inherited ones. Qualified names: a trailing dot makes a name absolute, so it is tried once. A lower ndots, so a dotted name goes absolute first – the lever Kubernetes exposes as dnsConfig.options. None helps a name that needs the search path.

4. There is no cache, and no negative cache either

The stub resolver resolves; it does not remember. Every call issues the queries its configuration implies, even when the same process asked for the same name a millisecond earlier, and a refusal is not remembered either. Whether something in front of libc caches – nscd, systemd-resolved, a node-local cache – is a property of the host; none runs here, and the query counts below say so.

Arm20 lookupsPer callQueries reaching libc
getaddrinfo, name exists140.1 ms6.9 ms20 per batch, 100 over the 5 batches
getaddrinfo, name does not exist143.5 ms6.9 ms20 per batch, one per refusal
socket.gethostbyname, name exists127.9 ms6.3 ms20 per batch
through the TTL cache, name exists46 µs2 µs1
through the TTL cache, name does not exist45 µs2 µs1
Table 4: 20 lookups per batch, 5 batches per arm, median of the batch totals and of every individual call. The cache’s line is three orders of magnitude cheaper per call (0.03% of the lookup) and issues 1 query where the uncached arms issue one per call.

The batch total is the honest unit, because the first call pays the lookup and the rest pay a dictionary read: 140.1 ms against 46 µs for the same 20 calls. What the cache buys is not only latency but 20 queries per request-shaped batch that your resolver never receives – and a resolver that rate-limits its clients prices those in refusals, not milliseconds.

The negative row is the one worth copying. A service that looks up a dead name on every request pays a round trip per request for the same refusal, and the DNS operator pays the query. A short negative TTL turns that into one refusal per TTL; the package keeps negative and positive TTLs separate because the two are wrong at different lengths.

from __future__ import annotations
import time
def resolve(self, host: str, port: int = 443) -> Answer:
    key = (host.lower().rstrip("."), port)
    started = time.perf_counter()
    now = self._clock()
    stale_record: Record | None = None
    with self._lock:
        record = self._records.get(key)
        if record is not None and now < record.expires_at:
            self._bump("hits")
            return self._answer(key, record, "cache", started)
        if record is not None and self.stale_s and now < record.expires_at + self.stale_s:
            self._bump("stale")
            stale_record = record
            flight = None
        else:
            flight = self._flights.get(key)
            leader = flight is None
            if leader:
                flight = _Flight()
                self._flights[key] = flight
            else:
                self._bump("shared")
                self._bump("misses")
    if stale_record is not None:
        # The refresh starts outside the lock: it takes the same lock to record its
        # result, and a refresher that runs the work inline would otherwise deadlock.
        self._start_refresh(key)
        return self._answer(key, stale_record, "stale", started)
    assert flight is not None
    if not leader:
        # Bounded: a leader that never returns must not keep the waiters it collected.
        # The leader pops the flight, so a waiter that gives up removes nothing.
        if not flight.event.wait(self.wait_timeout_s):
            self._bump("wait_timeouts")
            raise ResolutionError(
                key[0], f"the leader did not answer within {self.wait_timeout_s:g} s")
        if flight.error is not None:
            # The leader's own exception, unchanged: a waiter should be told what went
            # wrong by libc, not that some other thread was cancelled.
            raise flight.error
        if flight.record is None:
            raise ResolutionError(key[0], "the leader finished without an answer")
        return self._answer(key, flight.record, "shared", started)
    self._bump("misses")
    try:
        record = self._fetch(key)
    except BaseException as exc:
        with self._lock:
            self._flights.pop(key, None)
        flight.error = exc
        flight.event.set()
        raise
    with self._lock:
        self._flights.pop(key, None)
    flight.record = record                     # published before the event opens
    flight.event.set()
    return self._answer(key, record, "network", started)

The method is the whole policy in one place. A live entry returns without the lock being dropped; an expired entry inside its stale window is served while one refresh starts; a miss either becomes the leader or waits on its event, so the name is asked once however many threads arrive together. A leader that raises publishes the exception, not its record, so a waiter never mistakes a failed lookup for a thread that gave up.

5. The event loop stops while libc works

A blocking call inside a coroutine does not yield. The loop is one thread with a queue of callbacks, so a coroutine that calls socket.getaddrinfo directly stops every other task – timers, reads, writes, keepalives – for as long as libc takes. The instrument is a heartbeat: a task that asks to wake every five milliseconds and records how long it actually slept. Its gaps are the loop’s latency.

"""Probe 04: what a blocking lookup does to everything else on the loop.

The instrument is a heartbeat: a task that wakes every five milliseconds and records how
long it actually slept. Its gaps are the loop's own latency, and a blocking call inside a
coroutine shows up there as one gap the length of the call. The two arms differ only in who
does the resolving - ``socket.getaddrinfo`` on the loop's thread, or the same call in the
loop's default executor through ``loop.getaddrinfo``.
"""
from __future__ import annotations
import asyncio
import socket
import time
import probe
async def heartbeat(stop: asyncio.Event, gaps: list[float], interval: float = 0.005) -> None:
    """Wake every ``interval`` seconds and record how long the sleep really took."""
    last = asyncio.get_running_loop().time()
    while not stop.is_set():
        await asyncio.sleep(interval)
        now = asyncio.get_running_loop().time()
        gaps.append((now - last - interval) * 1000)
        last = now

async def measure(blocking: bool, count: int) -> dict:
    """Run ``count`` lookups on one arm and describe the loop's gaps and the call times."""
    loop = asyncio.get_running_loop()
    stop = asyncio.Event()
    gaps: list[float] = []
    task = asyncio.create_task(heartbeat(stop, gaps))
    await asyncio.sleep(0.03)
    calls: list[float] = []
    started = time.perf_counter()
    for _ in range(count):
        single = time.perf_counter()
        if blocking:
            socket.getaddrinfo("example.com", 443, type=socket.SOCK_STREAM)
        else:
            await loop.getaddrinfo("example.com", 443, type=socket.SOCK_STREAM)
        calls.append((time.perf_counter() - single) * 1000)
    total = (time.perf_counter() - started) * 1000
    await asyncio.sleep(0.03)
    stop.set()
    await task
    return {"gap_ms": probe.stats(gaps, keep=False),
            "max_gap_ms": probe.stats([max(gaps)] * 1, keep=False)["median"],
            "calls_ms": probe.stats(calls, keep=False),
            "total_ms": total,
            "count": count}

The probe runs three arms, five times each: one blocking lookup, eight blocking lookups in a row, and the same eight awaited through loop.getaddrinfo, which hands libc to the loop’s default executor. The table prints the worst gap in each run, the median of those worst gaps, and the total time the arm spent.

ArmWorst loop gapTotal timePer lookupWhere libc ran
one blocking lookup7.8 ms7.7 ms7.7 msloop thread
eight blocking lookups56 ms55.7 ms6.8 msloop thread
eight awaited through the loop1 ms57.3 ms7 msexecutor thread
Table 5: the loop’s worst gap per arm, 5 runs per arm, median printed. The blocking arm stops the loop for the sum of its calls – 55.993 ms against 1.037 ms, 54.0× the executor arm’s gap – and finishes in the same time: 97% of it. The ratio divides the medians, not the rounded cells: 56 ms against 1 ms would read as 56. The cost of the blocking form is not the lookup; it is everything else that did not run.

Read the last column against the first row: the same eight calls cost about the same wall time either way. What changes is who waits. In the blocking arm a timer, a socket read or another request’s response waited 56 ms; in the executor arm the worst wait was 1 ms, the heartbeat’s own interval plus scheduling noise. That is the argument for await loop.getaddrinfo(...): it does not make resolution asynchronous, it moves the block to a thread allowed to block.

What Python actually does when you await loop.getaddrinfo

The method is four lines of CPython. In 3.12’s base_events.py it picks socket.getaddrinfo, then returns await self.run_in_executor(None, getaddr_func, host, port, family, type, proto, flags). None means the loop’s default executor; the asyncio documentation says that default is “lazy-initialized” and is a concurrent.futures.ThreadPoolExecutor. The call is scheduled, not implemented: section 6 follows from the executor’s size, section 7 from the fact that a thread cannot be cancelled.

6. Six threads are the resolver’s real concurrency limit

The default executor is sized min(32, os.cpu_count() + 4). On a two-CPU host that is 6 threads, a number chosen for general blocking work, not for name resolution. Twenty-four concurrent lookups are therefore four waves that queue behind each other whether the resolver is fast or slow. The probe prices the queue twice: once with the host’s real lookups, once with a 25 ms stub that replaces libc’s work with a constant so the arithmetic is exact.

ArmConcurrent lookupsWall timePer callWaves
real lookups2432.3 ms17 ms4
stub, one lookup132.4 ms32.3 ms1
stub, six lookups633 ms31.8 ms1
stub, 24 lookups24129.3 ms79.4 ms4
stub, 48 lookups48259.3 ms143.3 ms8
Table 6: 5 runs per arm, median printed; the stub sleeps 25 ms and then calls the real resolver, so one lookup costs 32.4 ms and one wave of six costs 33 ms. The queue is linear in ceil(count / 6): the pool is not the resolver’s limit but the loop’s.

The real arm shows the same shape with less waiting: 24 concurrent lookups finished in 32.3 ms, 4.7× the price of one lookup, which is what four waves of a short task look like. The reading is not “raise the pool”: that moves the queue into the resolver – 48 simultaneous queries to a resolver that accepts four at a time is twelve waves there instead of eight here.

A class that bounds its own lookups has to decide one thing the executor does not: which moment returns the permit. The obvious shape – async with self.slots: await wait_for(loop.getaddrinfo(...)) – returns it when wait_for gives up, not when libc does: the timeout cancels the await, the thread keeps running, and the semaphore reports a free slot while its thread is busy. Six timeouts against six threads and the semaphore says six permits are available while the executor has none: the queue the bound was meant to prevent, now invisible.

The package ties the permit to the executor future and to one deadline: it starts the deadline, waits for a permit inside it, starts the lookup, attaches a done callback that returns the permit, then waits with what is left on a shielded future. The callback decides when the slot is free; the deadline decides what the caller gets, and it covers the wait for a permit as well as the wait for the thread. A call that cannot get a permit in time fails without taking one, and that failure is not cached, because it says nothing about the name. parked counts the permits an abandoned call still holds.

from __future__ import annotations
import asyncio
import socket
import time
from .cache import Record, ResolutionError
from .resolve import Address
async def _fetch(self, key: tuple[str, int]) -> Record:
    host, port = key
    started = time.perf_counter()
    slots = self.slots
    # One deadline for the whole call. The wait for a permit is a wait the caller
    # agreed to, so it spends the same budget: a pile of parked slots must not turn
    # the call into one that never returns.
    deadline = self.loop.time() + self.timeout_s
    remaining = max(0.0, deadline - self.loop.time())
    try:
        await asyncio.wait_for(slots.acquire(), timeout=remaining)
    except asyncio.TimeoutError:
        # No permit was taken, so nothing is owed back, and nothing is cached: the
        # name is fine and the next call that finds a slot should look it up.
        self.stats.failures += 1
        raise ResolutionError(
            host, f"timeout after {self.timeout_s:g} s waiting for a slot") from None
    self.stats.upstream += 1
    try:
        future = self.loop.run_in_executor(None, self._lookup, host, port)
    except BaseException:
        slots.release()
        raise
    finished = False

    def release(_future: asyncio.Future) -> None:
        """Give the permit back when the thread ends, whichever caller is still there.

        Tied to the executor future instead of the ``try`` block because the future
        outlives a timeout or a cancellation: the caller has gone, the thread has not.
        """
        nonlocal finished
        if finished:
            return
        finished = True
        self._abandoned.discard(_future)
        slots.release()

    future.add_done_callback(release)
    try:
        infos = await asyncio.wait_for(asyncio.shield(future),
                                       timeout=max(0.0, deadline - self.loop.time()))
    except asyncio.TimeoutError:
        self._note_abandoned(future, finished)
        self.stats.failures += 1
        record = Record((), f"timeout after {self.timeout_s:g} s",
                        self.loop.time() + self.negative_ttl_s, is_error=True)
        self._entries[key] = record
        raise ResolutionError(host, record.detail) from None
    except socket.gaierror as exc:
        self.stats.failures += 1
        record = Record((), f"{exc.errno}: {exc.strerror}",
                        self.loop.time() + self.negative_ttl_s, is_error=True)
        self._entries[key] = record
        raise ResolutionError(host, record.detail) from None
    except BaseException:
        # A cancelled caller leaves exactly the thread a timed-out one leaves, so it is
        # counted the same way; the permit is the callback's to return, not this block's.
        self._note_abandoned(future, finished)
        raise
    addresses = tuple(Address(info[0], info[4]) for info in infos)
    elapsed_note = f"{(time.perf_counter() - started) * 1000:.1f} ms in libc"
    record = Record(addresses, elapsed_note, self.loop.time() + self.ttl_s)
    self._entries[key] = record
    self._prune()
    return record
"""The async resolver: one flight per name, a timeout that caches, a bounded pool.

The loop is real (``asyncio.run``) and so is the executor; only the lookup is replaced, and
it blocks on purpose. The permit semantics are only interesting when a thread actually
outlives its caller, so the tests hold a thread open instead of pretending to.
"""
from __future__ import annotations
import asyncio
import os
import socket
import threading
import time
import pytest
from dnsguard import AsyncResolver, ResolutionError
from dnsguard.asyncr import DEFAULT_CONCURRENCY
def run(coro):
    return asyncio.run(coro)

def test_a_timeout_keeps_its_permit_until_the_thread_returns():
    """The defect this design exists to prevent: a timeout must not free the slot."""
    release = threading.Event()

    def stalled(host: str, port: int) -> list:
        release.wait(2.0)
        return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("203.0.113.9", port))]

    async def scenario():
        resolver = AsyncResolver(loop=asyncio.get_running_loop(), ttl_s=30, timeout_s=0.3,
                                 negative_ttl_s=5, concurrency=1, lookup=stalled)
        with pytest.raises(ResolutionError):
            await resolver.resolve("stalled.example.com")
        parked = resolver.parked
        follow_up = asyncio.create_task(resolver.resolve("other.example.com"))
        await asyncio.sleep(0.05)
        queued_while_parked = not follow_up.done()
        release.set()
        answer = await asyncio.wait_for(follow_up, timeout=2.0)
        return parked, queued_while_parked, resolver.parked, answer

    parked, queued, after, answer = run(scenario())
    assert parked == 1
    assert queued is True
    assert after == 0
    assert answer.source == "network"

def test_a_call_fails_its_deadline_when_every_slot_is_parked():
    """The hole the deadline closes: a queue of parked permits must not wait forever."""
    release = threading.Event()

    def stalled(host: str, port: int) -> list:
        release.wait(2.0)
        return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("203.0.113.7", port))]

    async def scenario():
        resolver = AsyncResolver(loop=asyncio.get_running_loop(), ttl_s=30, timeout_s=0.05,
                                 negative_ttl_s=5, concurrency=1, lookup=stalled)
        with pytest.raises(ResolutionError):
            await resolver.resolve("stalled.example.com")
        parked = resolver.parked
        started = time.perf_counter()
        with pytest.raises(ResolutionError) as caught:
            await resolver.resolve("other.example.com")
        waited = time.perf_counter() - started
        release.set()
        for _ in range(200):
            if resolver.parked == 0:
                break
            await asyncio.sleep(0.01)
        return parked, waited, caught.value, resolver.parked

    parked, waited, error, after = run(scenario())
    assert parked == 1
    assert waited < 0.5
    assert "waiting for a slot" in error.detail
    assert error.cached is False
    assert after == 0

def test_the_default_concurrency_stays_below_the_executor():
    """A default above the pool would queue in the executor and call it a bound."""
    workers = min(32, (os.cpu_count() or 1) + 4)
    resolver = AsyncResolver()
    assert resolver.concurrency == DEFAULT_CONCURRENCY
    assert DEFAULT_CONCURRENCY == 4
    assert DEFAULT_CONCURRENCY < workers

The tests are the specification. With one permit and one stalled lookup, a second name does not enter libc until the first thread returns: the parked count is one while the caller has already been failed, zero once the thread is done. With that permit parked, a call for a different name returns on its own deadline instead of waiting for the slot, and the refused name is not cached. Against the async with shape the second lookup enters while the only thread is inside libc.

The default concurrency is 4, not the executor’s 6: a bound above the pool does not bound the pool, it only stops the class from noticing the queue, and one stalled name parks every thread instead of four of six. The test pins both – DEFAULT_CONCURRENCY == 4 and DEFAULT_CONCURRENCY < workers – and the second is the one that keeps the default below min(32, cpu_count + 4) whatever the host.

Production SRE Note: A slow resolver does not produce a slow log line; it produces a slow queue. If the lookup p90 is 6.8 ms and the request p90 is an order of magnitude higher, the time is in the wait for a free thread, not in the query: export the calls in flight against the executor’s size before you touch the timeout.

7. Cancelling a lookup cancels the wait, not the thread

Every timeout on a lookup is a cancellation of the await, and the await is not where the work is. The coroutine returns at once, while the executor thread is inside libc with no channel to hear about the cancellation. The query finishes, the thread is free afterwards, and until then it is occupied by a request nobody wants.

The probe fills the pool with six slow lookups, cancels all six, and then times the next caller. The stub sleeps 300 ms per lookup so the held time is a constant; the control arm asks the same question of an idle pool.

  • The cancel itself returned in 0.11 ms: asyncio is as responsive as it claims to be, and the caller is told the lookup was abandoned.
  • The next caller waited 563.4 ms instead of 307.9 ms – 255.5 ms more, which is 83% of an ordinary lookup’s own wait and very nearly the part of the stub the cancelled threads had left to run.
  • The pool still had 6 worker threads after the cancellations – none was killed, because threads are not killable in Python and libc has no cancellation point to return from – and the queue the next caller met is what shows they were still busy.

This is why a timeout is not a fix. A deployment that wraps lookups in “wait two seconds and move on” has decided that every stalling name may hold a thread for two seconds after the request that wanted it returned a 504. With a pool of 6, that is 6 requests’ worth of queue built out of discarded work, and it looks like a resolver outage in the logs.

The class answers at two levels. The permit is returned by the thread rather than the caller, so stalled names park at most concurrency threads and the rest of the pool serves other names; and a timeout becomes a negative cache entry, so the next caller reads the failure instead of queueing. The leader owns the flight its waiters are parked on, so it removes it and fails that future before re-raising – for every failure, not only cancellation – and waiters await it through asyncio.shield, because a bare await lets one waiter’s cancellation cancel the future the others hold.

Production SRE Note: Put the timeout where the work is bounded, not where the request is. A permit held until the thread returns means one stalled name parks one slot, and four distinct stalled names hold all four permits – while callers of each name read a cached failure after its first one. Without it each stalled name retires a thread for good, and the number that would show it – threads inside libc – is never exported.

8. What a cache can know, and what it cannot

A DNS cache has to answer a question its interface does not ask. The record’s TTL belongs to the answer the resolver received; getaddrinfo returns addresses, not records, so the TTL is gone before Python sees anything. Whatever TTL a Python cache honours is a number you chose, and it is a trade: too long and a failover takes that long to reach the process, too short and every expiry is a stampede.

The stampede is the failure a naive cache adds rather than removes. The instant a popular name expires, every thread that asks finds no entry and each issues its own query. The probe starts 64 threads against one name: 64 queries without a cache, 1 with a cache that single-flights, and 63 of the 64 callers answered from the leader’s result.

ArmWall timeQueries to libcAnswers by source
no cache, 64 threads19.8 ms64network: 64
TTL cache with single flight16.3 ms1network: 1, shared: 63
TTL cache on a name that fails15.1 ms1failures: 64, all from the negative entry
expired entry, served stale9 ms2stale: 64, refreshes: 1
model: resolver accepting four at a time926.8 ms64network: 64
model with the cache68.1 ms1network: 1, shared: 63
1000 cache hits2.0 µs per call0cache
Table 7: 64 callers released together, 5 runs per arm, median printed. The wall time barely moves in the first two rows, because 64 queries to a resolver a round trip away are answered in parallel; what changes is the query count, the part a resolver sees. The two model arms – the fifth and sixth rows, a resolver that accepts four queries at a time and answers in 50 ms – are not a measurement of this host’s resolver, and there the cache is 13.6× faster.

The stale row served every caller from the expired entry while one background refresh ran: 64 stale answers, 1 refresh, 2 queries in total. The row above it is the same cache on a name that does not exist, where the negative entry keeps 64 failures from becoming as many queries.

"""A TTL cache in front of getaddrinfo, with one lookup per name in flight.

Two facts shape it.

The first is that ``getaddrinfo`` never tells you the DNS TTL. libc resolves, filters by
``AI_ADDRCONFIG``, sorts by RFC 3484, and hands back addresses; the record's TTL died in
the stub resolver. So the TTL this cache honours is one you choose, and choosing it is a
trade: too long and a DNS failover takes that long to reach your process, too short and you
are back to paying a round trip per expiry. The page's measurements price both sides.

The second is that a cache without single flight moves a stampede instead of absorbing it.
At the moment a popular name expires, every thread that asks finds no entry and each one
issues its own query; the cache has made the problem worse by synchronising them. So the
first thread to miss becomes the leader, the rest wait on one event, and the answer they
all receive is the leader's.

``stale_s`` adds a third state: an expired entry that is still served while one background
lookup replaces it. A request that would otherwise wait for the network gets an address
that was correct a moment ago, which is what you want for a name whose records rarely
change and whose resolution occasionally stalls.

A waiter's patience is bounded too: the leader may be inside libc, where nothing cancels
it, so ``wait_timeout_s`` stops a waiter from waiting for as long as the leader does.
"""
from __future__ import annotations
import threading
from dataclasses import dataclass, field
from .resolve import Address
@dataclass
class Record:
    """One cached answer. An error is a record too, so a dead name cannot be re-asked."""

    addresses: tuple[Address, ...]
    detail: str
    expires_at: float
    is_error: bool = False

@dataclass
class _Flight:
    """The leader's promise to the threads that arrived while it was resolving.

    Either ``record`` or ``error`` is filled in by the leader before ``event`` is set, so a
    waiter that wakes always has something to read: the answer, or the exception the leader
    itself raised.
    """

    event: threading.Event = field(default_factory=threading.Event)
    record: Record | None = None
    error: BaseException | None = None

The record keeps an error as an answer: empty addresses, a detail string, a shorter expiry. That is the difference between a negative cache and a cache, and it names a decision worth making – a failing name is the one your process asks for most.

The refresh path is where stale serving stays honest. It takes the flight before returning, so the 64 callers that arrive during a refresh do not each start one, and the refresh runs outside the lock, which it needs to record its result. A refresh that fails leaves the expired entry in place until the stale window ends – the behaviour you want when the resolver is what is broken – and a refresher that cannot start releases the flight so the next stale hit tries again.

Waiting is the other place a flight holds a thread: a caller behind a leader that is inside libc inherits that leader’s wait, and nothing cancels libc. wait_timeout_s bounds the wait at thirty-five seconds, and that number is taken from the worst ceiling the resolver file in section 2 can hand one leader rather than from a single query: three search domains expand a name into its four queries, each allowed an eight-second ceiling, so a leader can lawfully sit inside libc for thirty-two seconds before it answers. Thirty-five clears that one bound; a shorter default would cut off a leader that is slow rather than stuck, which is the failure this page prices everywhere else. A waiter that reaches the bound raises ResolutionError; the flight stays the leader’s to clear, so a waiter that gives up removes nothing. test_a_waiter_leaves_when_the_leader_stalls puts one caller behind a stalled leader with the bound cut to 0.1 s: it leaves in about that time, the flight count is zero once the leader returns, and the default itself is checked against the four-query ceiling. That test is not printed here: like the rest of its suite it stays in the test suite only, and this page quotes its name and what it pins.

What the cache cannot do bounds the claim. It cannot see the record’s TTL, so a name with a thirty-second TTL and one with a day are cached for the same configured period; it cannot see a failover before that period ends, or which resolver answered; and it is per process, so four gunicorn workers hold four caches of one name. Nor does it grow without bound: an entry is pruned once past its expiry and its stale window.

9. The connect walk: two addresses, two timeouts

The lookup returns a list and something must dial it. socket.create_connection walks that list in order and gives each address the socket timeout before moving on – the documentation says the timeout “will set the timeout on the socket instance before attempting to connect”, and the instance is created per attempt. Two addresses that blackhole therefore cost twice the timeout, measured here with TEST-NET-1 and TEST-NET-2.

  • create_connection("example.com", 443) took 11.8 ms against 5.7 ms for the first IPv4 address alone: 6.2 ms spent walking an order the resolver chose, not a cost the name imposed.
  • The IPv6 address in that same answer could not be dialled here at all – this host reports “[Errno 97] Address family not supported by protocol” – so the first family in the list was the only one that could connect.
  • Two blackholed addresses with a 500 ms timeout cost 500.9 ms under one shared deadline and 1,002 ms with 2.00× the budget each, the second exactly twice the first.
  • AI_ADDRCONFIG dropped the answer from 4 addresses to 2 (50%) on this host, because it has no configured IPv6 address: the flag removes exactly the addresses that could not connect.
"""Dial the addresses getaddrinfo returned, under one deadline instead of one per address.

``socket.create_connection`` gives every address the whole timeout. That is right for a
single host on a good network and wrong for a name with four addresses: an IPv6 address
that blackholes and an IPv4 address that answers cost the timeout first, and a request
budget of two seconds can be spent before the first byte of the second address is sent.

This module walks the same list with a shared deadline, records every attempt, and lets the
caller see which address was actually used - the three facts a "connection timed out"
ticket never carries.
"""
from __future__ import annotations
import time
from .resolve import Address
def budget(remaining_s: float, timeout_s: float, per_address: bool) -> float:
    """How long the next address may take.

    ``per_address`` reproduces ``socket.create_connection``: the full timeout for each
    address. Otherwise the address gets what is left of the call's own budget, and an
    address that arrives after the deadline gets nothing.
    """
    if per_address:
        return timeout_s
    return max(0.0, min(timeout_s, remaining_s))

def connect(addresses: tuple[Address, ...] | list[Address], port: int, *,
            timeout_s: float = 5.0, per_address: bool = False,
            connector=None) -> Connection:
    """Try each address in order until one connects or the budget is spent."""
    deadline = time.monotonic() + timeout_s
    attempts: list[Attempt] = []
    opener = connector or _open
    for address in addresses:
        left = budget(deadline - time.monotonic(), timeout_s, per_address)
        if left <= 0:
            break
        started = time.monotonic()
        try:
            sock = opener(address, port, left)
        except OSError as exc:
            attempts.append(Attempt(address.host, address.family_name, False,
                                    (time.monotonic() - started) * 1000, str(exc)))
            continue
        attempts.append(Attempt(address.host, address.family_name, True,
                                (time.monotonic() - started) * 1000))
        return Connection(sock, attempts)
    return Connection(None, attempts)

The walk returns its attempts rather than a boolean, which is the difference between a ticket that says “connection timed out” and one that says which address was tried, for how long and with what error. The shared deadline is a policy: a name with four addresses and a two-second budget should spend two seconds, not eight.

Happy Eyeballs is the other half of this section, named but not solved. RFC 8305 starts the next address after a short delay instead of waiting for the previous one to fail, and the asyncio documentation gives that delay as 250 ms. Python exposes it as happy_eyeballs_delay on asyncio.open_connection and loop.create_connection. The sequential walk was measured because it is what most code does; the parallel one changes the constant, not the reason.

10. One line per resolution, and what it must carry

Every incident here has the same shape in a log: a request that took a long time and no statement about why. A resolver that logs only failures cannot tell a cache hit from a wait on a stalled query, and that difference is the diagnosis. The line carries four facts: the name and port, the address count, which layer answered, and how long it took.

"""One line per resolution, for the log you will actually read at 03:00.

The line carries the four things an incident needs a resolution to report:
the name, how many addresses came back, which layer answered, and how long it took. A
resolver that logs only failures cannot tell a 12 ms request path from a 0.02 ms one, and
the difference between those two is the whole incident.
"""
from __future__ import annotations

from .cache import Answer


def _elapsed(milliseconds: float) -> str:
    """The elapsed time at the resolution it deserves: a cache hit is not 0.00 ms.

    Two decimals of a millisecond turn a 3 µs hit and a 30 µs hit into the same string, and
    the ratio to a 7 ms lookup, which is the whole argument for the line, is lost.
    """
    if milliseconds < 0.1:
        microseconds = f"{milliseconds * 1000:.1f}"
        return (microseconds[:-2] if microseconds.endswith(".0") else microseconds) + " µs"
    return f"{milliseconds:.2f} ms"


def line(answer: Answer) -> str:
    """Render one answer as a single log line, without a trailing newline."""
    ttl = f"{answer.expires_in_s:.0f} s"
    return (f"dns {answer.host}:{answer.port} {len(answer.addresses)} addresses from "
            f"{answer.source} in {_elapsed(answer.elapsed_ms)} (ttl {ttl})")


def detail(answer: Answer) -> str:
    """The same answer with every address, in the order a connect loop would try them."""
    hosts = ", ".join(f"{address.host} ({address.family_name})" for address in answer.addresses)
    return f"{line(answer)}: {hosts}"

The probe prints the line for each path, on a real name, from the same process that resolved it – four paths, four lines:

  • network: dns example.com:443 4 addresses from network in 7.69 ms (ttl 30 s)
  • cache: dns example.com:443 4 addresses from cache in 0.8 µs (ttl 30 s)
  • stale, served while it refreshes: dns example.com:443 4 addresses from stale in 0.28 ms (ttl 0 s)
  • failure: no-such-name.invalid: -2: Name or service not known

The network line and the cache line under it are the same question answered two ways, and a hit prints in microseconds rather than hundredths of a millisecond, because 0.00 ms is what a hit and a rounding error look like together. A dashboard that plots the line’s time by source shows the cache working before anyone argues about it. An entry near its TTL that never refreshes is a refresh failing quietly, a different incident from a slow resolver.

The address list is deliberately left out: four addresses per request is a log that costs more than the lookup it describes. detail() prints them when something is wrong, in the order a connect loop would try them – the fact a family-order bug needs.

FieldWhy it is on the lineWhat it catches
name and portthe key the cache usesa service resolving the wrong host
address countthe answer’s shapean AI_ADDRCONFIG change, a family disappearing
sourcewhich layer answereda cache that never hits, a stale window that never refreshes
elapsedwhat the caller paidqueueing behind the executor
ttlwhat is left of the entrya refresh that keeps failing
Table 8: the five fields of the line, and the failure each one makes visible without a second query.

11. The deploy checklist: five changes, in order

The measurements support five changes, and their order matters because each one makes the next cheaper to verify. None needs a new dependency: the package in the appendix is standard library only, and the smallest version of the policy is a dictionary with an expiry and a lock.

  1. Take the blocking call out of the request path. If a handler calls socket.getaddrinfo, socket.create_connection or a client library that does, every such call stops the loop for its full duration (table 5). Await loop.getaddrinfo, or resolve once at startup and renew in the background.
  2. Put a cache in front of the resolver, with a TTL you chose. The TTL is a policy, not a default: it is how long a failover may take to reach your process, and the only knob you have, because libc does not expose the record’s own. Table 4 prices a batch of lookups with and without one.
  3. Make the cache single flight. Without it one expiry becomes a burst of simultaneous queries – the stampede the cache was meant to absorb (table 7).
  4. Bound the concurrency and the deadline. A permit per lookup, returned when the thread returns, and one deadline for the whole call rather than one per address (section 9): a shared deadline halves the cost of two blackholed addresses.
  5. Log the line, including the source and the time. Without it the first four changes are unverifiable: a cache you cannot see hitting is a cache you will eventually remove for not helping.

The order is not arbitrary. Moving the call off the request path without a cache leaves the queue in place, only politer; adding a cache without single flight moves the stampede one level down; and bounding concurrency without a deadline turns a slow resolver into a queue with no upper bound on the request’s wait.

Two changes that look obvious are not on the list. Lowering timeout is not a fix: it shortens the resolver’s ceiling, but every abandoned lookup still holds its thread, and section 7 priced that at 255.5 ms for the next caller. Turning off ndots helps unqualified names and does nothing for the qualified ones service discovery uses.

Production SRE Note: A resolver change is a config change, and a config change needs a number before and after. Take the four measurements in this order – lookup, batch of 20, worst loop gap, executor occupancy – and the next deploy either moves them or did not do what it claimed.

12. What this page did not measure

The numbers are sharper than their scope. Everything measured ran on one Linux host with glibc 2.41, Python 3.12.16, 1.1.1.1 and 1.0.0.1 public resolvers and no search domain in its own file; the search path was varied per child process, and the model arms are labelled as models. Each arm ran 5 times: the spread inside an arm is in the ranges, the spread between hosts is not measured. Four things are therefore absent.

  • A second host, or a second day. 5 repetitions on one machine give a median and a range, not a distribution: resolver latency moves with the network, the day and the resolver’s load, and another host would move every figure in table 1. The mechanisms – four queries for a dotted name, four waves for twenty-four lookups – follow from the rules; the milliseconds do not.
  • The resolver’s own timeout path. Measuring 8,000 ms needs a nameserver that blackholes queries. This host’s resolvers answer, so the ceiling is the arithmetic of the documented directives, not a stopwatch reading, and the rate-limiting arm of table 7 (13.6×) is a model that accepts four queries at a time and answers in 50 ms – no real resolver’s policy is that number or that shape.
  • Host-level caches and other libcs. nscd, systemd-resolved and a node-local DNS cache change the query count the resolver sees, and none ran here; and every statement about ndots, attempts and the search path is glibc’s behaviour, which musl reads differently.
  • An IPv6 address that answers, or one that blackholes. This host has no configured IPv6 address, so the IPv6 answers in table 1 were resolved but could not be dialled ([Errno 97] Address family not supported by protocol), and the cost of walking one that blackholes is in no table here. The family order in table 1 is therefore this host’s answer, not a rule: with a routable IPv6 address or a different resolver the IPv6 address can come first, and section 9’s walk pays for that order instead. The Happy Eyeballs race is named from RFC 8305 and the asyncio documentation, not measured here.

What to measure next is the same list in the other direction. In the deployment, print the pod’s /etc/resolv.conf at startup – the search path and ndots explain a 3.49× multiplier nobody chose (33 ms against 9.4 ms in table 3). Count the queries: a tcpdump on port 53 for a minute shows whether single flight works, because a working one shows one query per name per TTL.

The policy argued for here fits in one sentence, whether you write it in a runbook or in code: keep the blocking call off the request path, cache each name with a TTL you can defend, make that cache single flight, and log which layer answered. The code in the appendix is one implementation of that sentence.

Sources: the documentation quoted on this page

The resolver directives – ndots, timeout, attempts, the nameserver limit and the search-list limits – are quoted from resolv.conf(5) at man7.org. The address ordering rule, the AI_ADDRCONFIG semantics and the EAI_AGAIN description come from getaddrinfo(3). The executor’s default, min(32, os.cpu_count() + 4), is from the Python concurrent.futures documentation; the per-attempt timeout sentence is from the socket documentation; the 250 ms connection-attempt delay is RFC 8305 as quoted by the asyncio documentation; and the pod’s default ndots:5 and three search domains are from the Kubernetes “DNS for Services and Pods” page.

Frequently asked questions

Why does one lookup cost 7 ms when my request takes seconds?

Because the lookup is not the only term. 20 lookups of one name cost 140.1 ms here, a name with three search domains costs 33 ms per lookup instead of 9.4 ms, and a caller waiting for a free executor thread pays the queue too. The single lookup is the smallest term, and the request path adds the rest.

Is loop.getaddrinfo asynchronous?

No. It awaits run_in_executor(None, socket.getaddrinfo, ...), so libc runs on a default-executor thread – 6 of them here – and the loop stays responsive only because the block happens there. That is why 24 concurrent lookups take four waves (table 6) and why a cancelled task leaves its thread running (section 7).

Where does “Temporary failure in name resolution” come from?

From EAI_AGAIN, which getaddrinfo(3) describes as “The name server returned a temporary failure indication. Try again later.” Python raises it as socket.gaierror with errno -3. It is what a resolver produces when its retries are exhausted, so the ceiling it hit is the one in section 2: 2 s times 2 attempts times 1.1.1.1 and 1.0.0.1 servers is 8,000 ms of waiting.

Does Python cache DNS results?

Not in the standard library. getaddrinfo goes to libc every time, and libc has no cache, so 20 lookups issue 20 queries (table 4). A cache is something you add, and the TTL and the single flight are then yours to choose: neither is a library default.

How do I choose a TTL when getaddrinfo never returns one?

You choose it from the trade, because the record’s TTL does not survive the call. The upper bound is how long a failover may take to reach the process; the lower bound is the query rate the resolver accepts. The two ends here are 46 µs for 20 calls behind a cache and 140.1 ms for the same 20 with none.

Why do 64 threads cause 64 queries even with a cache?

Because they arrive at the same instant and the entry expires once. The first caller finds nothing and becomes the leader; the other 63 wait on its result rather than each asking. That is single flight, and without it table 7’s cached row would read 64 queries instead of 1.

Why does cancelling a lookup not free the thread?

Because the thread is inside libc, which has no cancellation point. The coroutine is cancelled in 0.11 ms and the query keeps running; with six cancelled lookups the next caller waited 255.5 ms longer than on an idle pool. A timeout alone leaves that work in the pool; only a permit the thread returns keeps the count honest.

How do I see the search path and ndots of a running pod?

Read the file the process reads: cat /etc/resolv.conf inside the container. A Kubernetes pod shows one nameserver, three search domains and options ndots:5 by default, which is why a name with two dots pays 27.6 ms here instead of the 8.3 ms an absolute name pays.

TechBobby Engineering writes measured infrastructure runbooks: one failure, its probes, and the code that survives it. Every figure came from one Linux host. The appendix carries the package’s five modules, the shared probe plumbing and the probe behind table 7, each printed whole; status.py is printed whole in section 10.

Appendix: the code this article ran

Seven files are printed whole below, in the order a reader would run them: the package’s five modules, the shared probe plumbing, and the probe behind table 7. status.py is printed whole in section 10. No line of those files is elided. Not reproduced here are the one-off probe scripts behind the other tables and the test suite: those are bench tools. Section 6 prints the async regression tests this page’s design rests on; the cache test section 8 names is in the same suite. No file is linked from an external repository.

The conditions, the address and the one measured call resolve.py
"""One getaddrinfo call, measured, plus the resolver conditions it ran under.

libc's stub resolver is not a DNS client you can instrument from Python: ``getaddrinfo``
returns addresses and nothing else. No TTL, no server that answered, no query count, no
retry count. What it does leave behind is the time the call took, and that is the number
every runbook built on it starts from.

``parse_resolv_conf`` exists because the time only makes sense beside the conditions: a
lookup of an unqualified name costs one round trip in a file with ``ndots:1`` and no search
domains, and four in a Kubernetes pod with ``ndots:5`` and three of them.
"""
from __future__ import annotations

import socket
import time
from dataclasses import dataclass, field

FAMILY_NAMES = {socket.AF_INET: "inet", socket.AF_INET6: "inet6"}


@dataclass(frozen=True)
class Address:
    """One address getaddrinfo answered with, kept in the order libc returned it."""

    family: int
    sockaddr: tuple

    @property
    def host(self) -> str:
        return self.sockaddr[0]

    @property
    def family_name(self) -> str:
        return FAMILY_NAMES.get(self.family, f"family {self.family}")


@dataclass(frozen=True)
class Conditions:
    """The resolver settings that decide how many queries one lookup becomes."""

    nameservers: tuple[str, ...] = ()
    search: tuple[str, ...] = ()
    ndots: int = 1
    timeout_s: float = 5.0
    attempts: int = 2

    @property
    def search_attempts(self) -> int:
        """How many queries a single-label name costs: one per search domain, plus itself.

        The final absolute query is issued whether or not a search domain answered, unless
        one of them resolved, so this is the ceiling rather than the count on every path.
        """
        return len(self.search) + 1


@dataclass
class Lookup:
    """The result of one ``Resolver.resolve`` call."""

    host: str
    port: int
    elapsed_ms: float
    addresses: tuple[Address, ...] = ()
    error: str = ""

    @property
    def ok(self) -> bool:
        return not self.error

    @property
    def families(self) -> tuple[str, ...]:
        return tuple(address.family_name for address in self.addresses)


def parse_resolv_conf(text: str) -> Conditions:
    """Read the directives libc honours, in the order of their first appearance.

    Any run of whitespace separates a keyword from its arguments, because the file is
    whitespace-separated rather than space-separated and a tab is as legal as a space.
    ``domain`` is accepted as the one-domain spelling of ``search``; where both appear, the
    one libc reads last - the later directive in the file - is the list in force.

    ``LOCALDOMAIN`` and ``RES_OPTIONS`` override the file for the calling process, which is
    how the probes vary the search path without editing a system file; the
    parser takes the effective text instead of trying to model the overrides.
    """
    nameservers: list[str] = []
    search: list[str] = []
    ndots = 1
    timeout = 5.0
    attempts = 2
    for raw in text.splitlines():
        line_text = raw.split("#", 1)[0].split(";", 1)[0].strip()
        if not line_text:
            continue
        fields = line_text.split()
        key, arguments = fields[0], fields[1:]
        if key == "nameserver" and arguments:
            nameservers.append(arguments[0])
        elif key in ("search", "domain"):
            search = arguments
        elif key == "options":
            for option in arguments:
                name, _, value = option.partition(":")
                if name == "ndots" and value.isdigit():
                    ndots = int(value)
                elif name == "timeout" and value.replace(".", "", 1).isdigit():
                    timeout = float(value)
                elif name == "attempts" and value.isdigit():
                    attempts = int(value)
    return Conditions(tuple(nameservers), tuple(search), ndots, timeout, attempts)


class Resolver:
    """``socket.getaddrinfo`` with the elapsed time and the answers kept together.

    ``family`` is what the caller asks for. ``AF_UNSPEC`` returns the order libc chose,
    which is the order every ``connect`` loop then walks, one failed address at a time.
    """

    def __init__(self, family: int = socket.AF_UNSPEC,
                 socktype: int = socket.SOCK_STREAM) -> None:
        self.family = family
        self.socktype = socktype
        self.calls = 0
        self.total_ms = 0.0

    def resolve(self, host: str, port: int = 443) -> Lookup:
        started = time.perf_counter()
        self.calls += 1
        try:
            infos = socket.getaddrinfo(host, port, self.family, self.socktype)
        except socket.gaierror as exc:
            elapsed = (time.perf_counter() - started) * 1000
            self.total_ms += elapsed
            return Lookup(host, port, elapsed, (), f"{exc.errno}: {exc.strerror}")
        elapsed = (time.perf_counter() - started) * 1000
        self.total_ms += elapsed
        addresses = tuple(Address(info[0], info[4]) for info in infos)
        return Lookup(host, port, elapsed, addresses)


@dataclass
class Counter:
    """A tiny monotonic counter the probes use to count upstream lookups."""

    value: int = 0
    stamps: list[float] = field(default_factory=list)

    def bump(self) -> int:
        self.value += 1
        self.stamps.append(time.monotonic())
        return self.value
The TTL cache, the negative entry and the single flight cache.py
"""A TTL cache in front of getaddrinfo, with one lookup per name in flight.

Two facts shape it.

The first is that ``getaddrinfo`` never tells you the DNS TTL. libc resolves, filters by
``AI_ADDRCONFIG``, sorts by RFC 3484, and hands back addresses; the record's TTL died in
the stub resolver. So the TTL this cache honours is one you choose, and choosing it is a
trade: too long and a DNS failover takes that long to reach your process, too short and you
are back to paying a round trip per expiry. The page's measurements price both sides.

The second is that a cache without single flight moves a stampede instead of absorbing it.
At the moment a popular name expires, every thread that asks finds no entry and each one
issues its own query; the cache has made the problem worse by synchronising them. So the
first thread to miss becomes the leader, the rest wait on one event, and the answer they
all receive is the leader's.

``stale_s`` adds a third state: an expired entry that is still served while one background
lookup replaces it. A request that would otherwise wait for the network gets an address
that was correct a moment ago, which is what you want for a name whose records rarely
change and whose resolution occasionally stalls.

A waiter's patience is bounded too: the leader may be inside libc, where nothing cancels
it, so ``wait_timeout_s`` stops a waiter from waiting for as long as the leader does.
"""
from __future__ import annotations

import threading
import time
from dataclasses import dataclass, field
from typing import Callable

from .resolve import Address, Lookup, Resolver


class ResolutionError(RuntimeError):
    """A lookup that failed, whether now or out of the negative cache."""

    def __init__(self, host: str, detail: str, *, cached: bool = False) -> None:
        self.host = host
        self.detail = detail
        self.cached = cached
        super().__init__(f"{host}: {detail}" + (" (cached failure)" if cached else ""))


@dataclass(frozen=True)
class Answer:
    """What a caller gets: addresses, where they came from, and what it cost."""

    host: str
    port: int
    addresses: tuple[Address, ...]
    source: str
    elapsed_ms: float
    expires_in_s: float

    @property
    def families(self) -> tuple[str, ...]:
        return tuple(address.family_name for address in self.addresses)


@dataclass
class Stats:
    """Counters the probes read: how much work reached libc, and how much did not."""

    hits: int = 0
    misses: int = 0
    shared: int = 0
    stale: int = 0
    upstream: int = 0
    failures: int = 0
    refreshes: int = 0
    refresh_errors: int = 0
    wait_timeouts: int = 0

    def as_dict(self) -> dict[str, int]:
        return {"hits": self.hits, "misses": self.misses, "shared": self.shared,
                "stale": self.stale, "upstream": self.upstream,
                "failures": self.failures, "refreshes": self.refreshes,
                "refresh_errors": self.refresh_errors,
                "wait_timeouts": self.wait_timeouts}


@dataclass
class Record:
    """One cached answer. An error is a record too, so a dead name cannot be re-asked."""

    addresses: tuple[Address, ...]
    detail: str
    expires_at: float
    is_error: bool = False


@dataclass
class _Flight:
    """The leader's promise to the threads that arrived while it was resolving.

    Either ``record`` or ``error`` is filled in by the leader before ``event`` is set, so a
    waiter that wakes always has something to read: the answer, or the exception the leader
    itself raised.
    """

    event: threading.Event = field(default_factory=threading.Event)
    record: Record | None = None
    error: BaseException | None = None


def _thread_runner(work: Callable[[], None]) -> None:
    threading.Thread(target=work, name="dnsguard-refresh", daemon=True).start()


class CachedResolver:
    """Resolve through a TTL cache, a negative cache and a single flight per name.

    ``upstream`` is any callable ``(host, port) -> Lookup``; the default is a real
    getaddrinfo. ``clock`` is injectable so a test can expire an entry without sleeping,
    and ``refresher`` decides where a stale-while-revalidate lookup runs.
    ``wait_timeout_s`` bounds a shared caller's wait for the leader: thirty-five seconds is
    just past the worst ceiling a search path can hand one leader - four queries at eight
    seconds each - so a slow leader is never cut off and a stuck one holds no one.
    """

    def __init__(self, upstream: Callable[[str, int], Lookup] | None = None, *,
                 ttl_s: float = 30.0, negative_ttl_s: float = 5.0, stale_s: float = 0.0,
                 wait_timeout_s: float = 35.0,
                 clock: Callable[[], float] = time.monotonic,
                 refresher: Callable[[Callable[[], None]], None] = _thread_runner) -> None:
        self._upstream = upstream or Resolver().resolve
        self.ttl_s = ttl_s
        self.negative_ttl_s = negative_ttl_s
        self.stale_s = stale_s
        self.wait_timeout_s = wait_timeout_s
        self._clock = clock
        self._refresher = refresher
        # Re-entrant: a counter is bumped from inside the policy lock and outside it, and a
        # plain Lock would deadlock the moment those two paths met.
        self._lock = threading.RLock()
        self._records: dict[tuple[str, int], Record] = {}
        self._flights: dict[tuple[str, int], _Flight] = {}
        self.stats = Stats()

    def _bump(self, name: str, amount: int = 1) -> None:
        """Count one event under the lock, so a stampede cannot lose an increment."""
        with self._lock:
            setattr(self.stats, name, getattr(self.stats, name) + amount)

    def resolve(self, host: str, port: int = 443) -> Answer:
        key = (host.lower().rstrip("."), port)
        started = time.perf_counter()
        now = self._clock()
        stale_record: Record | None = None
        with self._lock:
            record = self._records.get(key)
            if record is not None and now < record.expires_at:
                self._bump("hits")
                return self._answer(key, record, "cache", started)
            if record is not None and self.stale_s and now < record.expires_at + self.stale_s:
                self._bump("stale")
                stale_record = record
                flight = None
            else:
                flight = self._flights.get(key)
                leader = flight is None
                if leader:
                    flight = _Flight()
                    self._flights[key] = flight
                else:
                    self._bump("shared")
                    self._bump("misses")
        if stale_record is not None:
            # The refresh starts outside the lock: it takes the same lock to record its
            # result, and a refresher that runs the work inline would otherwise deadlock.
            self._start_refresh(key)
            return self._answer(key, stale_record, "stale", started)
        assert flight is not None
        if not leader:
            # Bounded: a leader that never returns must not keep the waiters it collected.
            # The leader pops the flight, so a waiter that gives up removes nothing.
            if not flight.event.wait(self.wait_timeout_s):
                self._bump("wait_timeouts")
                raise ResolutionError(
                    key[0], f"the leader did not answer within {self.wait_timeout_s:g} s")
            if flight.error is not None:
                # The leader's own exception, unchanged: a waiter should be told what went
                # wrong by libc, not that some other thread was cancelled.
                raise flight.error
            if flight.record is None:
                raise ResolutionError(key[0], "the leader finished without an answer")
            return self._answer(key, flight.record, "shared", started)
        self._bump("misses")
        try:
            record = self._fetch(key)
        except BaseException as exc:
            with self._lock:
                self._flights.pop(key, None)
            flight.error = exc
            flight.event.set()
            raise
        with self._lock:
            self._flights.pop(key, None)
        flight.record = record                     # published before the event opens
        flight.event.set()
        return self._answer(key, record, "network", started)

    def _fetch(self, key: tuple[str, int]) -> Record:
        host, port = key
        self._bump("upstream")
        lookup = self._upstream(host, port)
        now = self._clock()
        if lookup.ok:
            record = Record(lookup.addresses, "", now + self.ttl_s)
        else:
            self._bump("failures")
            record = Record((), lookup.error, now + self.negative_ttl_s, is_error=True)
        with self._lock:
            self._records[key] = record
        self.prune()
        return record

    def _start_refresh(self, key: tuple[str, int]) -> None:
        """Hand one stale hit the job of replacing the entry; every other hit just reads it."""
        with self._lock:
            if key in self._flights:
                return
            self._flights[key] = _Flight()
        self._bump("refreshes")

        def work() -> None:
            try:
                self._fetch(key)
            except Exception:                                  # noqa: BLE001 - background
                pass
            finally:
                with self._lock:
                    flight = self._flights.pop(key, None)
                if flight is not None:
                    flight.event.set()

        try:
            self._refresher(work)
        except BaseException:
            # A pool that cannot take the job would otherwise leave the flight parked, and
            # every later miss on this name would wait for an event nobody can set.
            with self._lock:
                flight = self._flights.pop(key, None)
            if flight is not None:
                flight.event.set()
            self._bump("refresh_errors")

    def prune(self) -> int:
        """Drop entries that are past their expiry and past the stale window.

        Without this the dictionaries only ever grow: a process that resolves a name once
        and never again keeps that record for its whole lifetime, and a long-lived service
        with a churning set of names turns the cache into a leak.
        """
        now = self._clock()
        with self._lock:
            dead = [key for key, record in self._records.items()
                    if now >= record.expires_at + self.stale_s]
            for key in dead:
                del self._records[key]
        return len(dead)

    def _answer(self, key: tuple[str, int], record: Record, source: str,
                started: float) -> Answer:
        elapsed = (time.perf_counter() - started) * 1000
        if record.is_error:
            raise ResolutionError(key[0], record.detail, cached=source != "network")
        return Answer(key[0], key[1], record.addresses, source, elapsed,
                      max(0.0, record.expires_at - self._clock()))

    def wait_for_refreshes(self, timeout: float = 5.0) -> bool:
        """Block until no background refresh is running; the tests and probes use it."""
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            with self._lock:
                pending = [flight for flight in self._flights.values()]
            if not pending:
                return True
            for flight in pending:
                flight.event.wait(0.01)
        return False

    def cached_entries(self) -> int:
        with self._lock:
            return len(self._records)
The same policy on a loop, with a deadline and a permit the thread returns asyncr.py
"""The same policy on an event loop, where the blocking call is the whole problem.

``loop.getaddrinfo`` does not make resolution asynchronous. It hands the call to the
loop's default executor and waits for a thread, which means three things follow from
libc's behaviour and none of them from asyncio:

* the work happens on a thread of ``min(32, cpu_count + 4)``, so a burst of slow lookups
  queues behind however many that is on the host;
* cancelling the task cancels the *wait*, not the thread: the query is already in libc and
  runs to completion, holding its pool slot;
* a timeout you enforce with ``wait_for`` returns control to you but leaves the same thread
  busy, so a name that always stalls can retire the whole pool one abandoned lookup at a
  time.

So this class bounds concurrency with a semaphore whose permit is returned by the thread's
own completion rather than by the caller's timeout, spends one deadline on the wait for a
permit and on the lookup together, single-flights per name, and turns the timeout into a
cache entry rather than a thread leak. Everything it returns says where the answer came
from, because "resolved in 0.02 ms" and "resolved in 12 ms" mean different things on a
dashboard.
"""
from __future__ import annotations

import asyncio
import socket
import time
from typing import Callable

from .cache import Answer, Record, ResolutionError, Stats
from .resolve import Address

# Four is below the six worker threads a two-CPU host's default executor runs, so a stall
# parks at most four of them and leaves the rest of the service a thread of its own.
DEFAULT_CONCURRENCY = 4


def libc_lookup(host: str, port: int) -> list:
    """The blocking half: the one part of resolution Python cannot make asynchronous."""
    return socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)


class AsyncResolver:
    """A TTL cache and single flight for getaddrinfo, with bounded concurrency.

    ``concurrency`` defaults to four: fewer than the executor's threads on a small host,
    because a bound that is too generous does not remove the queue, it moves the queue into
    the resolver. ``lookup`` is injectable so a test can hold a thread open without libc.
    """

    def __init__(self, *, ttl_s: float = 30.0, negative_ttl_s: float = 5.0,
                 timeout_s: float = 2.0, concurrency: int | None = None,
                 lookup: Callable[[str, int], list] = libc_lookup,
                 loop: asyncio.AbstractEventLoop | None = None) -> None:
        self.ttl_s = ttl_s
        self.negative_ttl_s = negative_ttl_s
        self.timeout_s = timeout_s
        self.concurrency = DEFAULT_CONCURRENCY if concurrency is None else concurrency
        self._lookup = lookup
        self._loop = loop
        self._entries: dict[tuple[str, int], Record] = {}
        self._flights: dict[tuple[str, int], asyncio.Future] = {}
        self._slots: asyncio.Semaphore | None = None
        self._abandoned: set[asyncio.Future] = set()
        self.stats = Stats()

    @property
    def loop(self) -> asyncio.AbstractEventLoop:
        if self._loop is None:
            self._loop = asyncio.get_running_loop()
        return self._loop

    @property
    def slots(self) -> asyncio.Semaphore:
        if self._slots is None:
            self._slots = asyncio.Semaphore(self.concurrency)
        return self._slots

    @property
    def parked(self) -> int:
        """Permits still held by callers that already timed out or were cancelled."""
        return len(self._abandoned)

    async def resolve(self, host: str, port: int = 443) -> Answer:
        key = (host.lower().rstrip("."), port)
        started = time.perf_counter()
        record = self._entries.get(key)
        now = self.loop.time()
        if record is not None and now < record.expires_at:
            self.stats.hits += 1
            return self._answer(key, record, "cache", started)
        flight = self._flights.get(key)
        leader = flight is None
        if leader:
            flight = self.loop.create_future()
            self._flights[key] = flight
        else:
            self.stats.shared += 1
        self.stats.misses += 1
        assert flight is not None
        if not leader:
            # Shielded: one waiter giving up must not cancel the future the others share,
            # which is otherwise what awaiting a bare future does in asyncio.
            record = await asyncio.shield(flight)
            return self._answer(key, record, "shared", started)
        try:
            record = await self._fetch(key)
        except BaseException as exc:
            # Whatever went wrong belongs to the waiters too; a future left pending here
            # would make every one of them wait for a leader that has already finished.
            self._flights.pop(key, None)
            if not flight.done():
                flight.set_exception(exc if not isinstance(exc, asyncio.CancelledError)
                                     else ResolutionError(key[0], "the leader was cancelled"))
                flight.exception()                      # mark it retrieved for the waiters
            raise
        self._flights.pop(key, None)
        if not flight.done():
            flight.set_result(record)
        return self._answer(key, record, "network", started)

    async def _fetch(self, key: tuple[str, int]) -> Record:
        host, port = key
        started = time.perf_counter()
        slots = self.slots
        # One deadline for the whole call. The wait for a permit is a wait the caller
        # agreed to, so it spends the same budget: a pile of parked slots must not turn
        # the call into one that never returns.
        deadline = self.loop.time() + self.timeout_s
        remaining = max(0.0, deadline - self.loop.time())
        try:
            await asyncio.wait_for(slots.acquire(), timeout=remaining)
        except asyncio.TimeoutError:
            # No permit was taken, so nothing is owed back, and nothing is cached: the
            # name is fine and the next call that finds a slot should look it up.
            self.stats.failures += 1
            raise ResolutionError(
                host, f"timeout after {self.timeout_s:g} s waiting for a slot") from None
        self.stats.upstream += 1
        try:
            future = self.loop.run_in_executor(None, self._lookup, host, port)
        except BaseException:
            slots.release()
            raise
        finished = False

        def release(_future: asyncio.Future) -> None:
            """Give the permit back when the thread ends, whichever caller is still there.

            Tied to the executor future instead of the ``try`` block because the future
            outlives a timeout or a cancellation: the caller has gone, the thread has not.
            """
            nonlocal finished
            if finished:
                return
            finished = True
            self._abandoned.discard(_future)
            slots.release()

        future.add_done_callback(release)
        try:
            infos = await asyncio.wait_for(asyncio.shield(future),
                                           timeout=max(0.0, deadline - self.loop.time()))
        except asyncio.TimeoutError:
            self._note_abandoned(future, finished)
            self.stats.failures += 1
            record = Record((), f"timeout after {self.timeout_s:g} s",
                            self.loop.time() + self.negative_ttl_s, is_error=True)
            self._entries[key] = record
            raise ResolutionError(host, record.detail) from None
        except socket.gaierror as exc:
            self.stats.failures += 1
            record = Record((), f"{exc.errno}: {exc.strerror}",
                            self.loop.time() + self.negative_ttl_s, is_error=True)
            self._entries[key] = record
            raise ResolutionError(host, record.detail) from None
        except BaseException:
            # A cancelled caller leaves exactly the thread a timed-out one leaves, so it is
            # counted the same way; the permit is the callback's to return, not this block's.
            self._note_abandoned(future, finished)
            raise
        addresses = tuple(Address(info[0], info[4]) for info in infos)
        elapsed_note = f"{(time.perf_counter() - started) * 1000:.1f} ms in libc"
        record = Record(addresses, elapsed_note, self.loop.time() + self.ttl_s)
        self._entries[key] = record
        self._prune()
        return record

    def _note_abandoned(self, future: asyncio.Future, finished: bool) -> None:
        """Count a permit whose caller left while its thread is still inside libc."""
        if not finished:
            self._abandoned.add(future)

    def _prune(self) -> int:
        """Forget entries that have expired; the dictionary would otherwise only grow."""
        now = self.loop.time()
        dead = [key for key, record in self._entries.items() if now >= record.expires_at]
        for key in dead:
            del self._entries[key]
        return len(dead)

    def _answer(self, key: tuple[str, int], record: Record, source: str,
                started: float) -> Answer:
        elapsed = (time.perf_counter() - started) * 1000
        if record.is_error:
            raise ResolutionError(key[0], record.detail, cached=source != "network")
        return Answer(key[0], key[1], record.addresses, source, elapsed,
                      max(0.0, record.expires_at - self.loop.time()))
The connect walk with one deadline connect.py
"""Dial the addresses getaddrinfo returned, under one deadline instead of one per address.

``socket.create_connection`` gives every address the whole timeout. That is right for a
single host on a good network and wrong for a name with four addresses: an IPv6 address
that blackholes and an IPv4 address that answers cost the timeout first, and a request
budget of two seconds can be spent before the first byte of the second address is sent.

This module walks the same list with a shared deadline, records every attempt, and lets the
caller see which address was actually used - the three facts a "connection timed out"
ticket never carries.
"""
from __future__ import annotations

import socket
import time
from dataclasses import dataclass

from .resolve import Address


@dataclass(frozen=True)
class Attempt:
    """One address, the time it was given, and what happened."""

    host: str
    family: str
    ok: bool
    elapsed_ms: float
    error: str = ""


@dataclass
class Connection:
    """The socket that connected, or none, with every attempt that was made."""

    sock: socket.socket | None
    attempts: list[Attempt]

    @property
    def ok(self) -> bool:
        return self.sock is not None

    @property
    def elapsed_ms(self) -> float:
        return sum(attempt.elapsed_ms for attempt in self.attempts)

    @property
    def used(self) -> Attempt | None:
        return next((attempt for attempt in self.attempts if attempt.ok), None)


def budget(remaining_s: float, timeout_s: float, per_address: bool) -> float:
    """How long the next address may take.

    ``per_address`` reproduces ``socket.create_connection``: the full timeout for each
    address. Otherwise the address gets what is left of the call's own budget, and an
    address that arrives after the deadline gets nothing.
    """
    if per_address:
        return timeout_s
    return max(0.0, min(timeout_s, remaining_s))


def connect(addresses: tuple[Address, ...] | list[Address], port: int, *,
            timeout_s: float = 5.0, per_address: bool = False,
            connector=None) -> Connection:
    """Try each address in order until one connects or the budget is spent."""
    deadline = time.monotonic() + timeout_s
    attempts: list[Attempt] = []
    opener = connector or _open
    for address in addresses:
        left = budget(deadline - time.monotonic(), timeout_s, per_address)
        if left <= 0:
            break
        started = time.monotonic()
        try:
            sock = opener(address, port, left)
        except OSError as exc:
            attempts.append(Attempt(address.host, address.family_name, False,
                                    (time.monotonic() - started) * 1000, str(exc)))
            continue
        attempts.append(Attempt(address.host, address.family_name, True,
                                (time.monotonic() - started) * 1000))
        return Connection(sock, attempts)
    return Connection(None, attempts)


def _open(address: Address, port: int, timeout_s: float) -> socket.socket:
    sock = socket.socket(address.family, socket.SOCK_STREAM)
    sock.settimeout(timeout_s)
    try:
        sock.connect((address.host, port, *address.sockaddr[2:]))
    except OSError:
        sock.close()
        raise
    return sock
The package’s public names __init__.py
"""dnsguard: the four things a resolver needs that getaddrinfo does not give you.

Standard library only. The package is small on purpose: it wraps ``socket.getaddrinfo``
rather than speaking DNS, because the failure it exists for happens inside libc,
where the stub resolver lives - not in the wire format.

* :class:`dnsguard.Conditions` - what ``/etc/resolv.conf`` tells libc, parsed.
* :class:`dnsguard.Resolver` - one call, the addresses it returned, and how long it took.
* :class:`dnsguard.CachedResolver` - a TTL cache with one in-flight lookup per name.
* :class:`dnsguard.AsyncResolver` - the same policy for asyncio, where a blocking call
  stops every other task on that loop.
"""
from .asyncr import DEFAULT_CONCURRENCY, AsyncResolver
from .cache import Answer, CachedResolver, ResolutionError, Stats
from .connect import Attempt, Connection, connect
from .resolve import Address, Conditions, Lookup, Resolver, parse_resolv_conf
from .status import detail, line

__all__ = [
    "DEFAULT_CONCURRENCY",
    "Address",
    "Answer",
    "AsyncResolver",
    "Attempt",
    "CachedResolver",
    "Conditions",
    "Connection",
    "Lookup",
    "ResolutionError",
    "Resolver",
    "Stats",
    "connect",
    "detail",
    "line",
    "parse_resolv_conf",
]
Five repeats, a median with its range, one JSON file probe.py
"""Shared plumbing for the probes: five repeats, a median with its range, one JSON file.

Every number the article prints comes out of one of these files. The rule the probes keep
is that a run records what a call cost, never what it was expected to cost: an arm that
answers too fast to measure is reported with the resolution it had, and an arm that varies
is reported with its minimum and maximum beside the median.
"""
from __future__ import annotations

import json
import os
import pathlib
import platform
import socket
import statistics
import subprocess
import sys
import time

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
REPEATS = 5
MODULE = HERE.parent / "module"
sys.path.insert(0, str(MODULE))

import dnsguard  # noqa: E402  (the path above is what makes it importable)


def stats(values: list[float], keep: bool = True) -> dict:
    """Median, minimum and maximum, with the raw runs kept for the arms that are few."""
    described = {"median": round(statistics.median(values), 3),
                 "min": round(min(values), 3),
                 "max": round(max(values), 3)}
    if keep:
        described["runs"] = [round(value, 3) for value in values]
    return described


def timed(function, repeats: int = REPEATS) -> dict:
    """Call something ``repeats`` times and describe the time it took in milliseconds."""
    samples: list[float] = []
    for _ in range(repeats):
        started = time.perf_counter()
        function()
        samples.append((time.perf_counter() - started) * 1000)
    return stats(samples)


def host_facts() -> dict:
    """The conditions every measurement on this page ran under."""
    kernel = platform.release()
    glibc = ""
    try:
        glibc = " ".join(os.confstr("CS_GNU_LIBC_VERSION").split())
    except (ValueError, OSError):
        glibc = platform.libc_ver()[0] + " " + platform.libc_ver()[1]
    conf = pathlib.Path("/etc/resolv.conf")
    conditions = dnsguard.parse_resolv_conf(conf.read_text() if conf.exists() else "")
    server = conditions.nameservers[0] if conditions.nameservers else "127.0.0.1"
    return {
        "kernel": kernel,
        "glibc": glibc.strip(),
        "python": platform.python_version(),
        "cpu_count": os.cpu_count() or 1,
        "default_executor_threads": min(32, (os.cpu_count() or 1) + 4),
        "resolv_conf": str(conf),
        "nameservers": list(conditions.nameservers),
        "search": list(conditions.search),
        "ndots": conditions.ndots,
        "timeout_s": conditions.timeout_s,
        "attempts": conditions.attempts,
        "resolver": server,
    }


def write(name: str, payload: dict) -> dict:
    """Store one probe's record; a rerun replaces it rather than appending to it."""
    RESULTS.mkdir(exist_ok=True)
    payload = {"host": host_facts(), **payload}
    path = RESULTS / name
    path.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    print(f"{name}: {path}")
    return payload


def child_lookup_ms(host: str, env: dict[str, str] | None = None,
                    family: int = socket.AF_UNSPEC) -> dict:
    """Resolve ``host`` in a fresh interpreter, so libc re-reads its configuration.

    glibc reads the resolver configuration once per process, which is exactly why a search
    path cannot be varied inside the process that measures it: a child per condition is the
    only way the number belongs to the condition it is filed under.
    """
    code = (
        "import json,socket,time\n"
        f"t=time.perf_counter()\n"
        f"try:\n"
        f"    infos=socket.getaddrinfo({host!r},443,{family},socket.SOCK_STREAM)\n"
        f"    print(json.dumps({{'ms':(time.perf_counter()-t)*1000,'count':len(infos),"
        f"'families':[i[0] for i in infos]}}))\n"
        f"except OSError as exc:\n"
        f"    print(json.dumps({{'ms':(time.perf_counter()-t)*1000,'count':0,"
        f"'error':getattr(exc,'strerror',str(exc))}}))\n"
    )
    environ = {**os.environ, **(env or {})}
    result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
                            env=environ, timeout=120, check=True)
    return json.loads(result.stdout.strip().splitlines()[-1])
Sixty-four callers and the queries that reach libc 07_cache.py
"""Probe 07: a cache without single flight synchronises the stampede it was meant to absorb.

Sixty-four threads ask for the same name at the same moment. Without a cache each one
issues its own query. With a TTL cache but no single flight they still do - the entry is
empty for all of them at once - so the arms here are: no cache, a cache with one flight per
name, a cache serving stale while it refreshes, and the same cache on a name that fails.
"""
from __future__ import annotations

import threading
import time

import probe

dnsguard = probe.dnsguard
THREADS = 64
HOST = "example.com"


def stampede(resolver_factory, host: str = HOST) -> dict:
    """Start ``THREADS`` callers together and describe what reached libc."""
    resolver = resolver_factory()
    barrier = threading.Barrier(THREADS)
    answers: list[object] = []
    failures: list[Exception] = []
    started = time.perf_counter()

    def worker() -> None:
        barrier.wait()
        try:
            answers.append(resolver.resolve(host))
        except dnsguard.ResolutionError as exc:
            failures.append(exc)

    threads = [threading.Thread(target=worker) for _ in range(THREADS)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    wall = (time.perf_counter() - started) * 1000
    sources: dict[str, int] = {}
    for answer in answers:
        source = getattr(answer, "source", "network")
        sources[source] = sources.get(source, 0) + 1
    if hasattr(resolver, "wait_for_refreshes"):
        resolver.wait_for_refreshes(10)
    return {"wall_ms": wall, "sources": sources, "answers": len(answers),
            "failures": len(failures),
            "upstream": (resolver.stats.upstream if hasattr(resolver, "stats")
                         else getattr(resolver, "calls", THREADS))}


def repeat(factory, host: str = HOST) -> dict:
    runs = [stampede(factory, host) for _ in range(probe.REPEATS)]
    return {"wall_ms": probe.stats([run["wall_ms"] for run in runs]),
            "upstream": runs[-1]["upstream"],
            "sources": runs[-1]["sources"],
            "failures": runs[-1]["failures"]}


def hits(resolver: dnsguard.CachedResolver, count: int = 1000) -> dict:
    resolver.resolve(HOST)
    calls: list[float] = []
    for _ in range(count):
        started = time.perf_counter()
        resolver.resolve(HOST)
        calls.append((time.perf_counter() - started) * 1_000_000)
    return {"per_call_us": probe.stats(calls, keep=False)}


def stale_run() -> dict:
    resolver = dnsguard.CachedResolver(dnsguard.Resolver().resolve, ttl_s=0.01, stale_s=5)
    resolver.resolve(HOST)
    time.sleep(0.03)
    result = stampede(lambda: resolver)
    result["upstream"] = resolver.stats.upstream
    result["refreshes"] = resolver.stats.refreshes
    return result


class RateLimited:
    """An upstream that answers in a fixed time and refuses more than ``slots`` at once.

    This is a model of a resolver that rate-limits its clients, not a measurement of one.
    It is in the probe because the stampede's cost depends on it: sixty-four queries to a
    resolver that answers four at a time is sixteen waves of waiting, and one query is not.
    """

    def __init__(self, slots: int = 4, delay_s: float = 0.05) -> None:
        self.slots = threading.Semaphore(slots)
        self.delay = delay_s
        self.calls = 0
        self._lock = threading.Lock()

    def resolve(self, host: str, port: int = 443) -> object:
        with self._lock:
            self.calls += 1
        with self.slots:
            time.sleep(self.delay)
            return probe.dnsguard.Resolver().resolve(host, port)


def main() -> None:
    naive = repeat(lambda: dnsguard.Resolver())
    cached = repeat(lambda: dnsguard.CachedResolver(dnsguard.Resolver().resolve, ttl_s=30))
    negative = repeat(lambda: dnsguard.CachedResolver(dnsguard.Resolver().resolve,
                                                      ttl_s=30, negative_ttl_s=30),
                      host="no-such-name.invalid")
    naive_slow = repeat(lambda: RateLimited())
    cached_slow_upstream = RateLimited()
    cached_slow = repeat(lambda: dnsguard.CachedResolver(cached_slow_upstream.resolve, ttl_s=30))
    stale = [stale_run() for _ in range(probe.REPEATS)]
    cache_for_hits = dnsguard.CachedResolver(dnsguard.Resolver().resolve, ttl_s=300)
    hit = [hits(cache_for_hits) for _ in range(probe.REPEATS)]
    probe.write("07_cache.json", {
        "conditions": {"threads": THREADS, "repeats": probe.REPEATS, "hits": 1000,
                       "stale_ttl_s": 0.01, "stale_window_s": 5},
        "arms": {
            "naive": naive,
            "cached": cached,
            "negative": negative,
            "naive_slow": naive_slow,
            "cached_slow": cached_slow,
            "stale": {"wall_ms": probe.stats([run["wall_ms"] for run in stale]),
                      "sources": stale[-1]["sources"],
                      "upstream": stale[-1]["upstream"],
                      "refreshes": stale[-1]["refreshes"]},
            "hit": {"per_call_us": probe.stats([run["per_call_us"]["median"]
                                                for run in hit], keep=False)},
        },
    })


if __name__ == "__main__":
    main()

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.