Networking (DNS, HTTP, TCP)

Difficulty: Intermediate

Question

Explain what happens when you type a URL in the browser. Cover DNS, TCP, TLS, and HTTP.

Answer

When you type https://example.com/api/users and press Enter, a remarkable chain of events happens:

1. DNS Resolution: The browser needs an IP address. It checks its cache, then the OS cache, then queries DNS resolvers. The resolver walks the DNS hierarchy: root nameserver -> .com nameserver -> example.com authoritative nameserver. Returns the IP (e.g., 93.184.216.34).

2. TCP Connection: The browser initiates a TCP three-way handshake with the server: SYN -> SYN-ACK -> ACK. This establishes a reliable, ordered connection.

3. TLS Handshake: For HTTPS, a TLS handshake follows. Client and server agree on encryption algorithms, the server presents its certificate (proving identity), and they exchange keys to establish an encrypted channel. This adds 1-2 round trips.

4. HTTP Request: The browser sends an HTTP GET request with headers (Host, User-Agent, Accept, cookies, etc.).

5. Server Processing: The server processes the request (routing, middleware, business logic, database queries) and builds a response.

6. HTTP Response: The server sends back a status code (200 OK), headers (Content-Type, Cache-Control, Set-Cookie), and the response body (HTML, JSON, etc.).

7. Rendering: For HTML, the browser parses the DOM, fetches CSS/JS/images, and renders the page.

This entire process typically takes 100-500ms.

Code examples

DNS and Network Debugging

# DNS lookup
nslookup example.com
# Address: 93.184.216.34

dig example.com
# ANSWER SECTION:
# example.com.  3600  IN  A  93.184.216.34

# DNS record types:
# A     - Maps domain to IPv4 address
# AAAA  - Maps domain to IPv6 address
# CNAME - Alias to another domain
# MX    - Mail server
# TXT   - Text records (SPF, DKIM, domain verification)
# NS    - Nameserver

# Trace the route to a server
traceroute example.com
# Shows each hop (router) between you and the server

# Check if a port is open
nc -zv example.com 443
# Connection to example.com 443 port [tcp/https] succeeded!

# Full HTTP request/response details
curl -v https://example.com
# Shows DNS, TCP, TLS, HTTP headers in detail

# Check SSL certificate
openssl s_client -connect example.com:443 -servername example.com
# Shows certificate chain, expiry date, cipher suite

# Test HTTP response time
curl -o /dev/null -s -w "DNS: %{time_namelookup}s\nTCP: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\n" https://example.com

curl -v is the most useful debugging tool for HTTP issues. It shows every step: DNS, TCP, TLS, request headers, response headers. dig shows detailed DNS information.

HTTP Headers and Status Codes

# Common HTTP Status Codes:
# 200 OK              - Success
# 201 Created         - Resource created (POST)
# 204 No Content      - Success, no body (DELETE)
# 301 Moved Permanently - Permanent redirect (SEO)
# 302 Found           - Temporary redirect
# 304 Not Modified    - Use cached version
# 400 Bad Request     - Invalid client input
# 401 Unauthorized    - Not authenticated
# 403 Forbidden       - Authenticated but not authorized
# 404 Not Found       - Resource does not exist
# 409 Conflict        - Resource conflict (duplicate)
# 429 Too Many Requests - Rate limited
# 500 Internal Server Error - Server bug
# 502 Bad Gateway     - Upstream server error
# 503 Service Unavailable - Server overloaded/down

# Important Response Headers:
# Cache-Control: max-age=3600, public
# Content-Type: application/json; charset=utf-8
# X-RateLimit-Remaining: 95
# Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict

# Important Request Headers:
# Authorization: Bearer <jwt-token>
# Content-Type: application/json
# Accept: application/json
# Origin: https://myapp.com (CORS)

# CORS Headers (server response):
# Access-Control-Allow-Origin: https://myapp.com
# Access-Control-Allow-Methods: GET, POST, PUT, DELETE
# Access-Control-Allow-Headers: Content-Type, Authorization
# Access-Control-Allow-Credentials: true

Know status codes by heart - they communicate intent. Cache-Control headers dramatically improve performance. CORS headers control which domains can access your API.

CORS and WebSockets

// CORS (Cross-Origin Resource Sharing)
// Browser blocks requests from different origins by default
// Server must explicitly allow cross-origin access

import cors from 'cors';

app.use(cors({
  origin: ['https://myapp.com', 'http://localhost:5173'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,  // allow cookies
}));

// Preflight request: browser sends OPTIONS before POST/PUT/DELETE
// Server must respond with appropriate CORS headers
// GET and POST with simple headers skip preflight

// WebSocket: full-duplex communication
// HTTP: request-response (client initiates)
// WebSocket: bidirectional (both can send anytime)

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (data) => {
    // Broadcast to all connected clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data.toString());
      }
    });
  });

  ws.on('close', () => console.log('Client disconnected'));
});

// Use cases for WebSockets:
// - Real-time chat
// - Live notifications
// - Collaborative editing
// - Live dashboards
// - Multiplayer games

CORS is a browser security feature, not a server limitation. Preflight OPTIONS requests check permissions before the actual request. WebSockets maintain a persistent connection for real-time bidirectional communication.

Key points

Concepts covered

DNS, HTTP/HTTPS, TCP/IP, TLS, CORS, WebSockets