Skip to content

Networking, DNS and HTTP

Phase 2 · The web and APIs · 15 min read

What you'll be able to do

  • Trace an API call from a hostname to a response, and locate where it is delayed or fails.
  • Read HTTP requests, responses, and status codes well enough to build a small client.
  • Set timeouts and choose retries without accidentally repeating a write.

One API call, several conversations

Suppose Python calls requests.get("https://api.example.com/v1/x"). The library hides several steps. This timeline assumes a fresh connection and DNS cache miss. The numbers below are illustrative, not measurements; real values vary widely with distance, load, and caching.

One HTTPS request on a fresh connection: DNS, TCP, TLS, then the request (times are illustrative).

An RTT is the time for a message and reply to make a round trip. At an illustrative 50 ms RTT, one TCP RTT plus two TLS RTTs costs about 3 × 50 = 150 ms before application work. DNS and server processing add more. TLS can take fewer round trips in some cases. With HTTP keep-alive, later requests reuse a connection and avoid the handshakes; a client pool keeps several connections available. When either side closes an idle connection, the next request reconnects.

Addresses, ports, and the stack

A client initiates a connection; a server listens. A destination is an IP address plus a port: for example, 127.0.0.1:8000. localhost resolves to the same machine, often through 127.0.0.1 or IPv6 ::1. Private IPv4 ranges include 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16; they are not directly routed on the public internet.

Think of layers as jobs: a link layer moves data on one local hop; IP routes packets between hosts; TCP or UDP carries data between ports; TLS protects a connection; HTTP gives requests and responses meaning. A socket is the operating system's endpoint for this traffic. Your process handles it through a file descriptor, as in How programs run. A listening socket accepts connections; each accepted TCP connection gets its own socket.

DNS finds a destination, with a delay

DNS maps names to data. An A record gives an IPv4 address; AAAA gives an IPv6 address; CNAME is an alias; TXT carries text for verification and policies. A lookup may go through a local cache and recursive resolver before fetching an authoritative answer.

Records have a TTL, a time to live. A resolver may reuse a cached answer until its TTL expires. If an A record changes while one client has 240 seconds left on a cached answer, that client may keep using the old address for roughly four minutes. After a migration, check the resolved address and TTL before blaming HTTP.

Inspect a name with dig api.example.com or nslookup api.example.com.

TCP, UDP, and TLS

TCP's three-way handshake establishes a connection. TCP delivers an ordered byte stream, retransmits missing data, and adjusts its sending rate to avoid congestion. If an earlier segment is missing, later bytes in that stream wait for it: head-of-line blocking. TCP gives bytes, not message boundaries; HTTP defines where messages end.

UDP sends datagrams without TCP's built-in ordering, retransmission, or congestion control. It suits real-time media and DNS queries. QUIC, used by HTTP/3, runs over UDP but adds reliable streams, security, and congestion control.

HTTPS is HTTP protected by TLS. TLS provides confidentiality, integrity, and server authentication. The server presents a certificate for its name; your client checks the name, validity, and chain to a trusted authority. Keep certificate verification enabled; disabling it allows impersonation. For diagnosis, nc probes a TCP port and openssl s_client inspects a TLS connection.

HTTP is a message with rules

Here is a small HTTP/1.1 exchange. The request line contains method, target, and version. Headers describe the message; a blank line separates them from an optional body. The response starts with a status line. Content-Type tells a receiver how to interpret a body, and Content-Length gives its byte length when used.

GET /v1/x?limit=2 HTTP/1.1
Host: api.example.com
Authorization: Bearer <token>

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 8

{"n": 2}

GET and HEAD should be safe: they should not change server state as the purpose of the request. Safe methods are also idempotent: repeating them has the same intended effect. PUT and DELETE are idempotent by definition, though the second call may receive a different status. POST usually creates or triggers work and is not generally idempotent; a retry after a lost response could create two jobs. An explicit idempotency key can make a particular API's POST retryable when that API supports it.

Class Codes you will meet
2xx success 200 response; 201 created; 204 succeeded with no response body
3xx redirect or cache 301 permanent redirect; 302 temporary redirect; 304 cached representation still valid
4xx client-side issue 400 bad request; 401 authentication needed; 403 understood but refused (often a permissions decision; it does not prove the client is logged in); 404 missing; 409 conflict; 422 understood but invalid content; 429 rate limited
5xx server or gateway issue 500 server error; 502 gateway got a bad upstream response; 503 unavailable; 504 gateway timed out waiting upstream

Cache-Control tells clients and intermediaries whether and how long to cache. Retry-After can tell a client when to try again after 429 or 503. A server can set a cookie with Set-Cookie; the browser stores it and sends it back in Cookie on matching later requests, often to maintain a session. HTTP/1.1 sends readable text headers and typically handles one active response at a time per connection. HTTP/2 uses binary framing and multiplexes several streams on one connection, while preserving the meaning of methods, headers, and status codes.

Timeouts, retries, and responses that keep coming

A connect timeout limits establishing a connection. A read timeout limits how long a socket read can wait for data; it does not necessarily cap the whole request or an endlessly streaming response. Without a timeout, a stalled dependency can hold a worker indefinitely. For a read-only request, retrying a transient failure may help, but bound attempts and wait between them. For 429, obey Retry-After when practical. 503 suggests temporary unavailability; 504 says a gateway waited too long for its upstream. Do not blindly retry a non-idempotent POST, even on 504: the server may have completed the work before its response was lost. See Timeouts and retries for backoff and retry budgets.

Some responses are deliberately long-lived. HTTP/1.1 chunked transfer encoding can send a body in pieces when its length is unknown. Server-Sent Events (SSE) stream events from server to client over HTTP; they fit one-way token streams. WebSockets switch to a persistent, two-way message channel for interactive traffic. In all three cases, set timeouts with the expected pauses and total workload in mind.

Try this in two terminals; stop the server with Ctrl-C. curl -i shows response headers and body, while curl -v also shows connection details.

python -m http.server 8000
curl -i http://127.0.0.1:8000/
curl -v http://127.0.0.1:8000/

The browser developer tools Network tab shows timing, headers, status, and redirects. In Python, urllib.request.urlopen(url, timeout=3) sets a socket operation timeout; check HTTP errors before assuming the body is JSON.

For AI engineers

For AI engineers

Your model API call is an HTTP request even when an SDK hides it. A slow generation can outlast a short read timeout; a 429 can pause a batch; a provider 5xx can require a bounded retry. Streaming tokens resemble SSE, and base64 images make request bodies large. If a batch starts 10,000 calls without bounding concurrency or reusing connections, it can create thousands of simultaneous sockets and handshakes. Size the pool and concurrency to the service's limits, then record status, latency, and retry counts.

Common mistakes

  • Leaving timeouts unset, so one stalled call blocks a worker or batch indefinitely.
  • Retrying a POST blindly after a timeout, even though the first attempt may have succeeded.
  • Parsing every response as JSON without checking the status first; error pages can be HTML, and a body that fails to parse is an error.
  • Turning off TLS certificate verification to “fix” an HTTPS error.
  • Treating 401 as an authorization failure and 403 as a missing login; they mean different things.
  • Opening a new connection for every call or assuming a DNS record change reaches every client immediately.

Check yourself

The first request takes 300 ms, but the next takes 90 ms. The server's work is unchanged. What likely disappeared from the path?

The client may have reused a pooled TCP/TLS connection and a cached DNS answer, avoiding lookup and handshake round trips.

A client times out after sending a job-creating POST. Is it safe to send the same POST again?

Not automatically. The server may have created the job before the response was lost. Check whether the API supports an idempotency key or another way to query the result first.

A client receives 429 with Retry-After: 2. What should it do?

Respect the two-second delay when practical, then retry a safe or idempotent request within a bounded attempt budget. It should not retry forever or blindly repeat a non-idempotent write.

DNS now points to a new address, yet one client still uses the old one. What is a plausible cause?

That client or its resolver may still have the old answer cached until its TTL expires. Inspect its DNS answer and cache behavior.

Lab

Build a small HTTP/1.1 client without making external network calls. In code/networking-http/, parse URLs, construct a request, and read a response. Then fetch JSON from a local test server, distinguishing HTTP errors from timeouts. Finally, retry only rate limits and temporary unavailability, honoring a numeric Retry-After through an injected sleep function; timeouts are never retried. Run the starter checks with: cd code/networking-http && PYTHONPATH=starter python -m pytest tests -q

Go deeper