DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python
DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python
Search
Ask the AI

DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python

DNS resolution may delay a request before HTTP begins. To diagnose that wait, check which resolver answered, whether its cached record was still valid, what the response header reported, and how those choices affected latency.

This article follows the RFC 1034/1035 model and uses four deterministic requests to calculate the latency value generated by the companion lab.

1. Resolution Paths And Cache State

A stub resolver normally asks a recursive resolver. On a cache miss, that resolver may traverse root, TLD, and authoritative knowledge before answering. On a cache hit, it may return a record while its TTL remains valid. A DNS response header still matters: transaction ID connects response to question, flags report state, and answer count says whether an answer is present.

DNS resolution latency timeline with TTL cache misses and hits
With a fixed 60-second TTL, requests one and three miss while requests two and four hit.

2. A Hand Calculation For TTL Latency

Set a miss to 42 ms, a hit to 1 ms, and issue requests at seconds [0, 10, 70, 80]. The entry populated at second zero expires before second seventy.

latencies = [42, 1, 42, 1] ms
average = (42 + 1 + 42 + 1) / 4 = 21.50 ms
hit_ratio = 2 / 4 = 50%

A longer TTL is not automatically correct: it reduces resolution work but lengthens the stale-address period during migrations or failover.

3. Runnable Experiment

Environment: Python 3.10+ and Matplotlib. No root access, external network, or live DNS target is required; the run reads a bundled scenario file.

cd network-fundamentals-lab
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python src/dns_resolution_cache.py
expiry = -1
for at_second in [0, 10, 70, 80]:
    hit = at_second < expiry
    latency = 1 if hit else 42
    if not hit:
        expiry = at_second + 60

The generated dns-cache-results.csv records request time, cache state, latency, and expiry for auditing.

4. Reading A Header In C

For diagnosis, an IP address alone hides failures. The lab’s C example decodes a fixed safe response header rather than sniffing real traffic:

cc -std=c11 -Wall -Wextra -O2 src/dns_packet_parser.c -o /tmp/dns_parser
/tmp/dns_parser
# txid=0x2a10 flags=0x8180 questions=1 answers=1

5. Animated Walkthrough

The animation separates the recursive miss path from the direct cache-hit path inside a live TTL window.

6. Engineering Checklist

  • Log the queried name, record type, resolver, TTL, RCODE, and latency rather than only the final address.
  • Coordinate lowered TTL windows with DNS migrations and rollback timing.
  • Distinguish application, operating-system, and recursive-resolver cache behavior.
  • Use dig example.com A +noall +answer +stats for observation only; its output is not the reproducible lab result.

Negative caching: the record is correct and still will not resolve

The calculations above concern the TTL of successful responses. Failures get cached too. This can prolong a debugging session.

An authoritative NXDOMAIN or NODATA response can carry an SOA record in its authority section for negative caching. RFC 2308 sets the negative TTL to the smaller of the SOA record’s own TTL and its minimum field. The original shorthand below is retained: its last field is MINIMUM, while +short omits the SOA record TTL, so that field alone does not determine the negative-cache duration.

dig SOA example.com +short
# ns1.example.com. admin.example.com. 2026080801 7200 3600 1209600 3600
#                                                                  ^^^^
#                                     this last field is the negative TTL (seconds)

A lookup before a record is created can cache NXDOMAIN. After creation, the same recursive resolver may still return that negative answer. Compare its SOA remaining TTL with an authoritative response. The original 3600-second example applies only when the SOA TTL is no shorter and the resolver has not imposed a lower limit.

Configure the record before release and account for negative-cache expiry. If a prior lookup returned NXDOMAIN, record the response and its expiry; lookups remain useful diagnostic tools.

There are several cache layers beyond the TTL

DNS TTL defines the validity period of cached data. Recursive resolvers, operating systems and applications can apply additional policies. RFC 8767 permits serve-stale under specified refresh-failure conditions. Inspect DNS TTL, application settings and connection reuse separately.

  • The browser’s own DNS cache: browsers can maintain a separate resolver cache. Check expiry, the system-resolver path and DoH mode for the actual version and configuration; a universal one-minute value is not established here.
  • The operating system: systemd-resolved, nscd and macOS’s mDNSResponder each have their own caching policy.
  • The runtime or language layer: Java 17 documentation specifies indefinite positive caching when a security manager is installed. Java 25 documentation makes the default implementation-specific; setting networkaddress.cache.ttl to -1 means cache forever. Check the actual JDK and security properties. A connection pool can also keep using established connections after DNS refresh.

When some clients keep reaching an old IP, check authoritative answers, recursive caches, runtime caches and existing connections separately. Client differences alone do not establish permanent caching in one layer.

Query the zone’s authoritative server directly, for example dig @authoritative-NS example.com A +norecurse. Then compare the public recursive path with dig @8.8.8.8, the local default path with dig, and the application’s configuration and connections. A public recursive answer does not establish the current authoritative answer.

With a local proxy’s fake-IP DNS mode, answers can use a configured synthetic range such as 198.18.0.0/15; the proxy maps those addresses back to hostnames. Transparent proxying does not itself imply fake-IP. In this mode dig still describes local resolution, while identifying the remote address also requires proxy mappings and connection logs. My SSRF Guard Blocked Itself records how that mechanism affected an egress check.

7. DNS Resolution Evidence Matrix

The matrix below separates resolver behavior, cache state, response headers, and migration timing. Use it to identify whether a slow or stale lookup came from the application cache, operating-system cache, recursive resolver, or authoritative records.

Symptom Evidence to collect Likely layer Verification boundary
First lookup is slow, later lookups are fast Request time, TTL, cache hit/miss, resolver address, and latency. Recursive resolver cache or OS resolver cache. Compare cold resolver, warm resolver, and application cache behavior.
Some users still reach an old address Authoritative answer, recursive answer, remaining TTL, and change time. TTL propagation and resolver cache. Do not treat authoritative update as proof every resolver has expired.
Lookup succeeds but HTTP fails Resolved IP, record type, SNI hostname, route, and TLS certificate. Post-DNS network, TLS, or application routing layer. DNS only proves name-to-address mapping, not service readiness.
Private or proxy traffic leaks DNS Local port 53 traffic, DoH/DoT settings, proxy DNS mode, and app resolver logs. Application bypassing the intended resolver path. Capture both local resolver traffic and proxy-side hostname requests.

FAQ

Does TTL zero eliminate stale responses?

It removes much of the cache benefit without controlling every intermediary. Planned, temporary low TTL is generally a more usable migration tool.

Why does this lab avoid packet capture?

Fixed bytes preserve repeatability and are sufficient for header reasoning, while captures add permission and environment variation.

References

The next article takes the resolved address and calculates route selection and MTU boundaries.

Leave a Reply

Scroll down