Skip to main content

Networking Fundamentals Interview Questions

πŸ”Ή Simple, technical answers with real examples. No unnecessary jargon.

βœ… Difficulty Levels: 🟒 Basic | 🟑 Intermediate | πŸ”΄ Advanced

πŸ“‹ Every question includes: βœ… Clear technical answer βœ… Working example/diagram βœ… πŸ” Interviewer Notes: What they actually look for βœ… ❌ Common Mistakes: Red flags that will get you rejected


πŸ“‘ Table of Contents​

  1. OSI Model & TCP/IP Model
  2. TCP (Transmission Control Protocol)
  3. UDP (User Datagram Protocol)
  4. HTTP/HTTPS Protocols
  5. HTTP/HTTPS Protocols (incl. HTTP/2 and HTTP/3)
  6. DNS (Domain Name System)
  7. TLS/SSL & HTTPS
  8. Socket Programming
  9. Network Security
  10. Common Ports
  11. TCP Deep Dive
  12. HTTP, Connections & Load Balancing
  13. DNS, TLS & Certificates
  14. IP, Packets & Debugging
  15. Senior/Principal Networking Scenarios

OSI Model & TCP/IP Model​

OSI 7-Layer Model​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ OSI MODEL β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚ Layer β”‚ Function β”‚ Data β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 7 β”‚Application β”‚ Network process to app β”‚ Data β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 6 β”‚Presentationβ”‚ Data syntax, encryption β”‚ Data β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 5 β”‚Session β”‚ Interhost communication β”‚ Data β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 4 β”‚Transport β”‚ End-to-end connections β”‚ Segment β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 3 β”‚Network β”‚ Paths determination β”‚ Packet β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 2 β”‚Data Link β”‚ Node-to-node transfer β”‚ Frame β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1 β”‚Physical β”‚ Bit-by-bit delivery β”‚ Bit β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

TCP/IP 4-Layer Model​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TCP/IP MODEL β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Layer β”‚ Protocols/Technologies β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ App β”‚ HTTP, FTP, SMTP, DNS, SSH, WebSocket β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Transportβ”‚ TCP, UDP, SCTP β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Internetβ”‚ IP (IPv4/IPv6), ICMP, ARP, BGP β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Link β”‚ Ethernet, Wi-Fi, PPP, Frame Relay β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Differences​

FeatureOSI ModelTCP/IP Model
Layers74
DevelopmentISO (1984)DoD (1970s)
ApproachTheoreticalPractical
Session layerSeparateCombined with Application

TCP (Transmission Control Protocol)​

TCP Overview​

TCP is a connection-oriented, reliable, byte-stream protocol that ensures:

  • Ordered delivery - Data arrives in the same order sent
  • Error detection - Checksums verify data integrity
  • Flow control - Prevents overwhelming receiver
  • Congestion control - Prevents network overload
  • Full-duplex - Bidirectional communication

TCP Three-Way Handshake​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TCP THREE-WAY HANDSHAKE β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Client Server β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 1. SYN (seq=x) β”‚ β”‚
β”‚ │──────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 2. SYN-ACK (seq=y, ack=x+1) β”‚ β”‚
β”‚ │◀─────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 3. ACK (ack=y+1) β”‚ β”‚
β”‚ │──────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ CONNECTION ESTABLISHED β”‚
β”‚ │◀─────────────────────────────────────────────────────▢│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚
β”‚ β€’ SYN: Synchronize sequence numbers β”‚
β”‚ β€’ ACK: Acknowledgment of received data β”‚
β”‚ β€’ Sequence numbers track data flow β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

TCP Four-Way Termination​

Client (active closer) Server (passive closer)
β”‚ ESTABLISHED ESTABLISHED β”‚
β”‚ β”‚
β”‚ FIN ──────────────────────────────────────────▢│
β”‚ FIN_WAIT_1 CLOSE_WAIT β”‚
β”‚ β”‚
│◀──────────────────────────────────────────── ACKβ”‚
β”‚ FIN_WAIT_2 β”‚
β”‚ (server app finishes, calls close())
│◀──────────────────────────────────────────── FINβ”‚
β”‚ LAST_ACK β”‚
β”‚ ACK ──────────────────────────────────────────▢│
β”‚ TIME_WAIT (2 Γ— MSL) CLOSED β”‚
β”‚ CLOSED β”‚

The server's ACK and FIN can be combined into one segment when it has nothing left to send, which is why captures sometimes show only three packets.

TCP State Diagram​

OPENING
Client: CLOSED ──send SYN──────────────────────▢ SYN_SENT
SYN_SENT ──recv SYN+ACK, send ACK───────▢ ESTABLISHED
Server: CLOSED ──listen()──────────────────────▢ LISTEN
LISTEN ──recv SYN, send SYN+ACK─────────▢ SYN_RCVD
SYN_RCVD ──recv ACK─────────────────────▢ ESTABLISHED

CLOSING (active closer: the side that sends FIN first)
ESTABLISHED ──send FIN──────────────────────────▢ FIN_WAIT_1
FIN_WAIT_1 ──recv ACK──────────────────────────▢ FIN_WAIT_2
FIN_WAIT_2 ──recv FIN, send ACK────────────────▢ TIME_WAIT
TIME_WAIT ──wait 2 Γ— MSL──────────────────────▢ CLOSED

CLOSING (passive closer: the side that receives FIN first)
ESTABLISHED ──recv FIN, send ACK────────────────▢ CLOSE_WAIT
CLOSE_WAIT ──app calls close(), send FIN───────▢ LAST_ACK
LAST_ACK ──recv ACK──────────────────────────▢ CLOSED

TIME_WAIT only ever happens on the side that closed first. Many sockets stuck in CLOSE_WAIT mean the application is not closing connections.

TCP Segment Structure​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TCP SEGMENT STRUCTURE β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Source Port (16) β”‚ Destination Port (16) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Sequence Number (32) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Acknowledgment Number (32) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚Offset(4)β”‚ Res(6)β”‚ Flags(6)β”‚ Window Size (16) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Checksum (16) β”‚ Urgent Pointer (16) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Options (Variable) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Data (Variable) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Flags: URG, ACK, PSH, RST, SYN, FIN β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

TCP Flow Control (Sliding Window)​

# TCP Sliding Window Concept
"""
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SLIDING WINDOW β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ [Sent & Acked] β”‚ [Sent, Not Acked] β”‚ [Not Yet Sent] β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ SENT: 0-999 β”‚ β”‚ β”‚
β”‚ β”‚ ACKED: β”‚ ACKED: 0-499 β”‚ WINDOW: β”‚ β”‚
β”‚ β”‚ 0-499 β”‚ UNACKED: β”‚ 500-1999 β”‚ β”‚
β”‚ β”‚ β”‚ 500-999 β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ β€’ Window slides as ACKs arrive β”‚
β”‚ β€’ Receiver advertises available buffer (rwnd) β”‚
β”‚ β€’ Sender limited by window size β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
"""

# Python example of TCP socket
import socket

class TCPServer:
def __init__(self, host='0.0.0.0', port=8080):
self.host = host
self.port = port
self.socket = None

def start(self):
# Create socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind
self.socket.bind((self.host, self.port))

# Listen (backlog queue)
self.socket.listen(128) # Max 128 pending connections

print(f"Server listening on {self.host}:{self.port}")

while True:
# Accept connection
client_socket, address = self.socket.accept()
print(f"Connection from {address}")

# Handle client
self.handle_client(client_socket)

def handle_client(self, client_socket):
try:
# Receive data
data = client_socket.recv(1024)
if data:
print(f"Received: {data.decode()}")

# Send response
response = b"HTTP/1.1 200 OK\r\n\r\nHello"
client_socket.sendall(response)
finally:
client_socket.close()


class TCPClient:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.socket = None

def connect(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.host, self.port))
print(f"Connected to {self.host}:{self.port}")

def send(self, data: bytes):
self.socket.sendall(data)

def receive(self, buffer_size=1024) -> bytes:
return self.socket.recv(buffer_size)

def close(self):
if self.socket:
self.socket.close()

TCP Congestion Control​

"""
TCP CONGESTION CONTROL ALGORITHMS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. SLOW START
β€’ Start with small cwnd (Congestion Window)
β€’ Exponential increase: cwnd doubles each RTT
β€’ Continues until ssthresh reached

2. CONGESTION AVOIDANCE (CA)
β€’ Linear increase of cwnd
β€’ Additive Increase: cwnd += MSS each RTT

3. FAST RETRANSMIT
β€’ 3 duplicate ACKs β†’ Resend lost segment
β€’ Don't wait for timeout

4. FAST RECOVERY
β€’ After fast retransmit, reduce cwnd
β€’ Return to CA after successful ACK

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CONGESTION WINDOW GROWTH β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ cwnd β”‚
β”‚ β–² β”‚
β”‚ β”‚ β”Œβ”€ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ β”‚
β”‚ β”‚ β•± β•² β”‚
β”‚ β”‚ β•± β•² β”Œβ”€ ─ ─ ─ ─ ─ ─ ─ ─ β”‚
β”‚ β”‚ β•± β•² β•± β•² β”‚
β”‚ β”‚ β•± β•²β•± β•² β”Œβ”€ ─ ─ ─ ─ ─ ─ β”‚
β”‚ β”‚ β•± β•² β•±β•²β•± β”‚
β”‚ β”‚ β•± Slow Start β•²β•± β•² β”‚
β”‚ β”‚ β•± β•² β•± Congestion Avoidance β”‚
β”‚ β”‚β•± β•²β•± β”‚
β”‚ └──────────────────────────────────────────────▢ time β”‚
β”‚ ssthresh β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
"""

UDP (User Datagram Protocol)​

UDP Overview​

UDP is a connectionless, unreliable, datagram protocol:

  • No connection establishment - Sends immediately
  • No ordering - Datagrams may arrive out of order
  • No flow control - Sender can overwhelm receiver
  • Minimal overhead - Only 8-byte header
  • Broadcast/Multicast support

UDP Datagram Structure​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ UDP DATAGRAM STRUCTURE β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Source Port (16) β”‚ Destination Port (16) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Length (16) β”‚ Checksum (16) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Data (Variable) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Total Header Size: 8 bytes β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

TCP vs UDP Comparison​

FeatureTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityReliableUnreliable
OrderingOrderedNo ordering
SpeedSlower (overhead)Faster (minimal)
Flow ControlYesNo
Congestion ControlYesNo
Header Size20-60 bytes8 bytes
BroadcastNoYes
Use CasesHTTP, SSH, EmailDNS, VoIP, Gaming

When to Use UDP​

import socket

class UDPServer:
def __init__(self, port=8080):
self.port = port
self.socket = None

def start(self):
# Create UDP socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.socket.bind(('0.0.0.0', self.port))
print(f"UDP Server listening on port {self.port}")

while True:
# Receive datagram (no connection)
data, address = self.socket.recvfrom(4096)
print(f"Received from {address}: {data.decode()}")

# Process and respond
self.process_datagram(data, address)

def process_datagram(self, data: bytes, address: tuple):
# For streaming/video applications
# Add sequence numbers and reordering in application layer
pass

# UDP Client
class UDPClient:
def send_message(self, message: str, host='localhost', port=8080):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(message.encode(), (host, port))
sock.close()

Use Case Comparison​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TCP vs UDP USE CASES β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ TCP β”‚ β”‚ UDP β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ β€’ HTTP/HTTPS β”‚ β”‚ β€’ DNS queries β”‚ β”‚
β”‚ β”‚ β€’ SSH/SFTP β”‚ β”‚ β€’ VoIP (SIP, RTP) β”‚ β”‚
β”‚ β”‚ β€’ Email (SMTP/IMAP) β”‚ β”‚ β€’ Video streaming β”‚ β”‚
β”‚ β”‚ β€’ File transfers β”‚ β”‚ β€’ Online gaming β”‚ β”‚
β”‚ β”‚ β€’ Database connections β”‚ β”‚ β€’ DHCP β”‚ β”‚
β”‚ β”‚ β€’ API calls β”‚ β”‚ β€’ SNMP β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β€’ Broadcasting β”‚ β”‚
β”‚ β”‚ Needs: Reliability β”‚ β”‚ Needs: Speed & β”‚ β”‚
β”‚ β”‚ Order β”‚ β”‚ Low Latency β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HTTP/HTTPS Protocols​

HTTP Overview​

HTTP (Hypertext Transfer Protocol) is the foundation of web communication:

  • Stateless: Each request is independent
  • Request-Response: Client sends request, server returns response
  • Text-based: Human-readable headers
  • Extensible: Headers allow feature extensions

HTTP Request Structure​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HTTP REQUEST β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Request Line β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ METHOD β”‚ URL β”‚ VERSION β”‚ β”‚
β”‚ β”‚ GET β”‚ /api/users/123 β”‚ HTTP/1.1β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Headers β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Host: api.example.com β”‚ β”‚
β”‚ β”‚ Content-Type: application/json β”‚ β”‚
β”‚ β”‚ Authorization: Bearer eyJhbGci... β”‚ β”‚
β”‚ β”‚ Accept: application/json β”‚ β”‚
β”‚ β”‚ User-Agent: MyApp/1.0 β”‚ β”‚
β”‚ β”‚ Cache-Control: no-cache β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Blank Line (CRLF) β”‚
β”‚ β”‚
β”‚ Request Body (for POST/PUT/PATCH) β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ {"name": "John", "email": "john@example.com"} β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HTTP Response Structure​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HTTP RESPONSE β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Status Line β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ VERSION β”‚ STATUS CODE β”‚ REASON β”‚ β”‚
β”‚ β”‚ HTTP/1.1β”‚ 200 β”‚ OK β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Headers β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Content-Type: application/json β”‚ β”‚
β”‚ β”‚ Content-Length: 256 β”‚ β”‚
β”‚ β”‚ Date: Wed, 15 Mar 2026 12:00:00 GMT β”‚ β”‚
β”‚ β”‚ Server: nginx/1.24.0 β”‚ β”‚
β”‚ β”‚ Cache-Control: max-age=3600 β”‚ β”‚
β”‚ β”‚ Set-Cookie: session=abc123; HttpOnly; Secure β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Blank Line (CRLF) β”‚
β”‚ β”‚
β”‚ Response Body β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ { β”‚ β”‚
β”‚ β”‚ "id": 123, β”‚ β”‚
β”‚ β”‚ "name": "John", β”‚ β”‚
β”‚ β”‚ "email": "john@example.com" β”‚ β”‚
β”‚ β”‚ } β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HTTP Status Codes​

CodeCategoryMeaningCommon Uses
1xxInformationalRequest received, continuing100 Continue, 101 Switching Protocols
200SuccessRequest successful200 OK, 201 Created, 204 No Content
301RedirectResource moved301 Moved Permanently, 302 Found
304RedirectNot modified (cached)304 Not Modified
400Client ErrorBad requestMalformed body, failed validation
401Client ErrorAuthentication requiredMissing or invalid credentials
403Client ErrorForbiddenAuthenticated but not allowed
404Client ErrorNot found404 Not Found
429Client ErrorToo many requests429 Too Many Requests
500Server ErrorServer error500 Internal Server Error
502Server ErrorBad gatewayUpstream returned an invalid response
503Server ErrorService unavailableOverloaded or in maintenance
504Server ErrorGateway timeout504 Gateway Timeout

HTTP Methods​

MethodPurposeIdempotentSafeCacheable
GETRetrieve resourceYesYesYes
POSTCreate resourceNoNoNo
PUTReplace resourceYesNoNo
PATCHPartial updateNoNoNo
DELETERemove resourceYesNoNo
HEADHeaders onlyYesYesYes
OPTIONSSupported methodsYesYesNo

HTTP/1.1 vs HTTP/2 vs HTTP/3​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HTTP VERSIONS COMPARISON β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ HTTP/1.1 β”‚ HTTP/2 β”‚ HTTP/3 β”‚ β”‚
β”‚ β”‚ (1999) β”‚ (2015) β”‚ (2022) β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚
β”‚ β”‚ Text-based β”‚ Binary β”‚ Binary β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ Persistent conn,β”‚ Multiplexed β”‚ QUIC (UDP), β”‚ β”‚
β”‚ β”‚ one request at β”‚ streams on one β”‚ independent β”‚ β”‚
β”‚ β”‚ a time per conn β”‚ TCP connection β”‚ streams β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ HTTP-level β”‚ No HTTP-level β”‚ No HOL blocking β”‚ β”‚
β”‚ β”‚ HOL blocking β”‚ HOL, but TCP β”‚ across streams β”‚ β”‚
β”‚ β”‚ β”‚ HOL remains β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ Header overhead β”‚ HPACK β”‚ QPACK β”‚ β”‚
β”‚ β”‚ (repeated) β”‚ compression β”‚ compression β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ No server push β”‚ Server Push β”‚ Server Push β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HTTP/2 Multiplexing​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ HTTP/2 MULTIPLEXING β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ HTTP/1.1 - Multiple connections required β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Conn 1 β”‚ β”‚ Conn 2 β”‚ β”‚ Conn 3 β”‚ β”‚ Conn 4 β”‚ β”‚
β”‚ β”‚ GET / β”‚ β”‚ GET /1 β”‚ β”‚ GET /2 β”‚ β”‚ GET /3 β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β–Ό β”‚
β”‚ Sequential responses (head-of-line blocking) β”‚
β”‚ β”‚
β”‚ ───────────────────────────────────────────────────────── β”‚
β”‚ β”‚
β”‚ HTTP/2 - Single connection, multiple streams β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Single TCP Connection β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”‚ β”‚
β”‚ β”‚ β”‚Str1β”‚ β”‚Str2β”‚ β”‚Str3β”‚ β”‚Str4β”‚ β”‚Str5β”‚ β”‚ β”‚
β”‚ β”‚ β”‚CSS β”‚ β”‚JS β”‚ β”‚Img β”‚ β”‚JSONβ”‚ β”‚HTMLβ”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”¬β”€β”˜ β””β”€β”€β”¬β”€β”˜ β””β”€β”€β”¬β”€β”˜ β””β”€β”€β”¬β”€β”˜ β””β”€β”€β”¬β”€β”˜ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β–Ό β–Ό β”‚
β”‚ Interleaved frames on single connection β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

DNS (Domain Name System)​

DNS Overview​

DNS is the "phonebook of the internet" - translates human-readable domain names to IP addresses.

DNS Hierarchy​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ DNS HIERARCHY β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ ROOT β”‚ β”‚
β”‚ β”‚(.) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ .com β”‚ β”‚ .org β”‚ β”‚ .net β”‚ β”‚
β”‚ β”‚ (TLD) β”‚ β”‚ (TLD) β”‚ β”‚ (TLD) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ example β”‚ β”‚ wiki β”‚ β”‚ google β”‚ β”‚
β”‚ β”‚ .com β”‚ β”‚ .org β”‚ β”‚ .com β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚www.exmplβ”‚ β”‚ en.wiki β”‚ β”‚ www.goo β”‚ β”‚
β”‚ β”‚ .com β”‚ β”‚ .org β”‚ β”‚ gle.comβ”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β–Ό β–Ό β–Ό β”‚
β”‚ 93.184.216.34 198.35.48.110 142.250.80.46β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

DNS Resolution Process​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ DNS RESOLUTION FLOW β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Browser β”‚
β”‚ β”‚ β”‚
β”‚ β”‚ 1. Check local cache β”‚
β”‚ β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ Cache β”‚
β”‚ β”‚ Yes β†’ Return IP β”‚ Hit! β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ No β”‚
β”‚ β”‚ β”‚
β”‚ β”‚ 2. Query OS DNS Resolver β”‚
β”‚ β”‚ β”‚
β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ OS β”‚
β”‚ β”‚ Yes β†’ Return IP β”‚ Cache β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Hit! β”‚
β”‚ β”‚ No β”‚
β”‚ β”‚ β”‚
β”‚ β”‚ 3. Query Recursive Resolver (ISP/DNS Provider) β”‚
β”‚ │────────────────────────┐ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β–Ό β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ Recursive β”‚ β”‚
β”‚ β”‚ β”‚ Resolver β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ 4. Query Root Nameserver β”‚
β”‚ β”‚ │──────────────────────────────▢│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ Returns TLD (.com) NS β”‚
β”‚ β”‚ ◀──────────────────────────────│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ 5. Query TLD Nameserver β”‚
β”‚ β”‚ │──────────────────────────────▢│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ Returns example.com NS β”‚
β”‚ β”‚ ◀──────────────────────────────│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ 6. Query Authoritative NS β”‚
β”‚ β”‚ │──────────────────────────────▢│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ Returns IP: 93.184.216.34 β”‚
β”‚ β”‚ ◀──────────────────────────────│
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ Return to Browser β”‚
β”‚ β”‚ β–Ό β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ β”‚ Result β”‚ β”‚
β”‚ β”‚ β”‚ 93.184... β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

DNS Record Types​

TypePurposeExample
AIPv4 address93.184.216.34
AAAAIPv6 address2001:db8::1
CNAMECanonical name (alias)www.example.com β†’ example.com
MXMail exchange10 mail.example.com
TXTText data (verification)"v=spf1 include:_spf.example.com"
NSNameserverns1.example.com
PTRReverse DNS34.216.184.93.in-addr.arpa
SOAStart of AuthorityPrimary NS, admin email
SRVService location_http._tcp.example.com
CAACertification Authority Authorization0 issue "letsencrypt.org"

DNS in Python​

import socket
import dns.resolver

class DNSResolver:
def __init__(self):
self.resolver = dns.resolver.Resolver()
# Use Google DNS
self.resolver.nameservers = ['8.8.8.8', '8.8.4.4']

def resolve_a(self, domain: str) -> list:
"""Get A records (IPv4)"""
try:
answers = self.resolver.resolve(domain, 'A')
return [str(rdata) for rdata in answers]
except dns.resolver.NoAnswer:
return []

def resolve_aaaa(self, domain: str) -> list:
"""Get AAAA records (IPv6)"""
try:
answers = self.resolver.resolve(domain, 'AAAA')
return [str(rdata) for rdata in answers]
except dns.resolver.NoAnswer:
return []

def resolve_mx(self, domain: str) -> list:
"""Get MX records"""
try:
answers = self.resolver.resolve(domain, 'MX')
return [(str(rdata.preference), str(rdata.exchange))
for rdata in answers]
except dns.resolver.NoAnswer:
return []

def reverse_lookup(self, ip: str) -> str:
"""PTR record lookup"""
try:
reversed_ip = '.'.join(ip.split('.')[::-1])
answers = self.resolver.resolve(
f"{reversed_ip}.in-addr.arpa", 'PTR'
)
return str(answers[0])
except:
return None

# Usage
resolver = DNSResolver()
print(resolver.resolve_a("example.com"))
print(resolver.resolve_mx("example.com"))

TLS/SSL & HTTPS​

TLS Handshake (Simplified)​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TLS 1.2 HANDSHAKE β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Client Server β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 1. ClientHello β”‚ β”‚
β”‚ β”‚ (TLS version, cipher suites, β”‚ β”‚
β”‚ β”‚ random number, SNI) β”‚ β”‚
β”‚ │───────────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 2. ServerHello β”‚ β”‚
β”‚ β”‚ (chosen cipher, server random) β”‚ β”‚
β”‚ │◀───────────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 3. Certificate β”‚ β”‚
β”‚ β”‚ (server certificate + chain) β”‚ β”‚
β”‚ │◀───────────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 4. ServerHelloDone β”‚ β”‚
β”‚ │◀───────────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 5. ClientKeyExchange β”‚ β”‚
β”‚ β”‚ (premaster secret, encrypted) β”‚ β”‚
β”‚ │───────────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 6. ChangeCipherSpec β”‚ β”‚
β”‚ │───────────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 7. Finished β”‚ β”‚
β”‚ β”‚ (encrypted handshake hash) β”‚ β”‚
β”‚ │───────────────────────────────────▢│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 8. ChangeCipherSpec β”‚ β”‚
β”‚ │◀───────────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ 9. Finished β”‚ β”‚
β”‚ │◀───────────────────────────────────│ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ ENCRYPTED CONNECTION ESTABLISHED β”‚
β”‚ │═══════════════════════════════════════════════════════▢│
β”‚ β”‚ Application Data (HTTPS) β”‚
β”‚ │═══════════════════════════════════════════════════════▢│
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

TLS 1.3 Improvements​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TLS 1.3 vs 1.2 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ TLS 1.2 (2 RTTs) TLS 1.3 (1 RTT) β”‚
β”‚ ───────────────── ──────────────── β”‚
β”‚ Client Server Client Server β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ │───────▢│ │───────▢│ β”‚
β”‚ β”‚ ClientHello β”‚ ClientHello β”‚
β”‚ β”‚ β”‚ + Key Share β”‚ β”‚
β”‚ │◀───────│ │◀───────│ β”‚
β”‚ β”‚ β”‚ β”‚ ServerHello β”‚
β”‚ β”‚ β”‚ β”‚ + Key Share β”‚
β”‚ β”‚ β”‚ β”‚ + Certificate β”‚
β”‚ β”‚ β”‚ β”‚ + Finished β”‚
β”‚ │◀───────│ │◀───────│ β”‚
β”‚ β”‚ ServerHello β”‚ Finished β”‚
β”‚ β”‚ + Certificate │───────────▢│ β”‚
β”‚ β”‚ + ServerKeyExchange β”‚ β”‚
β”‚ β”‚ + ServerHelloDone β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ │───────▢│ β”‚ β”‚
β”‚ β”‚ ClientKeyExchange β”‚ β”‚
β”‚ β”‚ + ChangeCipherSpec β”‚ β”‚
β”‚ β”‚ + Finished β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ │◀───────│ β”‚ β”‚
β”‚ β”‚ ChangeCipherSpec β”‚ β”‚
β”‚ β”‚ + Finished β”‚ β”‚
β”‚ β”‚
β”‚ β€’ 1 RTT instead of 2 β”‚
β”‚ β€’ 0-RTT resumption supported β”‚
β”‚ β€’ Removed: MD5, SHA-1, 3DES, etc. β”‚
β”‚ β€’ Forward secrecy mandatory β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Certificate Chain​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CERTIFICATE CHAIN β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ Root CA (Certificate Authority) β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Issuer: ISRG Root X1 β”‚ β”‚
β”‚ β”‚ Subject: ISRG Root X1 β”‚ β”‚
β”‚ β”‚ Valid: 2015-2035 β”‚ β”‚
β”‚ β”‚ Self-signed (root cert) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β”‚ Signs β”‚
β”‚ β–Ό β”‚
β”‚ Intermediate CA β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Issuer: ISRG Root X1 β”‚ β”‚
β”‚ β”‚ Subject: Let's Encrypt R11 β”‚ β”‚
β”‚ β”‚ Valid: 2024-2027 β”‚ β”‚
β”‚ β”‚ Signed by: ISRG Root X1 β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β”‚ Signs β”‚
β”‚ β–Ό β”‚
β”‚ Server Certificate (Leaf) β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Issuer: Let's Encrypt R11 β”‚ β”‚
β”‚ β”‚ Subject: example.com β”‚ β”‚
β”‚ β”‚ Valid: 2024-03-15 to 2024-06-13 β”‚ β”‚
β”‚ β”‚ Signed by: Intermediate CA β”‚ β”‚
β”‚ β”‚ Contains: Public Key β”‚ β”‚
β”‚ β”‚ SAN: example.com, www.example.com β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ VERIFICATION PROCESS β”‚ β”‚
β”‚ β”‚ 1. Client receives server certificate β”‚ β”‚
β”‚ β”‚ 2. Looks up issuer (intermediate CA) β”‚ β”‚
β”‚ β”‚ 3. Verifies intermediate signed by root β”‚ β”‚
β”‚ β”‚ 4. Verifies server cert signed by intermediate β”‚ β”‚
β”‚ β”‚ 5. Checks validity dates β”‚ β”‚
β”‚ β”‚ 6. Checks hostname matches β”‚ β”‚
β”‚ β”‚ 7. Checks revocation status (OCSP/CRL) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Socket Programming​

TCP Socket Lifecycle​

import socket
import threading

class TCPSocketServer:
"""Production-ready TCP server with error handling"""

def __init__(self, host='0.0.0.0', port=8080):
self.host = host
self.port = port
self.socket = None
self.running = False

def start(self):
"""Start the TCP server"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind with timeout
self.socket.bind((self.host, self.port))
self.socket.listen(128)

self.running = True
print(f"TCP Server listening on {self.host}:{self.port}")

while self.running:
try:
self.socket.settimeout(1.0) # Allow periodic checks
client_socket, address = self.socket.accept()
print(f"Connection from {address}")

# Handle each client in separate thread
thread = threading.Thread(
target=self.handle_client,
args=(client_socket, address),
daemon=True
)
thread.start()

except socket.timeout:
continue
except Exception as e:
print(f"Server error: {e}")
break

def handle_client(self, client_socket: socket.socket, address: tuple):
"""Handle client connection"""
try:
# Set timeout for recv
client_socket.settimeout(30.0)

# Handle multiple requests
while True:
data = client_socket.recv(4096)
if not data:
break

# Process request
response = self.process_request(data)
client_socket.sendall(response)

except socket.timeout:
print(f"Client {address} timed out")
except ConnectionResetError:
print(f"Client {address} disconnected")
except Exception as e:
print(f"Error handling {address}: {e}")
finally:
client_socket.close()
print(f"Connection closed for {address}")

def process_request(self, data: bytes) -> bytes:
"""Process incoming request"""
# Simple HTTP-like response
return b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello"

def stop(self):
"""Stop the server"""
self.running = False
if self.socket:
self.socket.close()


class TCPClient:
"""TCP client with reconnection logic"""

def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.socket = None

def connect(self, timeout=5.0):
"""Connect to server"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(timeout)
self.socket.connect((self.host, self.port))
print(f"Connected to {self.host}:{self.port}")

def send_message(self, message: str) -> str:
"""Send message and receive response"""
if not self.socket:
raise ConnectionError("Not connected")

self.socket.sendall(message.encode())
response = self.socket.recv(4096)
return response.decode()

def close(self):
"""Close connection"""
if self.socket:
self.socket.close()
self.socket = None


# UDP Socket Example
class UDPSocketServer:
"""Simple UDP server"""

def __init__(self, port=8080):
self.port = port
self.socket = None

def start(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('0.0.0.0', self.port))

print(f"UDP Server listening on port {self.port}")

while True:
data, address = self.socket.recvfrom(4096)
print(f"Received from {address}: {data.decode()}")

# Echo back
self.socket.sendto(b"ACK: " + data, address)

def stop(self):
if self.socket:
self.socket.close()

Non-blocking Sockets​

import socket
import select

class NonBlockingTCPServer:
"""Non-blocking TCP server using select()"""

def __init__(self, port=8080):
self.port = port
self.socket = None
self.inputs = []
self.outputs = []
self.message_queues = {}

def start(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(('0.0.0.0', self.port))
self.socket.listen(128)
self.socket.setblocking(False) # Non-blocking mode

self.inputs = [self.socket]

print(f"Non-blocking server on port {self.port}")

while self.inputs:
readable, writable, exceptional = select.select(
self.inputs, self.outputs, self.inputs, 1.0
)

for s in readable:
if s is self.socket:
# New connection
client_socket, address = s.accept()
client_socket.setblocking(False)
self.inputs.append(client_socket)
self.message_queues[client_socket] = []
print(f"New connection from {address}")
else:
# Incoming data
try:
data = s.recv(4096)
if data:
self.message_queues[s].append(data)
if s not in self.outputs:
self.outputs.append(s)
else:
# Connection closed
self.inputs.remove(s)
if s in self.outputs:
self.outputs.remove(s)
s.close()
del self.message_queues[s]
except:
pass

for s in writable:
if s in self.message_queues:
try:
data = self.message_queues[s].pop(0)
s.sendall(b"Echo: " + data)
except IndexError:
self.outputs.remove(s)

for s in exceptional:
self.inputs.remove(s)
if s in self.outputs:
self.outputs.remove(s)
s.close()
del self.message_queues[s]

Network Security​

Common Network Attacks​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ NETWORK ATTACKS β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ MITM β”‚ β”‚ DDoS β”‚ β”‚
β”‚ β”‚ Man-in-Middle β”‚ β”‚ Distributed β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ Denial of β”‚ β”‚
β”‚ β”‚ β€’ SSL stripping β”‚ β”‚ Service β”‚ β”‚
β”‚ β”‚ β€’ ARP spoofing β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β€’ Session hijackβ”‚ β”‚ β€’ SYN flood β”‚ β”‚
β”‚ β”‚ β€’ Packet sniff β”‚ β”‚ β€’ UDP flood β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β€’ HTTP flood β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ SQLi β”‚ β”‚ XSS β”‚ β”‚
β”‚ β”‚ SQL Injection β”‚ β”‚ Cross-Site β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ Scripting β”‚ β”‚
β”‚ β”‚ β€’ Union-based β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β€’ Blind β”‚ β”‚ β€’ Stored XSS β”‚ β”‚
β”‚ β”‚ β€’ Error-based β”‚ β”‚ β€’ Reflected β”‚ β”‚
β”‚ β”‚ β€’ Time-based β”‚ β”‚ β€’ DOM-based β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ DNS β”‚ β”‚ Port β”‚ β”‚
β”‚ β”‚ Spoofing β”‚ β”‚ Scanning β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β€’ Cache poison β”‚ β”‚ β€’ TCP scan β”‚ β”‚
β”‚ β”‚ β€’ DNS hijacking β”‚ β”‚ β€’ SYN scan β”‚ β”‚
β”‚ β”‚ β€’ Pharming β”‚ β”‚ β€’ FIN scan β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Security Best Practices​

import ssl
import hashlib
import hmac

class NetworkSecurity:
"""Network security utilities"""

@staticmethod
def create_ssl_context() -> ssl.SSLContext:
"""Create secure SSL context"""
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)

# Load certificate and key
context.load_cert_chain(
certfile='cert.pem',
keyfile='key.pem'
)

# Set secure options
context.minimum_version = ssl.TLSVersion.TLSv1_3
# TLS 1.3 cipher suites are all AEAD and secure by default;
# set_ciphers() only affects TLS 1.2 and below, so it is not needed here.

return context

@staticmethod
def secure_compare(a: bytes, b: bytes) -> bool:
"""Constant-time comparison to prevent timing attacks"""
return hmac.compare_digest(a, b)

@staticmethod
def hash_password(password: str, salt: bytes) -> str:
"""Hash password with salt using bcrypt"""
import bcrypt
return bcrypt.hashpw(password.encode(), salt).decode()

@staticmethod
def verify_password(password: str, hashed: str) -> bool:
"""Verify password against hash"""
import bcrypt
return bcrypt.checkpw(
password.encode(),
hashed.encode()
)

@staticmethod
def create_jwt(secret: str, payload: dict) -> str:
"""Create secure JWT token"""
import jwt
import time

payload['exp'] = time.time() + 3600 # 1 hour expiry
payload['iat'] = time.time()

return jwt.encode(payload, secret, algorithm='HS256')

@staticmethod
def verify_jwt(token: str, secret: str) -> dict:
"""Verify JWT token"""
import jwt
try:
return jwt.decode(token, secret, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise ValueError("Token expired")
except jwt.InvalidTokenError:
raise ValueError("Invalid token")

Common Ports​

PortProtocolService
20TCPFTP Data
21TCPFTP Control
22TCPSSH
23TCPTelnet
25TCPSMTP
53UDP/TCPDNS
80TCPHTTP
110TCPPOP3
143TCPIMAP
443TCPHTTPS
465TCPSMTPS
587TCPSMTP (Submission)
993TCPIMAPS
995TCPPOP3S
1433TCPMS SQL Server
1521TCPOracle DB
3306TCPMySQL
5432TCPPostgreSQL
5672TCPRabbitMQ
6379TCPRedis
8080TCPHTTP Alt
8443TCPHTTPS Alt
27017TCPMongoDB

Interview Questions​

Q1: What is the difference between TCP and UDP?​

  • TCP is connection-oriented with reliability guarantees; UDP is connectionless
  • TCP provides ordering, flow control, and congestion control; UDP does not
  • TCP has larger headers (20-60 bytes) vs UDP's 8-byte header
  • UDP is faster due to less overhead

Q2: How does DNS resolution work?​

  1. Browser checks its cache
  2. OS resolver checks its cache
  3. Recursive resolver queries root β†’ TLD β†’ authoritative nameserver
  4. IP address returned and cached

Q3: What is the difference between HTTP/2 and HTTP/3?​

  • HTTP/3 uses QUIC (built on UDP) instead of TCP
  • HTTP/3 eliminates head-of-line blocking
  • HTTP/3 has faster handshake (1 RTT vs 2)
  • HTTP/3 has better congestion control

Q4: How does TLS/SSL work?​

  1. Client sends ClientHello with supported cipher suites
  2. Server responds with ServerHello, certificate, key exchange
  3. Client verifies certificate chain
  4. Client and server derive session keys
  5. Encrypted communication begins

Q5: What is the OSI model layers in order?​

  1. Physical, 2. Data Link, 3. Network, 4. Transport, 5. Session, 6. Presentation, 7. Application

Q6: What is ARP and what does it do?​

ARP (Address Resolution Protocol) maps IP addresses to MAC addresses in a local network. It broadcasts a request asking "Who has IP X?" and the owner responds with its MAC address.

Q7: What is the difference between TCP and UDP, and when do you pick each?​

TCP: connection-oriented, reliable, ordered, congestion control β€” used for HTTP, DB, file transfer. UDP: connectionless, no delivery guarantee, low overhead β€” used for DNS, video calls, gaming, real-time streaming where latency beats re-transmission.

Q8: How does DNS resolution work end-to-end?​

  1. Check browser/OS cache β†’ 2. ask recursive resolver β†’ 3. resolver walks root β†’ TLD (e.g., .com) β†’ authoritative nameserver β†’ 4. returns A/AAAA record β†’ 5. cached with TTL. Query types: A (IPv4), AAAA (IPv6), CNAME, MX, TXT, NS.

Q9: What is HTTP/3 and how is it different from HTTP/2?​

HTTP/3 runs over QUIC (UDP-based) instead of TCP: faster handshake (0-1 RTT), eliminates head-of-line blocking per stream, built-in TLS 1.3, connection migration across networks. HTTP/2 multiplexes over TCP (single connection) but head-of-line blocking at transport layer remains.

Q10: What is mTLS and when would you use it?​

Mutual TLS verifies both client and server certificates. Server proves identity to client (normal TLS) AND client proves identity to server. Used for service-to-service auth (zero trust, microservices, API gateways). Adds certificate management overhead.

Q11: What are the main HTTP methods and their properties?​

GET: read, safe (no mutation), cacheable. POST: create, non-idempotent. PUT: full replace, idempotent. PATCH: partial update. DELETE: remove, idempotent. HEAD: GET without body. OPTIONS: capabilities/CORS preflight. Safe = no server state change; idempotent = same result on repeat.

Q12: How does TLS handshake work?​

  1. ClientHello: protocol version, cipher suites. 2. ServerHello + certificate + key exchange. 3. Client verifies certificate chain (trust anchor). 4. Both derive session keys (RSA or ECDHE). 5. Finished messages; encrypted application data begins. ECDHE adds forward secrecy.

Q13: What is a reverse proxy vs a load balancer?​

Reverse proxy: accepts client requests and forwards to backend servers β€” hides topology, adds TLS, compression, caching (nginx/HAProxy). Load balancer: distributes traffic across instances (round robin, least connections, IP hash) with health checks. Often the same product; LB is a role of the proxy.

Q14: What is CDN and how does it improve performance?​

Content Delivery Network caches static assets (and some dynamic) at edge PoPs near users. Reduces latency (shorter distance), offloads origin servers, absorbs traffic spikes, aids DDoS mitigation. Key concepts: origin, edge POP, cache-control/expiry, cache invalidation.

Q15: What is the OSI model and why is it still relevant?​

7 layers: Physical β†’ Data Link β†’ Network β†’ Transport β†’ Session β†’ Presentation β†’ Application. Useful as a mental model for where protocols live (IP=3, TCP/UDP=4, TLS=5/6, HTTP=7) and for troubleshooting (which layer fails: cable, MAC/IP, port, handshake, or app).

Q16: What is a subnet and CIDR?​

Subnet: a logical partition of an IP network. CIDR notation: 192.168.1.0/24 = netmask 255.255.255.0 = first 24 bits are network prefix, 8 bits host β†’ 254 usable addresses. VPCs split subnets for public/private tiers, routing, and security-group boundaries.

Q17: What is NAT and why is it used?​

Network Address Translation rewrites source/destination IPs at a router/gateway β€” lets many private (RFC1918) hosts share one public IP. Essential for IPv4 conservation; issues: breaks direct inbound connections (mitigated by port forwarding/ALGs/NAT64).

Q18: What is the difference between symmetric and asymmetric encryption?​

Symmetric (AES): one shared key for encrypt/decrypt β€” fast, used for bulk data. Asymmetric (RSA/ECC): public key encrypts, private key decrypts β€” slow, used for key exchange and signatures. TLS uses asymmetric to agree a symmetric session key (hybrid).

Q19: How do you troubleshoot a network issue (framework)?​

  1. Is it the client? (curl from another host). 2. DNS (dig, nslookup). 3. Connectivity (ping). 4. Routing (traceroute). 5. Port open? (nc -vz host port). 6. TLS (openssl s_client). 7. App layer (curl -v, browser devtools). Check each layer in order, don't skip.

Q20: What is gRPC and how does it work over HTTP/2?​

gRPC = RPC framework using Protocol Buffers (binary, typed) over HTTP/2: bidirectional streaming, multiplexed connections, lower overhead than JSON REST. Client/server stubs generated from .proto. Trade-offs: harder debuggability than REST, browser support needs gRPC-Web proxy.


TCP Deep Dive​

Q21: Why does TCP need a three-way handshake instead of two?​

Difficulty: 🟒 Basic

Technical Answer: Each side picks its own random Initial Sequence Number (ISN), and each side must confirm that the other received it. The client's SYN carries its ISN; the server's SYN-ACK acknowledges that ISN and carries the server's own ISN; the final ACK confirms the server's ISN. With only two messages the server would never learn whether its ISN arrived, so it could not tell a fresh connection from a delayed, duplicate SYN left over from an old connection. Random ISNs also make it hard for an off-path attacker to inject segments into a connection, because they must guess the sequence numbers.

Client Server
| SYN seq=1000 | "my numbers start at 1000"
|--------------------------------------->|
| SYN-ACK seq=5000 ack=1001 | "got 1000; mine start at 5000"
|<---------------------------------------|
| ACK seq=1001 ack=5001 | "got 5000"
|--------------------------------------->|
| both ISNs confirmed |

The handshake costs one round trip before any data flows. That is why connection reuse matters so much for latency-sensitive backends: a new TLS-over-TCP connection to a server 80 ms away costs at least 160 ms (TCP + TLS 1.3) before the first request byte is sent.

πŸ” Interviewer Notes: They want "both sides must synchronise and confirm sequence numbers" plus the old-duplicate-SYN argument. Linking handshake cost to connection pooling is a strong signal.

❌ Common Mistakes: Saying the third ACK exists "to confirm the connection is open" without mentioning sequence numbers. Thinking SYN carries application data in normal TCP (TCP Fast Open is a separate, optional extension).

Q22: What is TIME_WAIT, why does it exist, and which side ends up in it?​

Difficulty: 🟑 Intermediate

Technical Answer: The side that sends the first FIN (the active closer) enters TIME_WAIT after the close sequence completes and stays there for 2 Γ— MSL (Maximum Segment Lifetime). Linux uses a fixed 60-second TIME_WAIT. It exists for two reasons:

  1. Reliable final ACK: if the last ACK is lost, the peer retransmits its FIN; the TIME_WAIT socket is still around to re-ACK it instead of answering with RST.
  2. Stale segment protection: it stops delayed packets from an old connection being accepted by a new connection that reuses the same 4-tuple (src IP, src port, dst IP, dst port).
Active closer (client) Passive closer (server)
ESTABLISHED ESTABLISHED
| FIN ---------------------------------> | CLOSE_WAIT (app must call close())
FIN_WAIT_1 |
| <--------------------------------- ACK |
FIN_WAIT_2 |
| <--------------------------------- FIN | LAST_ACK
TIME_WAIT (2*MSL) |
| ACK ---------------------------------> | CLOSED
CLOSED

Inspecting socket states on Linux:

# Count sockets per TCP state
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn

# Only TIME-WAIT sockets towards a specific upstream port
ss -tan state time-wait '( dport = :5432 )'

TIME_WAIT is mostly a problem for clients that open many short-lived outbound connections to the same destination: each one pins a local ephemeral port for 60 seconds. The real fix is connection reuse (keep-alive, pooling). net.ipv4.tcp_tw_reuse=1 lets Linux reuse TIME_WAIT sockets for new outgoing connections when TCP timestamps make it safe.

πŸ” Interviewer Notes: Strong answers say "the active closer gets TIME_WAIT" and connect it to ephemeral-port pressure. Mentioning that tcp_tw_recycle was removed from Linux because it broke clients behind NAT shows real operations experience.

❌ Common Mistakes: Treating TIME_WAIT as a bug to eliminate. Confusing it with CLOSE_WAIT (which means your application has not closed a socket the peer already closed β€” that one usually is a bug). Recommending SO_LINGER with a zero timeout everywhere, which sends RST and can lose data.

Q23: What is the difference between TCP flow control and congestion control?​

Difficulty: 🟑 Intermediate

Technical Answer:

  • Flow control protects the receiver. The receiver advertises a receive window (rwnd) in every ACK: "I have this many bytes of buffer free." The sender never has more unacknowledged data in flight than rwnd.
  • Congestion control protects the network. The sender keeps its own congestion window (cwnd), grows it while ACKs arrive (slow start, then congestion avoidance) and shrinks it on loss or other congestion signals. Algorithms include Reno, CUBIC (the Linux default) and BBR.

The sender is limited by both: bytes in flight ≀ min(rwnd, cwnd). Maximum throughput on a single connection is roughly window Γ· RTT, so on long, fast links you need a window at least as large as the bandwidth-delay product (BDP). The window-scale option lets the 16-bit window field describe windows larger than 64 KB.

def bdp_bytes(bandwidth_mbps: float, rtt_ms: float) -> int:
"""Bandwidth-delay product: bytes that must be in flight to fill the pipe."""
return int(bandwidth_mbps * 1_000_000 / 8 * rtt_ms / 1000)


def max_throughput_mbps(window_bytes: int, rtt_ms: float) -> float:
"""Upper bound on single-connection throughput for a given window."""
return window_bytes * 8 / (rtt_ms / 1000) / 1_000_000


if __name__ == "__main__":
# 1 Gbps link, 80 ms RTT (for example, US east coast to Europe)
print(f"BDP needed: {bdp_bytes(1000, 80) / 1024 / 1024:.1f} MiB") # ~9.5 MiB
# Without window scaling the window is capped at 65,535 bytes
print(f"64 KiB window: {max_throughput_mbps(65_535, 80):.1f} Mbps") # ~6.6 Mbps

πŸ” Interviewer Notes: Look for "rwnd is the receiver's limit, cwnd is the sender's estimate of the network" and the min() relationship. Senior candidates explain why one TCP stream across an ocean cannot fill a 10 Gbps link without large buffers.

❌ Common Mistakes: Using the two terms interchangeably. Saying UDP "has flow control at the IP layer" (it has none). Believing more bandwidth always fixes slow transfers when RTT and window size are the real limit.

Q24: What are Nagle's algorithm and delayed ACK, and why do they cause 40 ms latency spikes?​

Difficulty: 🟑 Intermediate

Technical Answer:

  • Nagle's algorithm (sender side): if there is unacknowledged data in flight, hold back new small segments and coalesce them until an ACK arrives or a full-sized segment is ready. It reduces tiny-packet overhead.
  • Delayed ACK (receiver side): wait briefly before ACKing, hoping to piggyback the ACK on a response or to ACK two segments at once. On Linux the minimum delayed-ACK timer is 40 ms.

Together they can deadlock briefly: a client sends a request as two small writes (headers, then body). The first write goes out immediately. Nagle holds the second write until the first is ACKed. The server is waiting for the full request, so it has no response to piggyback on, and its delayed-ACK timer runs out before it ACKs. Result: an extra ~40 ms on every request.

Fixes: write the whole message in one send() call (best), or disable Nagle with TCP_NODELAY for latency-sensitive protocols. Most HTTP clients, database drivers and RPC frameworks already set TCP_NODELAY.

import socket

def connect_low_latency(host: str, port: int) -> socket.socket:
sock = socket.create_connection((host, port), timeout=5)
# Disable Nagle: send small segments immediately
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
return sock

def send_request(sock: socket.socket, header: bytes, body: bytes) -> None:
# One write instead of two avoids the write-write-read pattern entirely
sock.sendall(header + body)

πŸ” Interviewer Notes: A candidate who recognises "suspiciously constant ~40 ms extra latency" as Nagle plus delayed ACK has debugged real systems. Preferring "batch your writes" over "always set NODELAY" shows judgement.

❌ Common Mistakes: Disabling Nagle on bulk-transfer sockets and then writing byte-by-byte, which floods the network with tiny packets. Thinking TCP_NODELAY disables delayed ACK on the peer (it only affects the local sender).

Q25: What is the difference between TCP keepalive, HTTP keep-alive and application heartbeats?​

Difficulty: 🟒 Basic

Technical Answer:

MechanismLayerPurposeTypical default
TCP keepalive (SO_KEEPALIVE)TransportProbe an idle connection to detect a dead peerOff; when on, Linux waits 2 hours idle before probing
HTTP keep-alive (persistent connections)Application (HTTP)Reuse one TCP connection for many requestsOn by default in HTTP/1.1
Application heartbeat (WebSocket ping, gRPC keepalive, custom ping)ApplicationProve the application is alive and keep middleboxes from expiring the flowProtocol- or library-specific

TCP keepalive's default 2-hour idle time is far longer than the idle timeouts of NAT gateways, firewalls and load balancers (often a few minutes or less), so if you rely on it you must tune it per socket:

import socket

def enable_tcp_keepalive(sock: socket.socket, idle: int = 60, interval: int = 10, count: int = 5) -> None:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# Option names differ by OS, so only set the ones this platform supports
if hasattr(socket, "TCP_KEEPIDLE"): # Linux and most other platforms
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)
elif hasattr(socket, "TCP_KEEPALIVE"): # macOS name for the idle time
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, idle)
if hasattr(socket, "TCP_KEEPINTVL"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval)
if hasattr(socket, "TCP_KEEPCNT"):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, count)

if __name__ == "__main__":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
enable_tcp_keepalive(s)
print("keepalive enabled:", bool(s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE)))
s.close()

A TCP keepalive only proves the peer's kernel is alive. A process stuck in a deadlock still ACKs keepalive probes, so long-lived application protocols add their own heartbeats.

πŸ” Interviewer Notes: They want the candidate to separate "detect dead peers" from "reuse connections" and to know the 2-hour default is useless behind NAT. Mentioning that heartbeats must be more frequent than the shortest idle timeout on the path is a plus.

❌ Common Mistakes: Saying "HTTP keep-alive sends packets to keep the connection alive" (it does not; it just does not close the connection). Assuming SO_KEEPALIVE alone detects a hung application.

Q26: When would you build on UDP, and what does the application then have to handle itself?​

Difficulty: 🟑 Intermediate

Technical Answer: Choose UDP when late data is worthless or when you want to control reliability yourself:

  • Real-time media and games: a retransmitted video frame or player position arrives too late to matter.
  • Small request/response lookups: DNS queries fit in one datagram, so a lost packet is just retried.
  • Telemetry and metrics (for example StatsD): losing a sample is acceptable; blocking the app is not.
  • New transports built in user space: QUIC (the transport under HTTP/3) runs over UDP so it can evolve without OS kernel changes.

With UDP, the application owns everything TCP would have done: message loss (timeouts and retries), duplicates (IDs), ordering (sequence numbers), datagram size (stay under the path MTU to avoid IP fragmentation) and pacing (do not flood the network).

import os
import socket
import struct

def udp_request(host: str, port: int, payload: bytes, timeout: float = 0.5, retries: int = 3) -> bytes:
"""Send one datagram and wait for the matching reply, retrying on loss."""
request_id = int.from_bytes(os.urandom(4), "big")
packet = struct.pack("!I", request_id) + payload
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(timeout)
for _ in range(retries):
sock.sendto(packet, (host, port))
try:
while True:
data, _ = sock.recvfrom(2048)
(reply_id,) = struct.unpack("!I", data[:4])
if reply_id == request_id: # ignore stale or duplicate replies
return data[4:]
except TimeoutError:
continue # lost request or lost reply: retry
raise TimeoutError(f"no reply from {host}:{port} after {retries} attempts")

The request ID matters: without it, a late reply to attempt 1 could be mistaken for the reply to a different request.

πŸ” Interviewer Notes: Good candidates say "UDP is not faster per packet; it just avoids handshakes, retransmission waits and head-of-line blocking." Mentioning QUIC as the reason UDP matters to web backends today is a plus.

❌ Common Mistakes: "UDP is for when you don't care about reliability" (many UDP protocols are reliable, just not via TCP). Sending large datagrams and being surprised by fragmentation loss. Retrying non-idempotent operations without request IDs.


HTTP, Connections & Load Balancing​

Q27: What is head-of-line blocking, and how do HTTP/1.1, HTTP/2 and HTTP/3 differ?​

Difficulty: 🟑 Intermediate

Technical Answer: Head-of-line (HOL) blocking is when one slow or lost item stops everything queued behind it.

  • HTTP/1.1: a connection carries one request/response at a time (pipelining exists but is effectively unused). A slow response blocks the connection, so browsers open several connections per origin. This is application-level HOL blocking.
  • HTTP/2: many streams are multiplexed over one TCP connection, which removes application-level HOL blocking. But TCP delivers bytes strictly in order, so a single lost packet stalls every stream until it is retransmitted. This is transport-level HOL blocking, and on lossy networks HTTP/2 can do worse than several HTTP/1.1 connections.
  • HTTP/3: runs on QUIC over UDP. QUIC handles loss per stream, so a lost packet only stalls the stream it belonged to.
HTTP/2 over TCP, packet 2 lost:
stream A: [1] [2 lost] [3 waits] [4 waits]
stream B: [5 waits ...........] <- B is blocked by A's loss
TCP delivers nothing past the gap until 2 is retransmitted

HTTP/3 over QUIC, packet 2 lost:
stream A: [1] [2 lost] [3 waits] [4 waits]
stream B: [5 delivered] <- B keeps flowing

πŸ” Interviewer Notes: The key insight is that HTTP/2 moved HOL blocking from the HTTP layer to the TCP layer, and QUIC moved stream handling into the transport to fix it. Candidates who can explain why HTTP/2 sometimes underperforms on mobile networks stand out.

❌ Common Mistakes: "HTTP/2 eliminated head-of-line blocking" (only at the HTTP layer). Thinking HTTP/1.1 opens a new connection per request (persistent connections are the HTTP/1.1 default).

Q28: Why do you need connection pooling, and how do you size a pool?​

Difficulty: 🟑 Intermediate

Technical Answer: Opening a connection costs a TCP handshake (1 RTT), a TLS handshake (1 RTT with TLS 1.3), CPU for key exchange, and for databases an authentication round trip and server-side process or memory. A pool keeps established connections open and hands them out for reuse.

Sizing:

  • Use Little's Law as a starting point: connections needed β‰ˆ request rate Γ— time each request holds a connection. 200 req/s Γ— 0.05 s β‰ˆ 10 connections, plus headroom.
  • Cap the pool so instances Γ— pool_size stays below the server's limit (for example PostgreSQL's max_connections).
  • Set an acquire timeout so callers fail fast instead of queueing forever when the pool is exhausted.
  • Set an idle expiry shorter than any idle timeout on the path (load balancer, NAT, server) so you never reuse a connection the other side has already dropped.
import asyncio
import httpx

# One shared client per process: the pool lives inside the client.
limits = httpx.Limits(
max_connections=50, # hard cap on concurrent connections
max_keepalive_connections=20, # idle connections kept warm
keepalive_expiry=30.0, # drop idle connections before upstream timeouts do
)
timeout = httpx.Timeout(connect=2.0, read=5.0, write=5.0, pool=1.0) # pool = wait for a free connection

async def main() -> None:
async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:
responses = await asyncio.gather(
*(client.get("https://example.com/") for _ in range(10))
)
print([r.status_code for r in responses])

if __name__ == "__main__":
asyncio.run(main())

πŸ” Interviewer Notes: Interviewers want Little's Law (or equivalent reasoning), awareness of the downstream connection limit across all instances, and a pool-acquire timeout. Creating a new client per request is the classic anti-pattern they are probing for.

❌ Common Mistakes: "Bigger pool = faster." Oversized pools overload the database and add contention. Creating an HTTP client inside every request handler, which throws away the pool. No timeout on acquiring a connection.

Q29: What is the difference between L4 and L7 load balancing?​

Difficulty: 🟑 Intermediate

Technical Answer:

L4 (transport)L7 (application)
SeesIPs, ports, TCP/UDPHTTP method, path, headers, cookies, gRPC service/method
BalancesConnectionsIndividual requests
TLSPassed through (usually)Usually terminated at the LB
FeaturesVery fast, protocol-agnostic, preserves end-to-end TLSPath/host routing, retries, header rewrites, auth, rate limiting, per-request metrics
ExamplesAWS NLB, Linux IPVS, kube-proxy ServicesAWS ALB, NGINX, Envoy, HAProxy in HTTP mode

The difference matters most for long-lived multiplexed connections. HTTP/2 and gRPC send many requests over one connection. An L4 balancer spreads connections, so if a client opens one connection, every request lands on the same backend. An L7 balancer spreads requests across backends.

L4: client --conn1--> LB --conn1--> backend A (all 10,000 gRPC calls go to A)
backend B (idle)

L7: client --conn1--> LB --req1--> backend A
--req2--> backend B
--req3--> backend A ...

πŸ” Interviewer Notes: Expect the candidate to bring up the gRPC/HTTP/2 imbalance problem unprompted at senior level. They should also know L7 is more expensive (it parses traffic and usually holds TLS keys).

❌ Common Mistakes: Saying L4 "cannot do health checks" (it can do TCP checks, and many L4 balancers support HTTP checks too). Assuming kube-proxy balances individual gRPC requests.

Q30: How does a backend learn the real client IP when traffic passes through proxies?​

Difficulty: 🟑 Intermediate

Technical Answer: Behind a load balancer, the TCP peer address your app sees is the proxy's. The original client IP is passed along by:

  • X-Forwarded-For (XFF): a de-facto standard header. Each proxy appends the address it received the connection from: client, proxy1, proxy2.
  • Forwarded: the standardised header (Forwarded: for=203.0.113.7;proto=https), less widely used.
  • PROXY protocol: a small header that L4 proxies prepend to the TCP stream, so non-HTTP protocols (and TLS pass-through) can carry the client address.

The security rule: anyone can send an XFF header. Only trust entries that were added by proxies you control. Read the list from the right and skip exactly as many hops as you have trusted proxies.

import ipaddress

TRUSTED_PROXIES = [ipaddress.ip_network("10.0.0.0/8")] # your LB / ingress subnets

def is_trusted(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return any(addr in net for net in TRUSTED_PROXIES)

def client_ip(peer_ip: str, xff_header: str | None) -> str:
"""Walk right-to-left, skipping trusted proxies; the first untrusted hop is the client."""
if not is_trusted(peer_ip) or not xff_header:
return peer_ip # request did not come through our proxies
hops = [h.strip() for h in xff_header.split(",") if h.strip()]
for hop in reversed(hops):
if not is_trusted(hop):
return hop
return hops[0] if hops else peer_ip

if __name__ == "__main__":
# Attacker sends a fake XFF; our LB at 10.0.0.5 appends the real address.
print(client_ip("10.0.0.5", "1.2.3.4, 198.51.100.20")) # -> 198.51.100.20

πŸ” Interviewer Notes: The trap is taking the left-most XFF value, which the client controls. Candidates who mention rate limiting or geo-blocking being bypassable via spoofed XFF understand the stakes.

❌ Common Mistakes: Trusting the first XFF entry. Trusting XFF when the request did not come from a known proxy. Forgetting PROXY protocol must be enabled on both sides, or the backend will try to parse the PROXY header as application data.

Q31: How do CDNs route users to the nearest edge β€” anycast or DNS?​

Difficulty: 🟑 Intermediate

Technical Answer: Two main techniques, often combined:

  • DNS-based (GeoDNS / latency-based DNS): the CDN's authoritative DNS returns a different IP depending on where the query comes from. Weakness: it sees the recursive resolver's IP, not the user's. The EDNS Client Subnet extension lets resolvers pass a truncated client subnet to improve this. Changes are limited by DNS TTLs and caching.
  • Anycast: the same IP prefix is announced via BGP from many locations; internet routing delivers each packet to the "closest" location in BGP terms (fewest AS hops or best policy, not necessarily lowest latency). Failover is fast: withdraw the route and traffic shifts without waiting for DNS TTLs. Anycast is natural for UDP (DNS resolvers such as 1.1.1.1 and 8.8.8.8 use it); for TCP it works because routes are normally stable for the life of a connection.
BGP announces 203.0.113.0/24 from every PoP
User (Paris) ---> nearest PoP: Paris ---> cache hit? serve : fetch origin
User (Tokyo) ---> nearest PoP: Tokyo ---> cache hit? serve : fetch origin
Same destination IP, different physical servers

πŸ” Interviewer Notes: Look for "anycast = same IP, many places, BGP picks" versus "GeoDNS = different IPs per region." Knowing the resolver-location problem and anycast's fast failover shows depth.

❌ Common Mistakes: Saying anycast always picks the lowest-latency site. Thinking anycast breaks all TCP (route changes mid-connection are possible but rare).


DNS, TLS & Certificates​

Q32: How do DNS TTLs affect a migration, and what is negative caching?​

Difficulty: 🟑 Intermediate

Technical Answer: Every DNS record has a TTL (seconds). Recursive resolvers cache the answer for that long, so after you change a record, some clients keep using the old value until their cached copy expires. Some clients cache on their own too (language runtimes, connection pools holding long-lived connections), which can stretch this further.

Migration playbook:

  1. Days before: lower the TTL (for example from 3600 to 60). Wait at least the old TTL so every cache picks up the short TTL.
  2. Cutover: change the record. Most clients move within about a minute.
  3. Keep the old target serving until traffic on it drops to zero (watch its logs, do not assume).
  4. After: raise the TTL again to reduce query load and dependence on DNS availability.

Negative caching: "this name does not exist" (NXDOMAIN) answers are cached too, for a duration taken from the zone's SOA record. If clients look up a name before you create it, they may keep getting NXDOMAIN for that period after you add it.

# See the TTL remaining in your resolver's cache (second column)
dig +noall +answer api.example.com A

# Ask the authoritative server directly (bypasses caches, shows the configured TTL)
dig +noall +answer api.example.com A @"$(dig +short NS example.com | head -1)"

# SOA record: the last field is used for negative-caching duration
dig +noall +answer example.com SOA

πŸ” Interviewer Notes: They want the "lower the TTL in advance and wait the old TTL" step β€” skipping it is the most common migration mistake. Mentioning that long-lived connections ignore DNS changes entirely is a senior-level point.

❌ Common Mistakes: Lowering the TTL at the moment of cutover (caches still hold the old long TTL). Shutting down the old server immediately. Forgetting about NXDOMAIN caching when creating new records.

Q33: Walk through the TLS 1.3 handshake. What does 0-RTT give you, and what is the risk?​

Difficulty: πŸ”΄ Advanced

Technical Answer: TLS 1.3 completes a full handshake in 1 RTT:

  1. ClientHello: supported versions and cipher suites, a random value, SNI, and a key share β€” the client guesses the key-exchange group (usually X25519) and sends its public key up front.
  2. ServerHello: the server picks the cipher suite and sends its own key share. Both sides can now derive handshake keys, so everything after this is encrypted: EncryptedExtensions, Certificate, CertificateVerify (proves possession of the private key), Finished.
  3. Client Finished, sent together with the first application data.

Compared to TLS 1.2: RSA key transport and static Diffie-Hellman are gone, so every connection has forward secrecy; the certificate is encrypted; the list of cipher suites is much shorter and only includes AEAD ciphers.

0-RTT (early data): on resumption, a client holding a pre-shared key from an earlier session can send application data in its first flight. The risk is replay: an attacker who captures the early data can resend it, and the server cannot fully tell. Only allow 0-RTT for idempotent requests (for example GET without side effects), or disable it.

import socket
import ssl

def inspect_tls(host: str, port: int = 443) -> None:
ctx = ssl.create_default_context()
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
with socket.create_connection((host, port), timeout=5) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as tls:
print("version:", tls.version()) # e.g. 'TLSv1.3'
print("cipher :", tls.cipher()[0]) # e.g. 'TLS_AES_256_GCM_SHA384'
print("ALPN :", tls.selected_alpn_protocol())

if __name__ == "__main__":
inspect_tls("example.com")
Client Server
ClientHello + key_share + SNI --------------------->
<--------------------- ServerHello + key_share
{EncryptedExtensions}
{Certificate}
{CertificateVerify}
{Finished}
{Finished} + [Application Data] -------------------->
{ } = encrypted with handshake keys

πŸ” Interviewer Notes: Key points: key share in the first message is what saves the round trip; forward secrecy is mandatory; 0-RTT is replayable. Senior candidates mention that a "HelloRetryRequest" costs an extra round trip if the client guessed the wrong group.

❌ Common Mistakes: Describing the TLS 1.2 flow (ClientKeyExchange, ChangeCipherSpec) as TLS 1.3. Saying 0-RTT is "free speed" without mentioning replay. Claiming the certificate is sent in plaintext in TLS 1.3.

Q34: What is SNI and why does it matter for servers hosting many domains?​

Difficulty: 🟒 Basic

Technical Answer: Server Name Indication is a field in the ClientHello that tells the server which hostname the client wants before the server sends its certificate. Without it, a server on one IP address cannot know which certificate to present, which used to mean one IP per HTTPS site. With SNI, a load balancer or CDN can serve thousands of domains on one IP and select the right certificate (and backend) per connection.

Consequences:

  • L4 proxies doing TLS pass-through can still route by hostname by reading the SNI, without decrypting.
  • SNI is sent in plaintext in standard TLS 1.3, so network observers can see which site you are connecting to. Encrypted Client Hello (ECH) is the mechanism designed to hide it.
  • Clients that do not send SNI (old libraries, raw IP connections) get the server's default certificate and usually fail hostname verification.
# Ask for a specific hostname's certificate on a shared IP
openssl s_client -connect 203.0.113.10:443 -servername api.example.com </dev/null 2>/dev/null \
| openssl x509 -noout -subject -ext subjectAltName

# Without -servername you may get a different (default) certificate
openssl s_client -connect 203.0.113.10:443 -noservername </dev/null 2>/dev/null \
| openssl x509 -noout -subject

In Python, server_hostname= in wrap_socket sets both the SNI and the name used for hostname verification.

πŸ” Interviewer Notes: They want "SNI lets the server pick the certificate before encryption starts." Linking it to SNI-based routing in L4 proxies and to the privacy leak shows breadth.

❌ Common Mistakes: Saying SNI is encrypted in TLS 1.3. Confusing SNI with the HTTP Host header (Host is sent after the handshake, inside the encrypted channel).

Q35: How does a client validate a server certificate, and what causes "unable to get local issuer certificate"?​

Difficulty: 🟑 Intermediate

Technical Answer: The client:

  1. Builds a chain from the leaf certificate, through intermediates the server sends, up to a root in its local trust store.
  2. Verifies each signature in the chain.
  3. Checks validity periods (notBefore/notAfter) for every certificate.
  4. Checks the hostname against the Subject Alternative Name (SAN) extension. Modern clients ignore the Common Name for this.
  5. Checks key usage / extended key usage (for example "server authentication") and, depending on the client, revocation.

"Unable to get local issuer certificate" almost always means the chain could not be completed: usually the server is not sending its intermediate certificate, or the client's trust store lacks the root (common with private CAs or minimal container images without CA bundles). Browsers sometimes hide the first problem by fetching or caching intermediates, so "it works in Chrome but fails in curl / Python" is a classic symptom.

import socket
import ssl
from datetime import datetime, timezone

def cert_report(host: str, port: int = 443) -> dict:
ctx = ssl.create_default_context() # verifies chain + hostname
with socket.create_connection((host, port), timeout=5) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as tls:
cert = tls.getpeercert()
not_after = datetime.fromtimestamp(ssl.cert_time_to_seconds(cert["notAfter"]), tz=timezone.utc)
return {
"subject": dict(item[0] for item in cert["subject"]),
"issuer": dict(item[0] for item in cert["issuer"]),
"san": [value for kind, value in cert.get("subjectAltName", ()) if kind == "DNS"],
"expires": not_after.isoformat(),
"days_left": (not_after - datetime.now(timezone.utc)).days,
}

if __name__ == "__main__":
try:
print(cert_report("example.com"))
except ssl.SSLCertVerificationError as exc:
print("verification failed:", exc.verify_message)

πŸ” Interviewer Notes: Strong answers mention SAN (not CN), the missing-intermediate problem and the "works in browser, fails in code" pattern. Senior candidates warn against verify=False as a fix.

❌ Common Mistakes: "Fixing" verification errors by disabling verification. Thinking the server should send the root certificate (clients must already trust it; sending it is harmless but useless). Forgetting container images may lack a CA bundle.

Q36: How do you implement mTLS between two Python services?​

Difficulty: πŸ”΄ Advanced

Technical Answer: In mutual TLS both sides present certificates. You need: a CA (usually a private one), a server certificate whose SAN matches the hostname clients use, and a client certificate per service identity. The server requires a client certificate and verifies it against the CA; after the handshake it reads the client's identity from the certificate (SAN or subject) for authorization.

import socket
import ssl

# ---- server side ----
def make_server_context() -> ssl.SSLContext:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain(certfile="server.crt", keyfile="server.key")
ctx.load_verify_locations(cafile="ca.crt") # CA that signs client certs
ctx.verify_mode = ssl.CERT_REQUIRED # reject clients without a valid cert
return ctx

def serve(port: int = 8443) -> None:
ctx = make_server_context()
with socket.create_server(("0.0.0.0", port)) as listener:
while True:
raw, addr = listener.accept()
try:
with ctx.wrap_socket(raw, server_side=True) as tls:
peer = tls.getpeercert()
sans = [v for k, v in peer.get("subjectAltName", ()) if k in ("DNS", "URI")]
# Authorization: decide based on the verified identity, not the IP
if "orders-service.internal" not in sans:
tls.sendall(b"forbidden\n")
continue
tls.sendall(b"hello, orders-service\n")
except ssl.SSLError as exc:
print(f"handshake failed from {addr}: {exc}")

# ---- client side ----
def call(host: str = "payments.internal", port: int = 8443) -> bytes:
ctx = ssl.create_default_context(cafile="ca.crt") # trust our private CA for the server
ctx.load_cert_chain(certfile="client.crt", keyfile="client.key")
with socket.create_connection((host, port), timeout=5) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as tls:
return tls.recv(1024)

Private CAs must issue standards-compliant certificates: since Python 3.13, ssl.create_default_context() enables strict X.509 verification, which rejects certificates missing extensions such as Authority Key Identifier, or a CA certificate without a key usage extension.

Operationally, the hard part is not the handshake but certificate lifecycle: issuing identities automatically, short lifetimes with automatic rotation, and distributing CA bundles during CA rotation (trust old and new CA at the same time). That is why service meshes (Istio, Linkerd) or SPIFFE-based tooling are often used instead of hand-rolled mTLS.

πŸ” Interviewer Notes: Look for CERT_REQUIRED, authorization from the certificate identity, and an answer to "how do certificates rotate?" Candidates who only describe the handshake without lifecycle are mid-level.

❌ Common Mistakes: Using CERT_OPTIONAL and never checking whether a certificate was sent. Authenticating the client but authorizing every authenticated client for everything. Long-lived client certificates with no rotation plan.


IP, Packets & Debugging​

Q37: What are MTU, MSS and fragmentation, and what is a PMTUD black hole?​

Difficulty: πŸ”΄ Advanced

Technical Answer:

  • MTU (Maximum Transmission Unit): the largest IP packet a link carries. Standard Ethernet is 1500 bytes; tunnels (VPN, VXLAN, GRE, WireGuard) reduce the effective MTU because they add headers.
  • MSS (Maximum Segment Size): the largest TCP payload per segment, advertised in the SYN. For IPv4 with no options: MSS = MTU βˆ’ 20 (IP header) βˆ’ 20 (TCP header) = 1460.
  • Fragmentation: IPv4 routers may split oversized packets unless the Don't Fragment (DF) bit is set. IPv6 routers never fragment; only the sender can.
  • Path MTU Discovery (PMTUD): TCP sends packets with DF set. A router that cannot forward one drops it and returns an ICMP "fragmentation needed" (IPv4) or "packet too big" (IPv6) message; the sender lowers its packet size.

A PMTUD black hole happens when a firewall blocks those ICMP messages. Small packets get through, large ones silently vanish. Symptoms: the TCP and TLS handshakes succeed, small API calls work, but large responses or uploads hang until timeout.

# Linux: send a 1500-byte packet with DF set (1472 data + 8 ICMP + 20 IP)
ping -M do -s 1472 -c 3 10.0.2.15
# Shrink until it succeeds to find the path MTU
ping -M do -s 1372 -c 3 10.0.2.15

# macOS equivalent: -D sets the DF bit
ping -D -s 1472 -c 3 10.0.2.15

# Show the MSS and path MTU the kernel is using per connection (Linux)
ss -ti dst 10.0.2.15

Fixes: allow the required ICMP types through firewalls, lower the MTU on tunnel interfaces, or clamp the TCP MSS at the tunnel edge so endpoints never send oversized segments.

πŸ” Interviewer Notes: "Handshake works, small requests work, big responses hang" is the pattern they want you to recognise. Knowing that blocking all ICMP breaks PMTUD is a strong signal.

❌ Common Mistakes: "ICMP is just ping; block it for security." Confusing MTU (IP packet size) with MSS (TCP payload size). Assuming 1500 bytes works everywhere, including inside overlay networks.

Q38: How do you plan non-overlapping CIDR ranges for VPCs and subnets?​

Difficulty: 🟑 Intermediate

Technical Answer: Overlapping ranges cannot be routed between: VPC peering, transit gateways and VPNs will refuse or misroute them, and fixing it later means re-addressing live systems. Plan up front:

  • Reserve a large private block per environment or region (for example 10.0.0.0/16 per VPC out of 10.0.0.0/8), leaving room to grow.
  • Split each VPC into subnets per availability zone and tier (public, private, data).
  • Avoid ranges used by corporate networks, VPN clients, and container overlay / Kubernetes pod and service CIDRs.
  • Remember cloud providers reserve some addresses in every subnet (AWS reserves five), so usable addresses are fewer than the raw count.

Python's standard ipaddress module does the arithmetic:

import ipaddress
from itertools import combinations

vpc = ipaddress.ip_network("10.20.0.0/16")

# Carve /20 subnets: 3 AZs x 2 tiers
subnets = list(vpc.subnets(new_prefix=20))[:6]
for net in subnets:
print(net, "addresses:", net.num_addresses) # 4096 each

# Detect overlaps across environments before you peer them
planned = {
"prod-us": ipaddress.ip_network("10.20.0.0/16"),
"prod-eu": ipaddress.ip_network("10.21.0.0/16"),
"k8s-pods": ipaddress.ip_network("10.20.128.0/17"), # mistake: inside prod-us
"office-vpn": ipaddress.ip_network("192.168.0.0/16"),
}
for (a, na), (b, nb) in combinations(planned.items(), 2):
if na.overlaps(nb):
print(f"OVERLAP: {a} {na} <-> {b} {nb}")

πŸ” Interviewer Notes: They look for awareness that overlaps block future peering and that Kubernetes pod/service CIDRs count. Using /16 for everything without thinking about how many VPCs you will need is a junior answer.

❌ Common Mistakes: Picking 10.0.0.0/16 for every VPC because it is the console default. Forgetting the Kubernetes service CIDR. Sizing subnets so small that autoscaling or pod IPs exhaust them.

Q39: What happens, end to end, when a backend service calls https://api.example.com/users?​

Difficulty: 🟒 Basic

Technical Answer:

  1. URL parsing: scheme https implies port 443; host api.example.com; path /users.
  2. Connection pool check: if an idle keep-alive connection to that host and port exists, reuse it and skip to step 6.
  3. DNS: the resolver library checks local caches and /etc/hosts, then asks the configured recursive resolver, which (on a cache miss) walks root β†’ .com β†’ example.com nameservers. The answer is cached for its TTL.
  4. TCP: the kernel picks an ephemeral source port, does ARP or uses the routing table to find the next hop, and completes the three-way handshake (1 RTT).
  5. TLS: ClientHello with SNI api.example.com and ALPN (h2, http/1.1); the server returns its certificate; the client validates the chain and hostname; keys are derived (1 RTT in TLS 1.3).
  6. HTTP: the request (GET /users, Host, headers) is sent, framed as HTTP/1.1 text or HTTP/2 frames depending on ALPN.
  7. Server side: load balancer β†’ possibly TLS termination β†’ reverse proxy β†’ app β†’ database; the response travels back.
  8. Response handling: the client reads the status and body; the connection goes back to the pool (or closes if the server sent Connection: close).
# See each step happen
curl -v https://api.example.com/users 2>&1 | grep -E '^\*|^> |^< ' | head -40

πŸ” Interviewer Notes: For backend roles, they want connection reuse, DNS caching, TLS with SNI/ALPN and the server-side hop chain β€” not browser rendering. Asking "which of these steps do we skip on the second request?" is a common follow-up.

❌ Common Mistakes: Forgetting connection reuse. Saying DNS is queried on every request. Skipping certificate validation or SNI.

Q40: How do you find out where the time goes in a slow HTTP call?​

Difficulty: 🟑 Intermediate

Technical Answer: Split the request into phases. curl reports cumulative timestamps for each:

VariableMeaning (cumulative from start)
time_namelookupDNS done
time_connectTCP connected
time_appconnectTLS handshake done
time_starttransferFirst response byte received (TTFB)
time_totalWhole transfer finished
curl -s -o /dev/null https://api.example.com/users -w '
dns %{time_namelookup}s
tcp %{time_connect}s
tls %{time_appconnect}s
ttfb %{time_starttransfer}s
total %{time_total}s
remote %{remote_ip}:%{remote_port} http=%{http_version}
'

Reading the result:

  • Large dns: resolver problems, search-domain expansion, or missing caching.
  • tcp βˆ’ dns roughly equals one RTT. Much larger means distance, packet loss or SYN retransmits (a jump of about one second is a classic sign of a dropped SYN on Linux).
  • tls βˆ’ tcp large: extra round trips, OCSP or a slow handshake on an overloaded server.
  • ttfb βˆ’ tls large: the server (app, database, downstream calls) is slow; the network is not the problem.
  • total βˆ’ ttfb large: big payload or limited throughput.

Then go deeper with the right tool: dig for DNS, ss -ti for per-connection RTT and retransmits, tcpdump for packet-level evidence, and distributed tracing for server-side time.

# Capture only the handshake and resets for one host (needs root)
sudo tcpdump -i any -nn 'host 203.0.113.10 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)'

πŸ” Interviewer Notes: A structured, phase-by-phase breakdown is what they want. Candidates who immediately blame "the network" or "the database" without measuring are marked down.

❌ Common Mistakes: Treating the timings as durations rather than cumulative timestamps. Measuring once and drawing conclusions (always repeat; first calls include cold caches). Forgetting that a connection pool hides DNS, TCP and TLS cost on warm calls.


Senior/Principal Networking Scenarios​

Q41: Outbound calls fail with "Cannot assign requested address" under load. What is happening?​

Level: Senior

Scenario: A Python service calls a payments API through a single NAT/egress IP. At peak traffic, a growing fraction of outbound calls fail instantly with OSError: [Errno 99] Cannot assign requested address. CPU and memory look normal.

Impact: Checkout success rate drops by 15% at peak; retries make it worse.

Root Cause: Ephemeral port exhaustion. Each outbound TCP connection to the same destination IP and port needs a unique local port. The code creates a new HTTP client per request, so every call opens a new connection and closes it after one use. The client side is the active closer, so each closed socket sits in TIME_WAIT for 60 seconds. With the default Linux range of roughly 28,000 ephemeral ports, anything above about 470 new connections per second to one destination exhausts the pool (28,000 Γ· 60). The same limit exists one level up on cloud NAT gateways, which have a per-destination port budget.

Fix:

  1. Reuse connections: one long-lived client with a keep-alive pool per process. This removes the problem at its source.
  2. Widen the port range and enable safe reuse of TIME_WAIT sockets for outgoing connections as headroom, not as the fix.
  3. Add more egress IPs (or NAT gateway addresses) if the connection rate is legitimately high.
  4. Alert on TIME_WAIT count and on connect errors.
# Before: a new client (and new TCP + TLS connection) per call
# async def charge(payload):
# async with httpx.AsyncClient() as client:
# return await client.post(URL, json=payload)

# After: one pooled client for the whole process
import httpx

URL = "https://payments.example.com/v1/charges"

client = httpx.AsyncClient(
limits=httpx.Limits(max_connections=200, max_keepalive_connections=100, keepalive_expiry=30),
timeout=httpx.Timeout(5.0, pool=1.0),
)

async def charge(payload: dict) -> httpx.Response:
return await client.post(URL, json=payload)

async def shutdown() -> None:
await client.aclose()
# Diagnose: TIME-WAIT sockets towards the upstream, and the available port range
ss -tan state time-wait '( dport = :443 )' | wc -l
sysctl net.ipv4.ip_local_port_range

# Headroom (Linux): widen the range and allow reuse for outgoing connections
sysctl -w net.ipv4.ip_local_port_range="10240 65000"
sysctl -w net.ipv4.tcp_tw_reuse=1

Workflow Diagram:

request --> new client --> connect() needs (src_ip, src_port, dst_ip, 443)
|
free ephemeral port? --no--> EADDRNOTAVAIL (Errno 99)
| yes
call --> close() --> TIME_WAIT 60s (port pinned)

After fix:
request --> shared pool --> idle conn? --yes--> reuse (no new port)
| no
connect() once, keep alive, reuse thousands of times

Interviewer Notes: The best answers do the arithmetic (ports Γ· TIME_WAIT duration = max new connections per second), identify the client as the active closer, and fix it with connection reuse rather than kernel tuning. Mentioning NAT gateway port limits shows cloud experience.

Red Flags: Suggesting tcp_tw_recycle (removed from Linux and broke NAT clients). "Just increase the port range" as the whole answer. Adding retries, which multiplies new connections.

Q42: Pods in Kubernetes see intermittent DNS timeouts and slow external calls. How do you diagnose it?​

Level: Senior

Scenario: Services in a Kubernetes cluster call api.stripe.com and orders.default.svc. A small percentage of requests take exactly 5 seconds longer than normal, and some fail with DNS resolution errors. CoreDNS CPU is high.

Impact: p99 latency jumps from 120 ms to over 5 s; sporadic 5xx errors during traffic peaks.

Root Cause: Two compounding problems:

  1. ndots:5 search-path expansion. The default pod resolv.conf has options ndots:5 and several search domains. Any name with fewer than five dots is tried with each search suffix first, so api.stripe.com becomes api.stripe.com.default.svc.cluster.local, api.stripe.com.svc.cluster.local, api.stripe.com.cluster.local, … before the real name β€” each for both A and AAAA. One lookup becomes many queries, multiplying CoreDNS load.
  2. Lost UDP DNS packets. The resolver sends A and AAAA queries in parallel from the same socket. A known Linux conntrack race on that pattern can drop one of the packets; glibc then waits its default 5-second timeout before retrying β€” the "exactly +5 s" signature.

Fix:

  • Use fully qualified names with a trailing dot for external hosts (api.stripe.com.), which skips search expansion.
  • Lower ndots for workloads that mostly call external names.
  • Run NodeLocal DNSCache so pods query a cache on their own node, which also avoids the conntrack race for pod-to-node DNS traffic.
  • Scale CoreDNS and enable its cache; monitor its latency and error metrics.
apiVersion: v1
kind: Pod
metadata:
name: checkout
spec:
dnsConfig:
options:
- name: ndots
value: "2" # names with 2+ dots are tried as absolute first
- name: single-request-reopen # glibc: use separate sockets for A and AAAA
containers:
- name: app
image: example/checkout:1.0
env:
- name: PAYMENTS_HOST
value: "api.stripe.com." # trailing dot = fully qualified, no search list
# Inspect what the pod actually uses
kubectl exec checkout -- cat /etc/resolv.conf
# Watch the expansion happen (run from a debug container with dig installed)
dig +search +showsearch api.stripe.com

Workflow Diagram:

app resolves "api.stripe.com" (2 dots < ndots 5)
|
+--> api.stripe.com.default.svc.cluster.local A/AAAA -> NXDOMAIN
+--> api.stripe.com.svc.cluster.local A/AAAA -> NXDOMAIN
+--> api.stripe.com.cluster.local A/AAAA -> NXDOMAIN
+--> api.stripe.com.<cloud search domain> A/AAAA -> NXDOMAIN
+--> api.stripe.com. A/AAAA -> answer
|
one UDP reply dropped by conntrack race --> wait 5 s --> retry

Fixed: "api.stripe.com." --> NodeLocal DNS cache --> answer (1 query pair)

Interviewer Notes: They want the 5-second timeout recognised as a DNS retry, the ndots explanation with the query multiplication, and NodeLocal DNSCache as the structural fix. Measuring CoreDNS query volume before and after shows rigor.

Red Flags: "Increase CoreDNS replicas" as the only answer. Hard-coding IPs into config. Not knowing what ndots means.

Q43: A TLS certificate expired at 02:00 and took down production. How do you fix it and prevent it?​

Level: Senior

Scenario: At 02:00 UTC, mobile apps and partner integrations start failing with certificate errors on api.example.com. Browsers show "NET::ERR_CERT_DATE_INVALID". The certificate was installed manually on the load balancer a year ago; the renewal reminder went to an ex-employee's mailbox.

Impact: Complete API outage for 3 hours; partners' webhooks fail and queue up.

Root Cause: Manual certificate lifecycle with a single human dependency and no monitoring of the certificate the endpoint actually serves. A secondary cause is often found too: an internal service had pinned the old certificate, so it kept failing even after renewal.

Fix:

  • Immediate: issue or renew the certificate (the CA's ACME endpoint or your CA portal), deploy it to every termination point (LB, CDN, ingress), verify from outside with openssl s_client.
  • Automate issuance and renewal with ACME (for example cert-manager in Kubernetes, or the cloud provider's managed certificates) and renew well before expiry.
  • Monitor what is served, not what is in a spreadsheet: probe every public and internal TLS endpoint daily and alert at 21 and 7 days remaining.
  • Inventory all termination points, including internal mTLS CAs and client certificates.
  • Pin to a CA or public key set, never to a single leaf certificate, if pinning is required at all.
"""Probe TLS endpoints and exit non-zero if any certificate expires soon. Run from cron/CI."""
import socket
import ssl
import sys
from datetime import datetime, timezone

ENDPOINTS = [("api.example.com", 443), ("auth.example.com", 443), ("example.com", 443)]
WARN_DAYS = 21

def days_left(host: str, port: int) -> int:
ctx = ssl.create_default_context()
with socket.create_connection((host, port), timeout=5) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as tls:
not_after = tls.getpeercert()["notAfter"]
expires = datetime.fromtimestamp(ssl.cert_time_to_seconds(not_after), tz=timezone.utc)
return (expires - datetime.now(timezone.utc)).days

def main() -> int:
failing = 0
for host, port in ENDPOINTS:
try:
left = days_left(host, port)
status = "OK" if left > WARN_DAYS else "EXPIRING"
print(f"{status:9} {host}:{port} {left} days left")
failing += left <= WARN_DAYS
except (OSError, ssl.SSLError) as exc: # includes already-expired certs
print(f"BROKEN {host}:{port} {exc}")
failing += 1
return 1 if failing else 0

if __name__ == "__main__":
sys.exit(main())

Workflow Diagram:

cert-manager / ACME client --(renew at 2/3 of lifetime)--> CA
|
v
new cert stored as secret --> ingress / LB reloads
|
daily probe (outside-in) --> days_left <= 21? --yes--> page owner team
| no
v
green

Interviewer Notes: Expect a blameless framing: the failure is a process with no automation and no outside-in monitoring, not a person. Strong candidates mention every termination point (CDN, LB, ingress, internal services), certificate pinning risks and shorter-lived automated certificates.

Red Flags: "Set a calendar reminder." Monitoring only certificate files on disk rather than the served certificate. Disabling verification on clients as a workaround.

Q44: Users see random 502 errors from the load balancer, but the app logs show no errors. Why?​

Level: Senior

Scenario: An API runs behind an AWS Application Load Balancer (idle timeout 60 s). A small but steady rate of requests (around 0.1%) returns 502 Bad Gateway. Application logs show no corresponding requests at all. The errors are more frequent during low-traffic hours.

Impact: Intermittent client failures; partners complain about flaky integrations; retries hide the problem but inflate latency.

Root Cause: Keep-alive timeout mismatch. The load balancer keeps idle connections to the backend open for up to 60 s and reuses them. The app server closes idle keep-alive connections much sooner (Uvicorn's default --timeout-keep-alive is 5 seconds; Gunicorn's default --keep-alive is 2 seconds). Race: the backend closes an idle connection at the same moment the LB sends a new request on it. The backend replies with RST (or the LB reads EOF), and the LB returns 502. The request never reached the application, so there is nothing in the app logs. Low traffic makes connections sit idle longer, so the race happens more often.

Fix: The upstream (backend) idle timeout must be longer than the downstream (LB) idle timeout, so the LB always closes first.

# app.py β€” run with: python app.py
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health() -> dict:
return {"ok": True}

if __name__ == "__main__":
uvicorn.run(
app,
host="0.0.0.0",
port=8000,
timeout_keep_alive=75, # longer than the ALB idle timeout (60 s)
)
# If NGINX sits between the LB and the app, apply the same rule at each hop
http {
keepalive_timeout 75s; # client side (towards the LB): longer than LB idle timeout

upstream app {
server 127.0.0.1:8000;
keepalive 32;
keepalive_timeout 50s; # upstream side: shorter than the app's 75 s
}
}

Workflow Diagram:

Broken: Fixed:
LB idle timeout 60s LB idle timeout 60s
app idle timeout 5s app idle timeout 75s

t=0 request #1 ok t=0 request #1 ok
t=5s app closes idle conn (FIN) t=60s LB closes idle conn first
t=5s LB sends request #2 on it t=61s LB opens new conn for request #2
-> RST / EOF -> LB returns 502 -> no race

Interviewer Notes: The key signals are "502 with nothing in app logs" and "worse at low traffic." They want the rule "each hop's idle timeout must exceed the one in front of it" applied across every hop (CDN β†’ LB β†’ proxy β†’ app).

Red Flags: Increasing the LB timeout (makes it worse). Blaming the app for crashing without evidence. Adding retries everywhere without fixing the timeout ordering.

Q45: An endpoint that calls a service in another region is slow, even though that service responds in 5 ms. How do you fix it?​

Level: Senior

Scenario: A US-East API calls an inventory service hosted in EU-West for each item in a cart. The inventory service's own metrics show 5 ms per request, but the US endpoint's p50 is 1.8 seconds for a 20-item cart.

Impact: Cart page latency breaks the SLO; conversion drops.

Root Cause: Round-trip time dominates, not server time. The RTT between the regions is around 80 ms. The code makes 20 sequential calls, so even on a warm connection the floor is 20 Γ— (80 ms + 5 ms) β‰ˆ 1.7 s. Whenever the pool has no idle connection, a call also pays TCP (1 RTT) + TLS 1.3 (1 RTT), turning 85 ms into about 245 ms. The service is fast; the call pattern is chatty.

Fix (in order of impact):

  1. Batch: one call for all 20 items (POST /inventory:batchGet). One RTT instead of twenty.
  2. Reuse connections: a pooled client removes the TCP and TLS round trips on every call.
  3. Parallelise independent calls with bounded concurrency if a batch API is not available.
  4. Move data closer: a regional read replica or cache of inventory in US-East, if the consistency model allows.
  5. Architecturally, avoid synchronous cross-region calls on the request path.
import asyncio
import httpx

INVENTORY = "https://inventory.eu.example.com"
client = httpx.AsyncClient(base_url=INVENTORY, timeout=httpx.Timeout(2.0)) # pooled, reused

async def stock_batch(item_ids: list[str]) -> dict[str, int]:
"""Best: one round trip for the whole cart."""
resp = await client.post("/v1/stock:batchGet", json={"ids": item_ids})
resp.raise_for_status()
return resp.json()["stock"]

async def stock_parallel(item_ids: list[str], max_concurrency: int = 10) -> dict[str, int]:
"""Fallback when no batch endpoint exists: bounded parallelism on warm connections."""
sem = asyncio.Semaphore(max_concurrency)

async def one(item_id: str) -> tuple[str, int]:
async with sem:
resp = await client.get(f"/v1/stock/{item_id}")
resp.raise_for_status()
return item_id, resp.json()["quantity"]

return dict(await asyncio.gather(*(one(i) for i in item_ids)))

Workflow Diagram:

Before (sequential calls):
item1: [req 85] item2: [req 85] ... item20: [req 85] ~ 1.7 s
(+160 ms for any call that must open a new TCP + TLS connection)

After (pooled + batch):
[req 80ms + 5ms server] ~ 90 ms

After (pooled + parallel, no batch API):
item1..10 [req] \
item11..20 [req] -> 2 waves x ~85 ms ~ 170 ms

Interviewer Notes: They want latency arithmetic in RTTs, recognition that server time is irrelevant here, and a preference for batching and data locality over "make the service faster." Principal-level answers question whether the call should cross regions at all.

Red Flags: Optimising the inventory service's database. Unbounded gather over hundreds of calls (overloads the dependency). Ignoring connection setup cost.

Q46: A service slowly stops responding and ss shows thousands of sockets in CLOSE_WAIT. What is wrong?​

Level: Senior

Scenario: A worker that streams files from an internal storage API degrades over several days: requests start timing out, then the process hits "Too many open files." Restarting fixes it for a few days. ss -tan shows thousands of connections to the storage API in CLOSE_WAIT.

Impact: Recurring outages every few days; on-call restarts the service by hand.

Root Cause: CLOSE_WAIT means the peer closed the connection (sent FIN) but this process never called close() on its socket. The kernel cannot clean it up, so file descriptors leak until the process hits its limit. Here the code uses requests with stream=True and returns early on some error paths without reading or closing the response, so those connections are never released back to the pool or closed. Unlike TIME_WAIT, CLOSE_WAIT never times out on its own: it is always an application bug.

Fix: Guarantee the response is closed on every path (a context manager), keep the session shared, and alert on CLOSE_WAIT and open-file-descriptor counts.

import requests

session = requests.Session() # shared pool

def copy_object(url: str, dest_path: str) -> bool:
# Bug version (leaks a connection when status != 200):
# resp = session.get(url, stream=True, timeout=10)
# if resp.status_code != 200:
# return False
# ...

# Fixed: the with-block closes the response on every path, including exceptions
with session.get(url, stream=True, timeout=10) as resp:
if resp.status_code != 200:
return False
with open(dest_path, "wb") as fh:
for chunk in resp.iter_content(chunk_size=64 * 1024):
fh.write(chunk)
return True
# Which remote endpoints own the CLOSE_WAIT sockets?
ss -tan state close-wait | awk 'NR>1 {print $4}' | sort | uniq -c | sort -rn | head
# File descriptors held by the process
ls /proc/"$(pgrep -f worker.py | head -1)"/fd | wc -l

Workflow Diagram:

storage API (idle timeout) --FIN--> our socket: ESTABLISHED -> CLOSE_WAIT
|
app calls close()? --no--> stays CLOSE_WAIT forever
| (fd leak -> EMFILE)
yes
v
LAST_ACK -> CLOSED (fd released)

Interviewer Notes: The crucial distinction: TIME_WAIT is normal kernel behaviour; CLOSE_WAIT is your code not closing sockets. Candidates should go from the socket state to "find the code path that does not close the response."

Red Flags: Raising ulimit -n as the fix. Tuning kernel TIME_WAIT settings for a CLOSE_WAIT problem. Scheduling periodic restarts as the long-term solution.

Q47: After moving traffic over a VPN / overlay network, large responses hang but small ones work. Why?​

Level: Senior

Scenario: Services in a data centre now reach a cloud database and APIs over an IPsec VPN. Health checks pass and small queries work, but queries returning large result sets and file uploads hang until timeout. Packet captures show the large packets being sent repeatedly with no ACK.

Impact: Batch jobs and reports fail; the migration is blocked.

Root Cause: MTU mismatch with a PMTUD black hole. Endpoints still assume a 1500-byte MTU and negotiate an MSS of 1460. The VPN adds tunnel overhead, so the real path MTU is smaller. Full-size packets (with DF set) are dropped at the tunnel, and the ICMP "fragmentation needed" messages that should tell the sender to shrink packets are blocked by a firewall. Handshakes and small payloads fit, so only large transfers hang.

Fix:

  1. Clamp the TCP MSS on the tunnel gateway so SYNs advertise an MSS that fits the tunnel β€” endpoints never send oversized segments.
  2. Allow the needed ICMP types (IPv4 "fragmentation needed", IPv6 "packet too big") through firewalls.
  3. Or lower the MTU on the tunnel interface explicitly.
# On the Linux gateway forwarding traffic into the tunnel:
# rewrite the MSS in SYN packets to fit the outgoing interface's path MTU
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN \
-j TCPMSS --clamp-mss-to-pmtu

# Verify the real path MTU from a host (Linux): largest payload that passes with DF set
for size in 1472 1422 1400 1372 1350; do
if ping -M do -s "$size" -c 1 -W 1 10.50.0.10 >/dev/null 2>&1; then
echo "largest passing ICMP payload: $size (MTU $((size + 28)))"; break
fi
done

Workflow Diagram:

host (MTU 1500, MSS 1460) --1500-byte packet, DF--> VPN gateway (tunnel MTU < 1500)
|
too big: drop + ICMP "frag needed"
|
firewall blocks ICMP --> host never learns
|
host retransmits 1500-byte packet forever --> hang

With MSS clamping:
SYN (MSS 1460) --> gateway rewrites MSS to fit tunnel --> all segments fit --> OK

Interviewer Notes: The "small works, large hangs, handshakes fine" pattern should immediately suggest MTU. Knowing MSS clamping as the practical fix and why blocking ICMP causes it shows network maturity.

Red Flags: Increasing application timeouts. Blaming the database. Recommending blocking all ICMP for security.

Q48: After a database failover updated DNS, some app instances keep writing to the old primary. Why?​

Level: Principal

Scenario: A managed database fails over: the DNS name db.internal now points to the new primary (TTL 30 s). Ten minutes later, some application instances still send writes to the old node, which is now a read-only replica, and they fail with "cannot execute in a read-only transaction."

Impact: Partial write outage long after the failover "completed"; manual restarts needed.

Root Cause: DNS only matters when a new connection is opened. The connection pools hold long-lived connections opened before the failover; they still point to the old IP and remain healthy at the TCP level. The pool has no maximum connection lifetime, and pool health checks (a simple SELECT 1) still succeed on a read-only replica. Some runtimes also cache DNS answers in-process longer than the record's TTL.

Fix:

  • Set a maximum connection lifetime in the pool so connections are recycled (and DNS re-resolved) regularly.
  • Treat specific errors (read-only, "not primary") as fatal for the connection: discard it and the pool reconnects.
  • Make health checks verify the role, not just liveness.
  • Check runtime DNS caching settings so they respect TTLs.
# SQLAlchemy example (PostgreSQL)
from sqlalchemy import create_engine, event, exc

engine = create_engine(
"postgresql+psycopg://app@db.internal/orders",
pool_size=10,
pool_recycle=300, # close connections older than 5 minutes; new ones re-resolve DNS
pool_pre_ping=True, # test connections on checkout
)

@event.listens_for(engine, "handle_error")
def drop_connection_on_readonly(ctx) -> None:
# SQLSTATE 25006 = read_only_sql_transaction: we are talking to a replica
if getattr(ctx.original_exception, "sqlstate", None) == "25006":
ctx.is_disconnect = True # invalidate this connection; the pool reconnects

@event.listens_for(engine, "checkout")
def assert_primary(dbapi_conn, _record, _proxy) -> None:
# Costs one query per checkout; raising DisconnectionError here makes the
# pool discard this connection and try a fresh one.
with dbapi_conn.cursor() as cur:
cur.execute("SELECT pg_is_in_recovery()")
if cur.fetchone()[0]:
raise exc.DisconnectionError("connected to a replica, retrying")

Workflow Diagram:

t0 pool: [c1 -> 10.0.1.5 (primary)] [c2 -> 10.0.1.5] ...
t1 failover: DNS db.internal -> 10.0.2.7 ; 10.0.1.5 becomes read-only replica
t2 pool still uses c1, c2 -> 10.0.1.5 -> writes fail (SQLSTATE 25006)
|
+-- handle_error marks connection dead -> pool reconnects
+-- pool_recycle expires old connections anyway
|
v
t3 new connection: resolve db.internal -> 10.0.2.7 -> role check passes -> writes OK

Interviewer Notes: Principal-level insight: failover correctness depends on clients, not just DNS. Strong answers mention max connection lifetime, role-aware health checks, and error-driven invalidation, and question whether DNS is the right failover mechanism versus a proxy that follows the primary.

Red Flags: "Lower the TTL further" (TTL does not affect existing connections). Restarting all apps as the runbook. Assuming pool_pre_ping detects role changes.

Q49: During a traffic spike, clients see connection timeouts but the servers show low CPU. What is happening?​

Level: Senior

Scenario: A flash sale sends traffic up 8Γ—. Clients report connect timeouts and occasional resets; latency for successful requests is fine; server CPU is at 35%. netstat -s shows climbing counters for "times the listen queue of a socket overflowed" and "SYNs to LISTEN sockets dropped."

Impact: A large fraction of users cannot reach the service during the most valuable hour of the quarter.

Root Cause: Accept queue overflow. After the handshake completes, the kernel places the connection in the listen socket's accept queue until the application calls accept(). Its size is the smaller of the backlog passed to listen() and net.core.somaxconn. The server was started with a small backlog and its accept loop is slow (a single-threaded acceptor doing work before accepting the next connection). When the queue is full, Linux drops the completing ACK or SYN; clients retransmit SYNs with exponential backoff (1 s, 2 s, 4 s …), which appears as timeouts while the server looks idle.

Fix:

  1. Raise somaxconn and the application's listen backlog together.
  2. Make accepting cheap: accept in a dedicated loop, hand work off to workers.
  3. Run more worker processes per host (or more hosts) and load-test connection rate, not just request throughput.
  4. Monitor ListenOverflows / ListenDrops and the accept queue depth.
# Accept queue per listening socket: for LISTEN sockets, Recv-Q = current queue, Send-Q = max backlog
ss -ltn 'sport = :8000'

# Overflow counters
nstat -az TcpExtListenOverflows TcpExtListenDrops

# Raise the kernel cap (persist in /etc/sysctl.d/ for production)
sysctl -w net.core.somaxconn=4096
sysctl -w net.ipv4.tcp_max_syn_backlog=8192
# The application must also ask for a large backlog
import uvicorn

if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=8000, workers=4, backlog=4096)

Workflow Diagram:

SYN --> SYN queue --(handshake done)--> accept queue [#####FULL] --> accept() (slow)
|
queue full: drop --> client retransmits SYN after 1s, 2s, 4s...
|
user sees "connect timeout" while CPU is idle

Fixed: bigger accept queue + fast accept loop + more workers --> queue drains quickly

Interviewer Notes: They want the candidate to look beyond CPU, know the SYN queue vs accept queue distinction, and use kernel counters as evidence. Explaining why the effective backlog is min(listen backlog, somaxconn) is a strong signal.

Red Flags: Scaling vertically because "the server is overloaded" despite low CPU. Raising only somaxconn without changing the application's backlog. Ignoring client SYN retry behaviour when interpreting latency.

Q50: Kubernetes nodes log "nf_conntrack: table full, dropping packet." How do you handle it?​

Level: Principal

Scenario: On busy Kubernetes nodes, random connections fail and DNS lookups time out. The node kernel log shows nf_conntrack: table full, dropping packet. The affected nodes run a high-throughput API gateway that makes many short-lived connections to backends and to DNS.

Impact: Random failures across all pods on the affected nodes, including unrelated workloads, because the conntrack table is node-wide.

Root Cause: kube-proxy (iptables or IPVS mode) relies on the Linux connection tracking table to apply Service NAT. Every flow β€” including each UDP DNS query and every short-lived TCP connection β€” occupies an entry until it times out. TCP entries for closed connections linger, and UDP entries remain for their timeout even after a single request/reply. High connection churn fills the table, and once it reaches nf_conntrack_max, the kernel drops new flows.

Fix:

  • Reduce churn: connection pooling and keep-alive in the gateway; NodeLocal DNSCache to cut DNS flows through Service NAT.
  • Right-size the table: raise nf_conntrack_max (kube-proxy also sets it based on CPU count via its conntrack settings) and review relevant timeouts.
  • Monitor nf_conntrack_count / nf_conntrack_max per node and alert at around 75%.
  • At scale, consider dataplanes that reduce reliance on conntrack-based NAT.
# Current usage vs limit
cat /proc/sys/net/netfilter/nf_conntrack_count /proc/sys/net/netfilter/nf_conntrack_max

# What is filling it (needs the conntrack tool)
conntrack -L 2>/dev/null | awk '{print $1}' | sort | uniq -c # by protocol
conntrack -L -p tcp 2>/dev/null | awk '{print $4}' | sort | uniq -c # TCP entries by state

# Raise the limit (persist via /etc/sysctl.d/ or the node bootstrap config)
sysctl -w net.netfilter.nf_conntrack_max=524288
"""Node exporter-style check: exit 1 when conntrack usage crosses a threshold."""
import sys
from pathlib import Path

BASE = Path("/proc/sys/net/netfilter")

def conntrack_usage() -> float:
count = int((BASE / "nf_conntrack_count").read_text())
limit = int((BASE / "nf_conntrack_max").read_text())
return count / limit

if __name__ == "__main__":
usage = conntrack_usage()
print(f"conntrack usage: {usage:.0%}")
sys.exit(1 if usage > 0.75 else 0)

Workflow Diagram:

pod --> Service VIP --> iptables/IPVS DNAT --> needs conntrack entry
|
table at nf_conntrack_max? --yes--> drop packet (any pod on node)
| no
v
entry created, lives until timeout

Churn sources: new TCP conn per request, UDP DNS queries
Fixes: keep-alive pools + NodeLocal DNS (fewer entries) + bigger table + alerting

Interviewer Notes: Principal-level answers recognise the blast radius (node-wide, affects unrelated pods), attack churn first, and treat raising the limit as capacity planning (each entry uses kernel memory). Linking it back to DNS problems in Q42 shows systems thinking.

Red Flags: Only raising nf_conntrack_max with no churn reduction. Not knowing what conntrack is or why kube-proxy needs it. Disabling conntrack globally on Kubernetes nodes, which breaks Service NAT.