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

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

When a browser receives a hostname, the first visible wait may happen before HTTP begins: DNS resolution. For engineers, DNS is not merely a name-to-address lookup. The useful questions are which resolver answered, whether a 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.

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.

Search questions

FAQ

Who is this article for?

This article is for readers who want an intermediate-level guide to DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python. It takes about 12 min and focuses on DNS, Python, C, RFC 1035.

What should I read next?

The recommended next step is CIDR, Longest Prefix Match, and MTU: Calculate IP Routing Step by Step, so the article connects into a longer learning route instead of ending as an isolated note.

Does this article include runnable code or companion resources?

Yes. Use the run notes, resource cards, and download links on the page to reproduce the example or inspect the companion files.

How does this article fit into the larger site?

It is connected to the article context block, learning routes, resources, and project timeline so readers can move from concept to implementation.

Article context

Network Fundamentals

A reproducible route through DNS, TCP, TLS, HTTP/3, proxy tunnels, load balancing, and shared caches with code and figures.

Level: Intermediate Reading time: 12 min
  • DNS
  • Python
  • C
  • RFC 1035
Other language version DNS 解析过程详解:从域名查询到 TTL 缓存的 Python 实验
Share summary DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python

A runnable DNS guide covering resolution paths, response headers, TTL cache latency, and deterministic Python/C experiments.

Download share card Open share center

Companion resources

Leave a Reply

Project timeline

Published posts

  1. DNS Resolution Explained: Build a TTL Cache and Packet Parser in Python A runnable DNS guide covering resolution paths, response headers, TTL cache latency, and deterministic Python/C experiments.
  2. CIDR, Longest Prefix Match, and MTU: Calculate IP Routing Step by Step Calculate CIDR ranges, longest-prefix route choice, and MTU/MSS payload segmentation with runnable Python and C examples.
  3. TCP Reliability and Congestion Window: A Runnable Sequence Number Experiment Track TCP sequence numbers, cumulative ACKs, loss, retransmission, and congestion-window changes with safe local experiments.
  4. HTTPS and TLS 1.3 Handshake: Keys, Certificates, and RTT in Practice Understand TLS 1.3 message flights, certificate authentication, ephemeral key agreement, and handshake latency with a safe teaching model.
  5. HTTP/2, HTTP/3, and CDN Caching: Read Page Speed from a Waterfall A deterministic browser-waterfall model for HTTP/2, HTTP/3, QUIC streams, and CDN cache hits or misses.
  6. Forward Proxy vs Reverse Proxy: Connection Paths, Trust Boundaries, and Latency A reproducible guide to forward proxies, reverse proxies, tunnels, TLS boundaries, and latency segments.
  7. HTTP CONNECT and HTTPS Proxy Tunnels: TLS Boundaries and Handshake Latency An RFC-based explanation of CONNECT tunnels, encrypted HTTPS payloads, and modeled first-request latency.
  8. SOCKS5 Proxy Explained: Protocol Bytes, DNS Resolution Boundaries, and Leakage Risk Decode safe SOCKS5 CONNECT bytes and compare local-DNS and proxy-side hostname resolution boundaries.
  9. Reverse Proxy Load Balancing: Queues, Health Checks, and a Reproducible Scheduler Compare round robin and load-aware queue selection while reasoning about health checks and retry boundaries.
  10. Proxy Cache Revalidation: Cache-Control, ETag, and Observable Correctness Use an RFC 9111 shared-cache model to calculate MISS, HIT, and 304 revalidation latency and correctness boundaries.

Published resources

  1. Network Fundamentals Lab README Setup, no-privilege safety boundary, ten Python experiments, and three C examples.
  2. Network fundamentals full lab bundle Bundles Python/C source, fixed scenarios, ten result CSVs, and protocol/proxy figures.
  3. DNS TTL results CSV HIT/MISS state, expiry, and latency for four fixed lookups.
  4. CIDR and MTU results CSV Longest-prefix route and 3600-byte payload segmentation results.
  5. TCP cwnd events CSV Per-round ACK, window, and deterministic retransmission events.
  6. TLS 1.3 flight results CSV Message direction, timing, and teaching shared value in a fixed RTT model.
  7. HTTP/CDN waterfall results CSV Phase timing for HTTP/2 and HTTP/3 in cold and warm cache models.
  8. Proxy path latency results CSV Phase timing for direct access, forward-proxy tunneling, and reverse-proxy cache paths.
  9. CONNECT/TLS timeline CSV Records CONNECT authority, tunnel establishment, and the encrypted HTTPS-request boundary.
  10. SOCKS5 DNS boundary CSV Stores ATYP, destination bytes, request length, and modeled local DNS counts.
  11. Proxy load-balancing queue CSV Compares backend selection and queue waiting for round robin and least queue.
  12. Proxy cache revalidation CSV Records MISS, HIT, 304 revalidation, object age, and response latency.
  13. Network request path visualizer Adjust TTL, prefixes, loss, handshake RTT, and cache paths in the browser.
  14. Network fundamentals topic share card A 1200x630 SVG card for the DNS, TLS, HTTP/3, proxy tunnel, and caching topic hub.

Next notes

  1. Add IPv6 and QUIC observation notes
  2. Review caching and protocol benefits with real-user metrics
Scroll down