Skip to content
Tech Interview Prep
Technical interview guide

OSI & TCP/IP Models

The layered models networking is reasoned about in, physical up to application, and where common protocols and problems live.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current IETF host, IPv4, IPv6, ARP, NDP, TCP, UDP, port, ICMP, PMTUD, TLS 1.3, QUIC, and Wireshark references reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-22

How does data encapsulation and decapsulation work across the TCP/IP and OSI layers, including the specific PDU names, headers, and layer dispatch keys?

Answer

Encapsulation wraps protocol data units (PDUs) by prepending control headers (and sometimes appending trailers) as payload travels down the stack. Decapsulation reverses this on receipt by parsing the outer envelope, verifying integrity, stripping the header, and using a demultiplexing key to dispatch the inner PDU to the correct layer handler.

PDU and Layer Mapping

OSI LayerTCP/IP Layer (RFC 1122)PDU NameCore Headers / MetadataDispatch / Demux Key
7, 6, 5 (App, Pres, Sess)ApplicationData / MessageHTTP/TLS/DNS framing (e.g., TLS ContentType 23)Application port / URI / ALPN
4 (Transport)TransportSegment (TCP) / Datagram (UDP)TCP (RFC 9293) / UDP (RFC 768) header (Source/Dest Port)Destination Port (RFC 6335)
3 (Network)InternetPacket / DatagramIPv4 (RFC 791) / IPv6 (RFC 8200) header (IPs, TTL/Hop Limit)IPv4 Protocol / IPv6 Next Header
2 (Data Link)LinkFrameEthernet II header + FCS trailer (Src/Dst MAC)EtherType (e.g., 0x0800 IPv4, 0x86DD IPv6)
1 (Physical)Link / PhysicalBits / SymbolsPreamble, SFD, line coding, signal transitionsMedia signal / PHY clock

Outbound Encapsulation Flow

  1. Application Layer: A program writes a stream or message into a socket (e.g., HTTP payload wrapped in TLS 1.3 records via RFC 8446). The PDU is Application Data.
  2. Transport Layer: The kernel buffers the data and segments it according to the Maximum Segment Size (MSS). It adds a 20-byte TCP header (RFC 9293) or 8-byte UDP header (RFC 768), including source and destination ports. The resulting PDU is a TCP Segment or UDP Datagram.
  3. Internet Layer: The kernel routes the segment and attaches an IP header: a 20-byte IPv4 header (RFC 791) or a 40-byte fixed IPv6 header (RFC 8200). The protocol field is set (6 for TCP, 17 for UDP). The PDU is an IP Packet.
  4. Link Layer: The host resolves the next-hop L2 address via ARP (RFC 826) or IPv6 Neighbor Discovery (RFC 4861). It wraps the packet into an Ethernet frame: 14-byte header (preamble excluded, 6-byte dest MAC, 6-byte src MAC, 2-byte EtherType 0x0800 or 0x86DD) and 4-byte Frame Check Sequence (FCS/CRC32) trailer.
  5. Physical Layer: The network interface card (NIC) encodes the frame into physical line signals or bit streams onto the physical medium.

Inbound Decapsulation and Demultiplexing Flow

[NIC Rx] -> Frame (CRC check)
             └─> EtherType=0x0800 ──> [IPv4 Layer] (Checksum, TTL-1 if routing)
                                        └─> Protocol=6 ──> [TCP Stack] (Seq/Ack, Ports)
                                                             └─> DstPort=443 ──> [TLS/App Socket]
  1. NIC: Validates FCS; discards corrupt frames without interrupting the CPU. Strips frame delimiters.
  2. Link Demux: Inspects EtherType. 0x0800 dispatches payload to IPv4; 0x86DD to IPv6; 0x0806 to ARP.
  3. Network Demux: Verifies IPv4 checksum, validates destination IP, and checks fragmentation fields. Inspects the IPv4 Protocol (or IPv6 Next Header) field: 6 dispatches to TCP, 17 to UDP, 1 to ICMP (RFC 792).
  4. Transport Demux: TCP matches the 4-tuple (src_ip, src_port, dst_ip, dst_port) against open sockets in the connection table, handles sequence ordering, acknowledges data, strips the TCP header, and enqueues bytes into the socket receive buffer.
  5. Application: The user-space application reads raw bytes from the file descriptor, unrolls TLS records (RFC 8446), and parses the application protocol.

Common Failure Modes

  • MTU/MSS Mismatch: Outer headers expand packet size beyond path MTU. If the DF (Don't Fragment) bit is set and an intermediate router cannot forward, an ICMP Type 3 Code 4 (Fragmentation Needed) is sent (RFC 1191). If firewalls drop ICMP, this creates a Path MTU black hole.
  • Demux Key Drop: Mismatched EtherType or unrecognized IP Protocol numbers cause the receiving stack to drop the PDU silently or emit ICMP Protocol Unreachable.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Compare the OSI and TCP/IP architectural models: where do their boundaries diverge, and how do their end-to-end design assumptions differ in practice?

Answer

Core answer. OSI is a prescriptive 7-layer reference model (ISO/IEC 7498-1). TCP/IP is a descriptive 4-layer model (RFC 1122). They agree on transport and network; they diverge at the top, where OSI splits session and presentation out of application and TCP/IP folds them in, and at the bottom, where OSI separates physical from data link and TCP/IP merges both into one Link layer. The deeper difference is the design assumption. OSI's network layer was specified to offer both connectionless (CLNS) and connection-oriented (CONS) service, and its era assumed intelligent network nodes. TCP/IP assumes a dumb, best-effort datagram core with reliability, sequencing and flow control pushed to the transport endpoints: the end-to-end principle (Saltzer, Reed, Clark, 1984).

Where the boundaries diverge.

OSI layerTCP/IP layer (RFC 1122)What moved
7 Application, 6 Presentation, 5 SessionApplicationSession and presentation are not kernel boundaries; TLS 1.3 (RFC 8446) and serialization live in user-space libraries
4 TransportTransportSame split; TCP (RFC 9293), UDP (RFC 768)
3 NetworkInternetSame split; IP (RFC 791 / RFC 8200), ICMP (RFC 792)
2 Data Link, 1 PhysicalLinkMerged into one interface boundary: driver plus NIC

What breaks in practice. The clean layering is violated by real deployments, and that is the part interviewers probe.

  • NAT rewrites a transport-layer field from a network-layer device. A NAT (RFC 3022) reads and mutates the TCP/UDP source port as a packet crosses it. That is a layer-3 device acting on layer-4 state. Consequence: IPsec AH, which authenticates the IP header including addresses, cannot survive NAT; FTP and SIP need application-layer gateways to work through it.
  • Ossification. Firewalls, load balancers and deep-packet inspection read TCP headers, so a new transport protocol cannot deploy directly on IP: middleboxes drop it. QUIC (RFC 9000) is the workaround: it runs over UDP and encrypts its own headers so middleboxes cannot inspect them.
  • QUIC's own failure mode. Because it uses UDP, restrictive enterprise networks that block or throttle UDP 443 force a fallback to TCP/TLS, losing QUIC's 0-RTT and head-of-line-blocking avoidance. Detect it by measuring connection setup time and protocol negotiated in logs.
  • ICMP and ARP already cross boundaries. ICMP is a network-layer protocol carried inside IP datagrams; ARP/NDP bridge Link and Internet addressing. The strict SAP-only interface OSI describes does not exist in the deployed stack.

Deciding criteria. Use OSI when you need shared vocabulary for troubleshooting or teaching: "is this a layer-2 or layer-3 problem?" isolates a fault fast, and its session/presentation split is a useful checklist for where state lives. Use TCP/IP when you are designing or debugging an actual protocol, because RFC 1122 is what is implemented. The comparison stops mattering once you are inside a running stack: there is no session layer to inspect, and the Link layer is one boundary, not two.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Compare the service each layer provides: which layers are connectionless and which are connection-oriented, and why does the network layer offer only best-effort delivery while the transport layer offers both TCP and UDP?

Answer

Core (first 90 seconds). The link and network layers are connectionless and best-effort; the transport layer is where an application chooses its guarantees. IP (RFC 791, RFC 8200) provides addressing, forwarding and a hop limit, and nothing else: it explicitly permits datagrams to be lost, duplicated, delayed, reordered, and delivered without notification. TCP (RFC 9293) adds connection state and, with it, in-order reliable byte-stream delivery, duplicate suppression, flow control and congestion control. UDP (RFC 768) adds ports, a length and a checksum: message boundaries preserved, no ordering, no retransmission, no rate control.

LayerConnection stateDelivery guaranteeOrderingDuplicatesFlow / congestion control
Link (Ethernet)nonenone end-to-endnonepossiblenone (802.11 retries are per-hop)
Network (IP)nonebest-effort; may drop silentlynonepossiblenone
Transport: TCPper-connection, keyed on the 4-tuplereliable, or the connection resetsin-order byte streamsuppressedreceive window + congestion window
Transport: UDPnonebest-effortnonepossiblenone

Why the network layer is only best-effort. Three reasons, and interviewers want at least two. First, the end-to-end argument: reliability at every hop is redundant work. A packet can still be dropped in a router's output queue, or the path can change mid-flight, so hop-by-hop reliability never adds up to end-to-end reliability. Second, state: if routers held per-flow state, every routing reconvergence would need to re-establish it, and forwarding would stop being a stateless lookup at line rate. Third, heterogeneity: a path can mix fibre, Wi-Fi and a congested transit link, and no single per-hop policy fits all of them. Note that the link layer is connectionless too; Ethernet has no ACKs. Wi-Fi retransmits, but that is a per-hop repair, not a guarantee the application can rely on.

Why the transport layer offers both. TCP's guarantees cost something: one RTT before the first data byte, kernel state per connection, retransmission delay, and head-of-line blocking. One lost segment stalls every stream multiplexed over it. UDP costs nothing and guarantees nothing, which is exactly right for request/response protocols and for anything that wants to define its own semantics. QUIC (RFC 9000) is the clearest example: it runs over UDP, reimplements loss recovery, ordering and congestion control in userspace, and gets per-stream ordering plus 0-RTT resumption. Reliability where the application wants it, not where the kernel puts it.

Failure modes. (1) Treating send() returning as delivery: IP and UDP both drop silently, so the application needs its own timeout and idempotency; detect it by comparing bytes sent against bytes received and watching application-level timeouts. (2) Assuming UDP is simply "faster": an application that blasts datagrams at line rate causes queue drops and loss collapse. QUIC-style congestion control is not optional. (3) NAT state: UDP bindings typically expire in tens of seconds versus hours for established TCP, so long-lived UDP flows need keepalives. (4) PMTU black holes: IPv6 routers do not fragment, and filtering ICMPv6 Packet Too Big (RFC 8201) silently kills large packets. Visible as a connection that completes its handshake then stalls on the first full-size segment.

Arithmetic worth stating. With a 30 ms RTT and 1% loss, a single TCP connection's throughput is roughly (MSS/RTT) × 1.22/√p ≈ (1460/0.03) × 12.2 ≈ 4.7 Mbit/s: illustrative, but it shows why loss, not bandwidth, is usually the limit, and why an application that needs more opens parallel connections or moves to QUIC.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Which OSI layer does each of these operate at: hub, switch, router, firewall, load balancer, TLS terminator, ARP, ICMP, TCP, HTTP, and how does that layer determine what the device can inspect, forward, or block?

Answer

One rule decides every case: a device can only act on fields it can parse, and it can only parse up to the layer where it forwards or terminates. Everything above that boundary is opaque payload.

ItemLayerWhat it can inspect / act on
Hub1 PhysicalNothing. Repeats symbols out every port; one collision domain, no addressing.
Switch2 Data LinkDestination MAC, EtherType, 802.1Q VLAN tag. Learns source MAC into the CAM table, floods unknown unicast and broadcast.
Router3 NetworkDestination IP prefix, TTL/Hop Limit, DSCP. Rewrites the L2 header at every hop.
Stateless ACL / classic firewall3–45-tuple only: src/dst IP, src/dst port, protocol. No payload.
Stateful firewall / NGFW3–7Adds connection state; reaches L7 only by proxying or deep packet inspection.
L4 load balancer45-tuple hash. Never sees HTTP.
L7 load balancer7Path, Host, cookie, header, because it terminates TCP and parses the request.
TLS terminatorbetween 4 and 7SNI in the ClientHello (plaintext in TLS 1.3 per RFC 8446 unless ECH); HTTP only once it holds the session keys.
ARP2/3 boundaryLink-scoped, EtherType 0x0806 (RFC 826). Carries IPv4 addresses but never crosses a router.
ICMP3Carried inside IP, Protocol 1; ICMPv6 is Next Header 58 (RFC 4443). Routers generate it.
TCP4Ports, flags, sequence numbers; IP Protocol 6 (RFC 9293).
HTTP7Method, path, headers.

Two entries are the ones candidates get wrong. ARP is not a network-layer protocol even though it resolves IP addresses: it is link-scoped, so a host ARPs for its default gateway, never for an off-subnet destination. ICMP is not a transport protocol even though it looks like one: it rides inside IP with no ports, so a router can drop it without touching any TCP flow.

Worked trace: L4 load balancer and sticky sessions. Three backends behind an L4 LB hashing the 5-tuple. A client at 10.0.2.7 opens six connections from source ports 40001–40006. Hash mod 3 gives 0,1,2,0,1,2: two connections per backend. The session cookie written by backend 0 is present for two of six requests; the other four land on backends 1 and 2 with no session and re-authenticate. The fix is not a bigger LB: it is an L7 LB that reads the cookie, or a shared session store. Detection: backend logs show a ~67% session-miss rate while the LB reports every backend healthy.

Failure modes and how you catch them.

  • "Block that URL path on the router ACL." A router ACL matches L3/L4 fields only. The rule will be accepted and the traffic will still pass. Detect by testing the path end to end, not by reading the config.
  • "The switch is dropping our IP." A pure L2 switch never reads the IP header. The drop is at the router, the host firewall, or a VLAN mismatch: check the CAM table and VLAN assignment first.
  • ARP requests for an off-subnet address in a capture mean a wrong netmask on the sender, not a broken router.
  • ICMP filtered anywhere on the path breaks Path MTU Discovery: small packets pass, 1500-byte DF packets vanish. Confirm with ping -M do -s 1472 and a capture showing the ICMP Fragmentation Needed never arriving.
  • SNI-based routing works without decryption because the ClientHello is plaintext; path-based routing does not, so a "route on /api" rule on a non-terminating proxy silently falls back to the default backend.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Explain sockets, listening ports, and ephemeral ports.

Answer

A socket is a kernel object that names one endpoint of a conversation. For TCP, a connection is identified by the 4-tuple ((local IP, local port, remote IP, remote port)) not by the server's port alone. The kernel demuxes every arriving segment by looking that tuple up in its connection table.

A listening socket is bound to a local address and port and sits in LISTEN. It has no remote endpoint. When a SYN arrives, the kernel creates a new socket for that connection, the accepted socket, carrying the full 4-tuple. The listening socket stays in LISTEN and keeps accepting. That is why one process on port 443 serves thousands of concurrent connections: they are distinct sockets, not distinct ports.

Ephemeral ports are the client-side source ports the kernel assigns when you call connect() without binding first. On Linux the range comes from /proc/sys/net/ipv4/ip_local_port_range, default 32768 60999: 28,232 ports.

Python
# Python 3.11
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 8080))   # wildcard: every IPv4 interface
s.listen(128)               # accept-queue length
conn, peer = s.accept()     # conn is a NEW socket with the full 4-tuple
print(s.getsockname())      # listening socket
print(conn.getsockname())   # accepted socket, local side
print(peer)                 # accepted socket, remote side

Trace it with a client connecting from 203.0.113.7:51234 to 10.0.0.5:8080. s.getsockname() prints ('0.0.0.0', 8080): the wildcard bind, unchanged. conn.getsockname() prints ('10.0.0.5', 8080): the kernel resolved the wildcard to the interface the SYN arrived on. peer prints ('203.0.113.7', 51234). Two connections from the same client to the same server port differ only in the client's ephemeral port, and that is enough to keep them apart.

Mechanically, the kernel keeps a hash table keyed on the 4-tuple. A segment matching an established entry goes to that socket's receive queue. A SYN with no matching entry goes to the listening socket's accept queue, whose length is the listen() backlog capped by net.core.somaxconn (4096 since Linux 5.4; 128 before). When the queue is full the kernel drops the SYN by default, so the client retransmits.

OptionWhat it actually permitsWhen to use
SO_REUSEADDRBind a port still in TIME_WAIT; bind a specific address while a wildcard bind exists on the same portAlmost always on servers, so a restart does not fail with EADDRINUSE
SO_REUSEPORTMultiple live sockets on the exact same address:port; the kernel hashes the 4-tuple to pick oneMulti-process accept fan-out, one worker per core

Failure modes worth naming. Source-port exhaustion: a client opening many connections to one remote IP:port is capped near 28k concurrent tuples, fewer once TIME_WAIT holds them. connect() fails with EADDRNOTAVAIL; ss -s shows the TIME_WAIT count climbing. Fix with connection pooling or more destination IPs. TIME_WAIT: the side that closes first holds the tuple for 60 seconds on Linux (TCP_TIMEWAIT_LEN), so a late segment from the old connection cannot land on a new one with the same tuple. Dual-stack: Linux defaults net.ipv6.bindv6only=0, so binding :: also accepts IPv4 via ::ffff: mapped addresses; binding 0.0.0.0 and :: separately can collide. Load balancers: an L4 proxy terminates the client connection and opens its own to the backend, so every backend connection shares the LB's IP as remote and the backend's ephemeral range becomes the limit.

Finally, DNS returning several A/AAAA records means a successful connect() to one address proves nothing about the others: they may be down or unhealthy. Health checks have to hit every endpoint, not just the first that answered.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Explain what addresses a host uses for an off-subnet destination.

Answer

Assumptions: IPv4 host 10.0.1.5/24 on eth0, default route via 10.0.1.1, destination 10.0.2.9. IPv6 is the same shape with NDP in place of ARP.

The 90-second answer. The host never puts the gateway's address in the packet. It keeps the remote destination IP in the IP header and rewrites only the link-layer address, hop by hop. Longest-prefix match picks the route; the route names an egress interface and a next-hop IP; the host resolves that next-hop IP to a MAC with ARP (IPv4, RFC 826) or NDP (IPv6, RFC 4861); it emits a frame whose destination MAC is the gateway's. The source IP is chosen separately, by RFC 6724 rules, not by the route's next hop.

FieldValueWhere it comes from
IP dst10.0.2.9unchanged end to end
IP src10.0.1.5source-address selection
Frame dst MACgateway's MACARP/NDP for 10.0.1.1
Frame src MACeth0's MACegress interface
TTL64 → 63decremented by the first router, not the host
$ ip route get 10.0.2.9
10.0.2.9 via 10.0.1.1 dev eth0 src 10.0.1.5
$ ip neigh show 10.0.1.1
10.0.1.1 dev eth0 lladdr 52:54:00:12:34:56 REACHABLE

So the frame on the wire is dst 52:54:00:12:34:56, src eth0's MAC, carrying an IP packet 10.0.1.5 → 10.0.2.9. The gateway repeats the same decision for 10.0.2.9 and rewrites the L2 header again; the IP addresses stay untouched until a NAT device changes them.

Why it works this way: IP is the end-to-end identifier, L2 is per-link. A host cannot address a MAC on a link it is not attached to, so it hands the packet to a router that is on-link.

Alternatives, and when they apply.

  • Proxy ARP (RFC 1027): the host ARPs for 10.0.2.9 itself and a router answers with its own MAC. Common on legacy subnets and some overlay setups; it hides the subnet boundary and turns the ARP table into a routing table, which is why it is usually disabled.
  • On-link assumption: some stacks, when no route matches, assume the destination is on-link and ARP for it directly. Linux instead fails the send with ENETUNREACH. This is a real portability difference when a default route is missing.
  • Point-to-point links (PPP, /31, tunnels): no next-hop MAC exists; the packet is handed straight to the interface.

Source-address selection. RFC 6724 picks the source independently: rule 8 prefers the candidate whose prefix matches the destination longest, rule 9 prefers an address on the outgoing interface. That is why a host holding both 10.0.1.5 and 192.168.1.x uses 10.0.1.5 for 10.0.2.9.

Failure modes and how to detect them.

  • Missing or stale neighbor entry: the first packets are queued while ARP/NDP resolves; with no reply the kernel returns EHOSTUNREACH and emits ICMP host unreachable. Detect with ip neigh show in FAILED/INCOMPLETE state and the ip -s neigh counters.
  • Neighbor table exhaustion: net.ipv4.neigh.default.gc_thresh3 (default 1024) caps entries; past it resolution fails and dmesg logs "neighbour table overflow". Raise it on hosts with many peers.
  • Blackholed default route: the host ARPs the gateway and sends happily, nothing returns. ip route get still shows the via, but traceroute stops at the first hop and interface counters show tx climbing with rx flat.
  • Wrong egress interface or VLAN: the route points at a dev that does not carry the gateway's subnet, so ARP gets no reply. Compare the dev from ip route get against ip -br addr.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Use TTL/Hop Limit and traceroute evidence carefully.

Answer

Core answer. TTL (IPv4) and Hop Limit (IPv6) are the same 8-bit field, and their only job is to bound how long a packet circulates: they are not a distance measure. Traceroute exploits the drop rule: a probe with TTL=1 reaches the first router, which decrements to 0, drops it, and returns ICMP Time Exceeded (IPv4 type 11 code 0; ICMPv6 type 3 code 0). Repeat with TTL=2, 3, … until the destination answers. Every hop in the output is an inference from an ICMP error, so each is a hypothesis until corroborated.

Assumptions to state: ICMP error generation is enabled along the path, the path is stable over the probe window, and you know the sender's initial TTL before doing arithmetic on a received TTL.

The numbers. A router decrements before forwarding; if the result is 0 it drops and generates the error. Initial values are sender-dependent:

OriginDefault initial TTL / Hop Limit
Linux64 (net.ipv4.ip_default_ttl, net.ipv6.conf.default.hop_limit)
Windows128
Cisco IOS, locally originated255

A capture showing TTL 57 from a Linux host means 7 hops (64 − 57). The same 57 from a Windows host would mean 71 hops: impossible, so you've misidentified the origin. GTSM (RFC 5082) is the one place the value is load-bearing: BGP peers send TTL 255 and reject anything less, which is why multi-hop BGP needs explicit configuration.

Tool defaults: Linux traceroute sends UDP to ports starting at 33434, 3 probes per hop, 30 hops max (-q 3 -m 30); Windows tracert uses ICMP Echo with the same counts. -I and -T switch to ICMP and TCP; mtr and paris-traceroute keep per-flow state so ECMP doesn't scramble the picture.

Why the output lies.

  • ECMP: routers hash per flow, usually on the 5-tuple. Three probes at one TTL with different UDP source ports can take three paths, so you see different addresses at one TTL, or the same address reappearing later: a phantom loop.
  • Tunnels and MPLS: the ingress copies the inner TTL into the outer header; transit routers decrement the outer TTL and never see the inner one, so the tunnel collapses to one hop. On Cisco IOS, TTL propagation for forwarded traffic is off by default, so an MPLS core shows only the PE routers.
  • Rate limiting: ICMP error generation is rate-limited (Linux net.ipv4.icmp_ratelimit, default 1000 ms), so probes get no reply and print * even though the router is healthy.
  • Asymmetric return: the Time Exceeded comes back from the router, and its source address is the egress interface toward you, not the interface the probe arrived on. The RTT is round trip to that router, not one-way to the hop.
  • Filtering: no ip unreachables or a firewall dropping ICMP gives * for the last hops while the destination is reachable over TCP.

Worked trace (hypothetical):

$ traceroute -q 3 -m 8 203.0.113.10
 1  10.0.0.1        0.41 ms  0.39 ms  0.40 ms
 2  172.16.4.1      1.20 ms  1.19 ms  1.22 ms
 3  198.51.100.9    8.77 ms  8.69 ms  8.81 ms
 4  198.51.100.14   9.02 ms  8.95 ms  9.11 ms
 5  198.51.100.9    9.44 ms  9.38 ms  9.50 ms
 6  203.0.113.10   12.44 ms 12.39 ms 12.40 ms

.9 at hop 3 and again at hop 5 looks like a loop. It isn't: hops 3–5 are one ECMP pair and the probes hashed onto different members. Confirm by re-running with a pinned source port, or with paris-traceroute, which holds the flow constant. A real loop shows the same address at every TTL, RTT climbing monotonically, and the destination never answering.

When not to trust it.

EvidenceTells youBlind to
One tracerouteOne flow's forward path, one momentECMP, rate limits, return path
Repeated traces, fixed flowStable vs flapping pathTunnels, MPLS core
Destination reachabilityEnd-to-end worksWhere it went
Looking glass / BGP dataControl-plane viewForwarding reality
Capture at both endsActual TTLs, actual pathIntermediate hops

Use traceroute to find where to look, then confirm with captures and route data. Never quote a hop count or one-way latency from a single trace.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Compare IPv4 and IPv6 fragmentation behavior.

Answer

Two things decide this: who is allowed to fragment, and what the sender knows about the path.

Assumptions: Ethernet MTU 1500, IPv4 header 20 bytes, IPv6 fixed header 40 bytes, no extension headers beyond the Fragment header.

Core answer. IPv4 lets any router on the path fragment a datagram that exceeds the next link's MTU, unless the DF bit is set. IPv6 removed that: routers never fragment, and only the source may, using a Fragment extension header. Everything else (PMTUD, ICMP handling, firewall behavior) follows from that one change.

Mechanism. The IPv4 header carries a 16-bit Identification, a 3-bit Flags field (DF, MF), and a 13-bit Fragment Offset counted in 8-byte units. A router that must forward a 1500-byte datagram onto a 1400-byte link splits it, sets MF on all but the last fragment, and copies the same ID so the destination can reassemble. Because the offset is in 8-byte units, every non-final fragment's payload must be a multiple of 8. With DF set, the router instead drops the packet and returns ICMP Type 3 Code 4 (Fragmentation Needed): that message is what IPv4 PMTUD runs on.

IPv6 has none of those fields in the fixed header. A source that wants to fragment inserts an 8-byte Fragment header (Next Header 44) with a 13-bit offset in 8-byte units, an M flag, and a 32-bit Identification. Routers that receive an oversized packet drop it and return ICMPv6 Packet Too Big (Type 2), carrying the next hop's MTU. That message is the basis of IPv6 PMTUD, specified in RFC 8201.

Worked arithmetic. A 4000-byte UDP payload on a 1500-byte Ethernet MTU:

  • IPv4: 4000 + 8 UDP + 20 IP = 4028 bytes. Fragments: 1480 (offset 0, MF=1), 1480 (offset 185, MF=1), 1040 (offset 370, MF=0).
  • IPv6: 4000 + 8 UDP = 4008 bytes of fragmentable payload. Fragments: 1448 (offset 0, M=1), 1448 (offset 181, M=1), 1112 (offset 362, M=0).

Trade-offs. IPv4 router fragmentation needs no endpoint cooperation and still works when PMTUD is broken, but it costs router CPU and memory, and reassembly happens at the destination where fragments may arrive over different paths. IPv6 pushes that cost to the endpoints, keeps routers stateless and fast, and gives a 32-bit ID instead of 16: far fewer collisions at high throughput. The price is a hard dependency on ICMPv6: if Packet Too Big is filtered, the sender never learns the smaller MTU.

Failure modes. PMTUD black hole: small packets pass, large ones vanish, retransmits repeat at full size, and no ICMP appears in the capture. IPv6 Fragment headers dropped by middleboxes that only whitelist common next headers. IPv4 fragment-overlap attacks (teardrop) and reassembly-buffer exhaustion from many partial fragments. IPv4's 16-bit ID wraps quickly on fast links, so fragments from different datagrams can collide.

When not to fragment. UDP apps that emit large datagrams. Size the payload to 1280 bytes (the IPv6 minimum MTU) or below, or use TCP, and let PMTUD do its job.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Diagnose and mitigate a Path MTU failure.

Answer

Assumptions first. I'd ask two things: IPv4 or IPv6, and is the symptom size-dependent. Do small exchanges (SYN, TLS handshake, a short ping) succeed while bulk transfer stalls? That pattern points at PMTUD, not routing or loss. I'd also ask whether the path crosses a tunnel or IPsec.

Core answer. PMTUD works by having the sender set DF (IPv4) or rely on the fact that IPv6 routers never fragment, then send at the current path MTU. When a router can't forward a packet that size, it drops it and returns ICMP Fragmentation Needed (IPv4 Type 3 Code 4) or ICMPv6 Packet Too Big (Type 2), carrying the next-hop MTU. The sender lowers its MTU and retransmits. If that ICMP is filtered anywhere along the path, the sender never learns: it keeps retransmitting the same oversized segment and the connection stalls. That is a PMTU black hole.

Reproduce and localize. Probe with DF and a binary search. IPv4: ping -M do -s 1472 10.0.0.1 (1472 + 28 = 1500). IPv6: ping -6 -s 1452 (1452 + 48 = 1500). Find the largest size that passes, then compare it against the expected MTU for the path. If the largest passing size is exactly 1500 minus a known encapsulation overhead, you have found the tunnel.

Overheads worth checking: GRE 24 bytes (20 outer IPv4 + 4 GRE) → 1476; VXLAN 50 → 1450; PPPoE 8 → 1492; 6in4 20 → 1480; WireGuard 60 for IPv4 → 1440; IPsec ESP tunnel mode roughly 50–73 depending on cipher and auth. TCP MSS is MTU minus 40 (IPv4) or 60 (IPv6), so a 1500 path gives 1460/1440.

Offload illusion. tcpdump on the sending host can show 64 KB "packets" because TSO/GSO segment in the NIC, and on the receiver GRO coalesces them back. Captured sizes then don't reflect what is on the wire. Disable with ethtool -K eth0 tso off gso off gro off, or capture at a tap/mirror, before trusting any size.

Mitigation, with deciding criteria.

  • Restore ICMP: the correct fix. Allow Type 3 Code 4 (IPv4) and Type 2 (IPv6) through every firewall on the path. Choose this when you control the path; it fixes UDP and TCP alike.
  • MSS clamping: iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu. Works when you can't fix ICMP and the traffic is TCP. Wrong choice for UDP/QUIC, and it must be applied where the SYN crosses: clamping at one end only helps if that end's SYN is clamped. Document the scope; a hardcoded --set-mss 1400 that is too low costs throughput on every connection.
  • PLPMTUD (RFC 8899 for IPv6, RFC 4821): probe with DF and binary-search without needing ICMP. Choose when ICMP is unfixable and the traffic isn't TCP. Costs probing time and needs stack support; Linux exposes net.ipv4.tcp_mtu_probing (0 off, 1 on black-hole detection, 2 always).

Failure modes and detection. The signature is a connection that completes its handshake and then hangs on the first large write: SSH banner then freeze, TLS handshake then stalled page. It is intermittent because ECMP and route changes move traffic onto paths with different MTUs, so a fix on one path doesn't hold. Detection: ss -ti shows retransmits and a stuck MSS; tcpdump shows repeated same-size retransmits with no ICMP reply.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Troubleshoot IPv6 neighbor and router discovery.

Answer

First, split the problem. Router discovery (RD) is multicast: the host sends Router Solicitations to ff02::2 and learns prefixes and a default route from Router Advertisements. Neighbor discovery (ND) is mostly unicast: Neighbor Solicitation/Advertisement resolves a link-layer address, and Duplicate Address Detection reuses NS/NA before an address is usable. Ask which one is broken: no address or no default route is RD; an address that exists but traffic to a specific peer fails is ND.

Router discovery. A host sends up to 3 RS at 4 s intervals (RFC 4861 MAX_RTR_SOLICITATIONS/RTR_SOLICITATION_INTERVAL), then waits for periodic RAs. Default MaxRtrAdvInterval is 600 s, and the Router Lifetime in the RA defaults to 1800 s: three intervals. If RAs are filtered (ICMPv6 type 134), the host gets no default route and no SLAAC prefix: ip -6 route show default is empty and ip -6 addr shows only link-local. If a router advertises Router Lifetime 0 it withdraws itself, so a default route that vanishes every few minutes points at a router flapping or a lifetime shorter than the advertisement interval. RA Guard (RFC 6105) drops RAs arriving on host-facing ports; if it is enabled on a port that actually faces a router, legitimate RAs are dropped and every host behind it loses its default route.

Neighbor discovery and DAD. Before using an address, the host sends an NS from :: to the solicited-node multicast ff02::1:ffXX:XXXX for its tentative address. With Linux defaults dad_transmits=1 and a 1000 ms retransmit timer, DAD finishes in about 1 s; any NA in that window means a duplicate, the address stays tentative, and the kernel logs a duplicate-address event. If ICMPv6 types 135/136 are filtered, DAD never completes and the address sits tentative forever: ip -6 addr shows the tentative flag and NS goes out with no NA returning.

Neighbor cache states explain intermittent failures. After an entry is confirmed it is REACHABLE for ReachableTime (Linux default 30 s), then STALE. On the next send it enters DELAY for 5 s, then PROBE, sending up to 3 unicast NS at 1 s intervals; no reply deletes the entry and the next packet restarts at INCOMPLETE. A VM migration or failover that changes a MAC leaves a STALE entry that only fails when probed: ip -6 neigh show shows INCOMPLETE or FAILED, and the symptom is a few seconds of loss on first contact.

The trap that catches most people: NDP messages must arrive with hop limit 255, and receivers drop them otherwise. A proxy, load balancer, or tunnel that rewrites hop limit breaks NDP silently while ping still works. Check with tcpdump -ni eth0 icmp6 and ip6[40] == 135 and read the hop limit.

Trade-offs. RA Guard stops rogue RAs but must be disabled on router-facing ports, or it causes the outage it was meant to prevent. Blocking "ICMP" wholesale at a firewall is the common root cause; you must allow 133–137, and keep ICMPv6 type 2 (Packet Too Big) separate because it drives path-MTU, not discovery. With multiple routers, RFC 4191 preference (High/Medium/Low) decides which default route wins; equal preference means the host picks one and does not load-balance, so a "missing" route may just be a lower-preference router.

Fast checks: ip -6 addr (tentative/deprecated flags), ip -6 route show default, ip -6 neigh show dev eth0, and sysctl net.ipv6.conf.eth0.accept_ra net.ipv6.conf.eth0.dad_transmits. If accept_ra is 0 or the interface is forwarding with accept_ra=1, the host ignores RAs entirely: a config cause that looks exactly like a filtered RA.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Create an ICMP filtering policy.

Answer

Assumptions. Stateful edge firewall between an enterprise network and the internet, dual-stack, general-purpose hosts. "ICMP" means ICMPv4 (RFC 792) and ICMPv6 (RFC 4443). Rules are evaluated top-down, first match wins, default deny.

Core answer. Default deny, then permit the ICMP that IP itself needs to work, and rate-limit the rest. RFC 4890 splits ICMPv6 into "not to be dropped", "to be dropped", and "to be dropped subject to rate limiting"; the error messages and NDP sit in the first group. ICMPv4 can be filtered harder because IPv4 has no NDP: permit errors only when they match a flow the firewall has already seen.

OrderMatchAction
1ICMPv6 types 1,2,3,4 (errors), any codepermit
2ICMPv6 133/134/135/136 (RS, RA, NS, NA), hop limit 255permit; rate-limit 135/136
3ICMPv6 128/129 (echo)permit; 10 pps per source, burst 20
4ICMPv4 types 3,11,12 (errors)permit only if related to an existing flow
5ICMPv4 0/8 (echo)permit; 10 pps per source
6ICMPv4 5 (redirect), 4 (source quench, deprecated by RFC 6633)deny
7Unknown typesdeny
8Defaultdeny

Why the embedded packet matters. ICMPv4 errors carry the original IP header plus the first 8 bytes of payload (RFC 792); ICMPv6 errors carry as much of the original packet as fits under the minimum MTU (RFC 4443). For TCP those 8 bytes are source port, destination port, and sequence number. An off-path attacker who can guess or observe a connection's 4-tuple can forge a Destination Unreachable (type 3) or Time Exceeded (type 11) with a matching embedded header and make the host abort a healthy connection: the classic blind ICMP reset. Hosts trust it because the error is matched to the connection table by the embedded tuple, not authenticated. RFC 5927 recommends the host validate the embedded sequence number against the receive window and check the ICMP source is the connection's peer; a firewall cannot do the window check, so it does the next best thing: pass only errors that are "related" to a flow it has already seen, and drop unsolicited errors.

Trade-offs. Drop-all-ICMP is the tempting alternative and it is wrong: dropping ICMPv6 breaks IPv6 outright (no NDP, no PMTUD), and dropping ICMPv4 type 3 code 4 or ICMPv6 type 2 creates PMTUD black holes where small packets pass and large ones vanish. The other extreme, permit all ICMP, reopens the forgery and flood surface. The middle: permit error types unconditionally for IPv6, related-only for IPv4, rate-limit echo and NDP solicitations, deny redirects and deprecated types. Stricter filtering is wrong on-path inside a single trust domain, where you can permit more and lean on uRPF.

Failure modes and detection. PMTUD black hole: the TCP handshake succeeds, then stalls on the first full-size segment; watch counters on dropped type 3 code 4 / type 2 and reproduce with ping -M do -s 1472. NDP breakage: ip -6 neigh shows INCOMPLETE/FAILED; watch counters on dropped 135/136. Spoofed errors: uRPF (BCP 38 / RFC 2827 ingress filtering) drops most; alert on per-source ICMP error spikes. Flood: echo above 10 pps per source.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and troubleshoot a protocol through NAT.

Answer

What I'd say first

Assume a stateful NAT between two endpoints we control, no ALG, and no control over the NAT vendor. The design rule that follows: the client always initiates, the flow is long-lived, and the protocol carries its own session identity so a remapped port doesn't break the session. Then pick the keepalive interval from the shortest idle timer on the path, not from a guess.

Mapping and filter are two different things

A NAT keeps a mapping (inside tuple → outside tuple) and a filter (who may send back through it), with separate timeouts. Endpoint-independent mapping (RFC 4787) means the same inside port maps to the same outside port regardless of destination: that's what lets a peer learn your address once. Address-dependent filtering means only the host you sent to can reply. Most cloud NATs are endpoint-independent mapping with address-dependent filtering.

Timers are per-transport and vary by orders of magnitude:

PathUDP idleTCP established idle
RFC 4787 / RFC 5382 recommendation≥ 2 min2 h 4 min
Linux conntrack default30 s (120 s once a reply is seen)432000 s (5 days)
AWS NAT Gateway30 s350 s

So the binding constraint is usually UDP at 30 s. A keepalive every 15 s keeps the mapping alive on all three.

Trade-off: keepalive interval

Halving the interval doubles the packet rate. At 15 s, one 60-byte keepalive per client is 5,760 packets/day, ~0.35 MB/day; 100k clients is ~34 GB/day of pure keepalive. If the protocol is TCP, don't add an application keepalive at all: TCP keepalive at 60 s, or a read timeout that tolerates 350 s idle, is enough, and you avoid the UDP tax. Deciding criterion: use UDP keepalives only when the flow is genuinely idle for long stretches; if the app already sends every few seconds, the keepalive is redundant.

Port capacity

A NAT IP has a bounded port range per destination. AWS NAT Gateway: 55,000 simultaneous connections to one destination IP. 100k clients all talking to one backend need ≥ 2 NAT IPs, or the protocol must multiplex many sessions over one flow. Churn matters more than count: a mapping held for 5 days (Linux TCP) exhausts ports faster than one released in 30 s.

Failure modes and how you see them

  • Idle expiry: the server sees the flow stop while the client thinks it's up. Detect by comparing client send timestamps to server receive gaps; a gap equal to the NAT timer is the signature.
  • Port exhaustion: new connections fail with SYN timeouts while established ones keep working. Detect via NAT connection-count metrics and conntrack -C against nf_conntrack_max.
  • Hairpin: two clients behind the same NAT can't reach each other via the public address unless hairpin is enabled. Detect by testing inside-to-inside through the external VIP.
  • Failover: a NAT failover remaps ports, so the server's cached tuple is stale. Detect by correlating endpoint captures with NAT translation logs on the same 5-tuple.

Troubleshooting trace

Client sends UDP to 203.0.113.10:4433 every 60 s. The server sees nothing after the first packet. On the client host, conntrack -L -p udp shows the entry marked [UNREPLIED] with a 30 s timeout: the server's reply never came back, so the filter never opened and the mapping expired between sends. Fix: send every 15 s and have the server reply to every keepalive, which moves the entry to the seen-reply state (120 s on Linux). That's the whole diagnosis: mapping timeout, not a routing problem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design an application around IP's actual guarantees.

Answer

Core answer (first 90 seconds). IP gives you exactly one guarantee: a best-effort attempt to move a datagram from one interface to another. RFC 791 and RFC 8200 define no delivery confirmation, no ordering, no duplicate suppression, and no retransmission. The IPv4 header checksum covers the header only, not the payload; IPv6 dropped the header checksum entirely. So the design question is never "does IP deliver this?": it is "which guarantees do I buy above IP, and where do I put the boundary?"

Pick the transport by what the application actually needs:

  • Ordered byte stream, one connection, mature tooling → TCP. You get ordering, retransmission, flow control, and congestion control. You pay for head-of-line blocking: one lost segment stalls every later byte until it is retransmitted.
  • Ordered stream or independent streams, encrypted by default, mobile networks → QUIC. It runs over UDP, so IP still drops and reorders, but QUIC packet numbers are monotonic and never reused, which removes TCP's retransmission ambiguity. A lost packet only stalls its own stream, not the others.
  • Datagrams where a late answer is worthless → UDP plus application logic. Live voice, game state, telemetry. You accept loss and build your own deadlines.

Mechanism, and why the choice matters. TCP's retransmission timer starts at an initial RTO of 1 second (RFC 6298) and backs off exponentially; fast retransmit fires after three duplicate ACKs. On a path with 1% loss and a 100 ms RTT, that means a stalled stream can wait a full second before recovery even begins. QUIC recovers faster because it can distinguish a new packet from a retransmitted one by packet number, so it does not have to guess. UDP gives you neither, so a request/response protocol over UDP needs its own sequence number, its own timeout, and its own duplicate suppression: otherwise a retransmitted request is processed twice.

Fragmentation is where naive designs break. Take a 3000-byte UDP payload on a 1500-byte MTU path. IPv4 fragments it into 1480 + 1480 + 40 bytes of data. If the middle fragment is lost, the receiver holds the other two until the reassembly timer expires (Linux ipfrag_time defaults to 30 s), then discards all three. The sender gets no signal unless an ICMP Fragmentation Needed message comes back, and those are frequently filtered. The fix is to keep datagrams under the path MTU (1280 bytes is the safe IPv6 floor; 576 is the IPv4 minimum reassembly buffer) or to let TCP/QUIC handle segmentation.

Failure modes and how you detect them.

FailureSymptomDetection
Silent datagram lossRequest sent, no reply, no errorApplication-level timeout + retry counter
Duplicate deliverySame order charged twiceIdempotency key on the write path; count duplicates in logs
ReorderingStale state overwrites fresh stateMonotonic version/sequence number per record
Fragmentation black holeSmall requests work, large ones hangCompare success rate by payload size; tracepath for PMTU
Asymmetric routingReply arrives on a different path, stateful firewall drops itConnection resets with no server-side log

When not to use each. Do not use raw UDP for anything that must be ordered and complete: you will rebuild TCP badly. Do not use TCP for a real-time stream where a 1-second retransmit stall is worse than a dropped frame. Do not assume QUIC is free: it needs UDP to pass the firewall, and some corporate networks block UDP/443 outright.

The rule that ties it together. Never infer application success from the fact that a packet left the NIC. Success is a response you received, validated, and applied exactly once.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Diagnose a TCP connection that cannot complete its handshake.

Answer

What I'd say first

Before opening a capture I'd pin down which of three symptoms I'm looking at, because each one eliminates most of the search space:

  • connect() hangs and returns ETIMEDOUT after roughly two minutes.
  • connect() returns ECONNREFUSED in under a millisecond.
  • connect() succeeds, but the first request hangs.

I'll assume Linux endpoints, one TCP flow, no TLS in the way yet.

Mechanism

The handshake is SYN, SYN-ACK, ACK, and each step has its own signature.

If the SYN never arrives (firewall DROP, wrong route, ARP failure, or an address-family mismatch) the client retransmits. net.ipv4.tcp_syn_retries defaults to 6, backing off 1, 2, 4, 8, 16, 32, 64 seconds, so connect() blocks for about 127 seconds before ETIMEDOUT. That long hang is the fingerprint of a silent drop.

If the SYN arrives but nothing is listening, the kernel answers with RST and connect() fails in microseconds. An immediate ECONNREFUSED means the packet reached a host and no socket was bound, or a REJECT rule fired. Different investigation entirely.

The subtle case: the handshake completes but the connection never reaches the application. When a SYN arrives, the kernel puts a request socket in the SYN queue and sends SYN-ACK. When the final ACK arrives, the connection moves to the accept queue, where it waits for accept(). If that queue is full, the kernel drops the final ACK (net.ipv4.tcp_abort_on_overflow=0 is the default). The client is already ESTABLISHED; the server stays in SYN_RECV and retransmits SYN-ACK per tcp_synack_retries (default 5). The client re-ACKs. The connection only completes when the application drains the queue. If it never does, the client's data sits in the server's receive buffer and the request times out at the application layer: with a perfectly healthy-looking handshake on the client.

The accept queue is bounded by min(net.core.somaxconn, the backlog passed to listen()). somaxconn defaults to 4096 on Linux 5.4+ (128 before that). The SYN queue is bounded by net.ipv4.tcp_max_syn_backlog; when it overflows, tcp_syncookies=1 (the default) lets the handshake complete anyway by encoding state in the ISN, so a SYN flood degrades rather than fails.

SymptomWhere it brokeConfirm with
connect() hangs ~127 s, then ETIMEDOUTSYN or SYN-ACK droppedtcpdump on client: SYN out, no SYN-ACK back
connect() returns ECONNREFUSED in <1 msRST: no listener, or REJECT ruless -lnt on server; iptables -L -n -v counters
connect() succeeds, first request hangsaccept queue full, final ACK droppedss -lnt: Recv-Q == Send-Q; nstat -az TcpExtListenOverflows

Commands

ss -lnt is the fastest read: Send-Q is the backlog limit, Recv-Q is the current accept-queue depth. Recv-Q pinned at Send-Q means the application isn't calling accept() fast enough. nstat -az TcpExtListenOverflows TcpExtListenDrops TcpExtSyncookiesSent gives cumulative counters. ss -tan state syn-recv shows half-open connections. tcpdump -nn -i any 'tcp port 443 and tcp[tcpflags] & (tcp-syn|tcp-ack) != 0' on both ends tells you whether the SYN arrived and whether the SYN-ACK left.

Trade-offs and traps

Capturing on both endpoints is worth the effort: if the server shows SYN-ACK sent and the client never sees it, the problem is a middlebox or asymmetric routing. The SYN went one way, the SYN-ACK came back another and hit a stateful firewall that never saw the SYN. conntrack -L and dmesg | grep nf_conntrack catch a full NAT table.

One trap: tcpdump on the sending host shows bad checksums because the NIC computes them after capture. Don't chase it: verify on the receiving side instead.

I'd stop once I know which of the three symptoms I have and which side of the wire the packet died on; everything after that is a targeted fix.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Explain a TCP retransmission trace.

Answer

What a strong candidate says first

A retransmission trace is a capture in which the same sequence range leaves the same sender twice. Before naming a cause, decide which of two mechanisms fired, because they mean different things: fast retransmit (three duplicate ACKs, RFC 5681) says one segment was lost and the path is otherwise working; RTO expiry says the sender heard nothing at all and the timer backed off.

Open the capture in Wireshark with relative sequence numbers on (Preferences → Protocols → TCP), filter tcp.analysis.flags, and find the gap. The receiver's ACK number stalls at the first missing byte; every later in-order segment that arrives produces a duplicate ACK of that same number. Three of those and the sender resends without waiting.

A worked trace

Sender 10.0.0.5:52344 → 10.0.0.9:443, MSS 1460, relative sequence numbers.

t (s)dirseqlenackflag
0.000→11460
0.000→14611460
0.000→29211460lost
0.000→43811460
0.000→58411460
0.000→73011460
0.021←02921ACK
0.022←02921dup ACK 1
0.023←02921dup ACK 2
0.024←02921dup ACK 3
0.024→29211460fast retransmit
0.045←08761ACK
0.046→87611460
0.067←010221ACK

Read it: the receiver's ACK sits at 2921 from 0.021 to 0.024. It has bytes 1–2920 and nothing else contiguous. The three duplicate ACKs at 0.022–0.024 are the sender's signal to resend 2921 immediately. The ACK at 0.045 jumps to 8761, covering everything through the retransmission. The RTT sample comes from the next segment (8761 sent 0.046, ACKed 0.067 → 21 ms), not from the retransmitted one: Karn's algorithm, because you cannot tell whether that ACK was for the original or the copy.

Why the timer behaves as it does

RTO starts at 1 s (RFC 6298); Linux floors it at 200 ms (TCP_RTO_MIN) and caps it at 120 s (TCP_RTO_MAX). Every expiry doubles it, and tcp_retries2 (default 15) ends the connection after roughly 15 minutes. That is why a single lost segment costs ~20 ms with fast retransmit and ~1 s with RTO: the difference is whether the receiver's later segments generate duplicate ACKs at all. If the loss is the last segment in flight, there is nothing to duplicate-ACK and you wait the full RTO.

What can fool you

  • Capture drop: the "retransmission" is only in your capture file. Check the capture's own drop counters (Wireshark: Statistics → Capture File Properties; dumpcap -w reports drops on exit). If the receiver never ACKs the range, suspect the capture, not the network.
  • Reordering: a segment arrives late but before the RTO. Wireshark marks it tcp.analysis.out_of_order; a retransmission that arrives after the original was already ACKed is tcp.analysis.spurious_retransmission. Linux detects these with RACK (RFC 8985) and F-RTO (RFC 5682).
  • Offload: TSO/GSO on the sender and GRO/LRO on the receiver rewrite the packet boundaries before the capture point. You see segments larger than MSS, or one 64 KB "segment" where the wire had 44. Checksum offload also makes Wireshark report "checksum incorrect" on packets that were fine. Capture on the NIC with ethtool -K eth0 gro off if you need ground truth.
  • Delayed ACK: Linux holds the ACK timer at 40 ms (TCP_DELACK_MIN). A 40 ms gap between data and ACK is not loss.
  • One-sided capture, if you only have the sender's side, you cannot distinguish "the ACK was lost" from "the segment was lost". Get both ends, or use ss -ti on the sender: it prints retrans, rto, and rtt per socket.

Naming the hop

Only after correlating both captures and the application's own timing should you attribute the loss. A retransmission that appears on the sender but never on the receiver's ingress means the loss is between them; one that appears on both means the receiver's ACK was lost on the return path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Diagnose a slow TCP transfer using window evidence.

Answer

First 60–120 seconds: I’d clarify whether this is one flow or many, whether both endpoints are Linux, and whether a proxy or shaper sits in path. Then I’d get ss -ti on both ends and a packet capture. The first split is receiver window (rwnd) vs congestion window (cwnd). Bytes in flight is roughly min(cwnd, rwnd). If rwnd is the limiter, the receiver or its buffer policy is the problem. If cwnd is the limiter, the network path is. If both are open and bytes in flight are low, the application, CPU, or a middlebox is stalling the flow.

rwnd is the receiver’s advertised free buffer. It is a 16-bit field, so without the window-scale option the maximum is 64 KiB. Window scaling is negotiated in the SYN; a scale factor of 7 multiplies the field by 128, so 64 KiB becomes 8 MiB. cwnd is the sender’s congestion limit; it grows with ACK clocking and collapses on loss. A zero window means the receiver has no room; the sender sends zero-window probes and waits for a window update. Delayed ACK can make a sender with a small write pattern look slow even when both windows are open.

Example: 100 Mbps path, 80 ms RTT. BDP = 12.5 MB/s × 0.08 s = 1 MB. If rwnd is 64 KiB, max throughput = 65,536 B / 0.08 s = 819 KB/s ≈ 6.55 Mbps. With wscale 7, rwnd can be 8 MiB, so it is not the limiter. If cwnd is 10 MSS (~14,600 B), max = 14,600 / 0.08 = 182.5 KB/s ≈ 1.46 Mbps. That arithmetic tells you which window to chase.

EvidenceLikely causeNext checkFix
rwnd pinned near 0 or 64 KiB; cwnd largereceiver app not reading or no window scalingapp read rate, SYN wscale, ss -ti rwndfix reader, raise SO_RCVBUF/tcp_rmem, enable wscale
cwnd small, retrans > 0, RTT spikesloss/congestionss -ti retrans, dup ACKs, mtrloss recovery, pacing, reduce loss
both windows open, bytes in flight lowapp/CPU/proxystrace, perf, proxy logsfix app, bypass proxy
many small segments, ACK every otherdelayed ACK/silly windowcapture segment sizesTCP_NODELAY, coalesce writes

Trade-offs: enlarging the receive buffer fixes a receiver-limited flow but costs memory per connection and can add bufferbloat latency. Fixing the reader is cheaper and lower latency but requires app changes. Enabling window scaling is usually free but must be negotiated on both ends and can expose large buffers. Raising cwnd by changing congestion control helps only if loss is not the cause; otherwise it makes loss worse. Pacing smooths bursts but adds CPU.

Failure modes to name: zero-window probes with no window update means the reader is stuck; detection is ss -ti rwnd:0 and repeated probes, cost is a stalled connection holding memory. No wscale on a high-BDP path caps at 64 KiB; detection is SYN without wscale and throughput matching the arithmetic, cost is a hard ceiling. cwnd collapse with retransmits means loss; detection is retrans and dup ACKs, cost is throughput halving and tail latency. Capture offload can lie: TSO/LRO/GRO coalesce segments and checksum offload can make window evidence look wrong; verify with endpoint counters and disable offloads if needed.

Decision sequence: read rwnd first, then cwnd, then bytes in flight. If rwnd is small, fix receiver. If cwnd is small, fix path. If both are open, fix the app or middlebox.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Investigate unexpected TCP resets.

Answer

First 90 seconds

Ask two things before opening a capture: which endpoint sent the RST, and was the connection idle or mid-transfer when it arrived. Those two answers split the problem in half.

A RST is not a message, it is a rejection: the sender had no connection state matching the segment, or its application aborted the socket. So the job is to find who sent it and why they had no state.

Confirm the sender and the RST's validity

tcpdump -i any -nn 'tcp[tcpflags] & tcp-rst != 0'

Compare the RST's sequence number against the receiver's next-expected sequence (RCV.NXT). RFC 5961 is the rule the kernel follows: a RST whose seq is exactly RCV.NXT resets the connection; a RST that is in-window but not exactly RCV.NXT gets a challenge ACK instead; an out-of-window RST is dropped silently. So a challenge ACK in the capture is proof the RST was spoofed or stale: an off-path injector that guessed the sequence wrong.

Why each side sends one

On Linux, nstat -az | grep TcpExt names the reason directly:

countermeaning
TCPAbortOnCloseapp closed the socket with unread data in the receive queue
TCPAbortOnDatadata arrived on a socket already closed
TCPAbortOnLingerSO_LINGER with timeout 0
TCPAbortOnTimeoutretransmission timeout exceeded (tcp_retries2, default 15 ≈ 924 s)
TCPAbortOnMemoryout of memory
TCPAbortOnSynSYN to a closed port

If the server's counters are flat and the client still sees a RST, the RST came from the path, not the server.

Middlebox RST on idle timeout

A load balancer or NAT keeps its own connection state with its own idle timer. ALB default idle timeout is 60 s, NLB 350 s; Linux conntrack's established timeout defaults to 432000 s but many NATs use far less. When the timer fires the device drops state; the next packet from the client matches nothing, so the device answers with RST. Signature: the RST arrives after a gap longer than the device's idle timeout, and the server never saw the connection close.

Localising the injector

TTL decrements by one per hop. Compare the TTL of the RST with the TTL of genuine packets from the same endpoint: a RST carrying a higher TTL than the real path implies came from a device closer than the endpoint. IP ID patterns help only weakly. Treat both as inference: a device log or a capture on the far side is proof.

Trade-offs

Endpoint capture is authoritative for what that host saw but blind to RSTs injected downstream of it. Middlebox logs are authoritative for the device, but many don't log RSTs at all. TTL/IPID is cheap and always available but only narrows the region. Order: endpoint capture first, then device logs, then TTL inference.

Failure modes

  • Trusting the source IP in the RST: spoofed RSTs carry the victim's address.
  • Reading only one side's capture: if only one endpoint sees the RST, it was injected on that side's path.
  • Missing the challenge ACK, which proves the RST was invalid.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design a safe binary protocol over TCP.

Answer

Assumptions first. Two services we control, TLS 1.3 terminating at each end, so confidentiality and integrity come from the transport and I don't re-implement them. If a proxy terminates TLS in the middle, that assumption breaks and I add an HMAC over the frame: I'll come back to it. Single logical connection per peer, no multiplexing requirement yet.

The core answer: length-prefixed framing with a fixed 16-byte header.

TCP is an ordered byte stream with no message boundaries. One send of 100 bytes can arrive as three recvs; three sends can arrive as one recv. So the protocol must frame. I use a length prefix rather than a delimiter because binary payloads contain every byte value, so a delimiter needs escaping, and escaping is where the bugs live.

fieldbyteswhy
magic10x9C; a wrong byte means we are desynced: close, don't skip
version1lets the layout change later without a flag day
type2message kind, drives dispatch
length4payload bytes, header excluded
corr_id8matches response to request

Big-endian throughout. Max frame 1 MiB, checked before allocating the payload buffer.

Python
import struct
HEADER = struct.Struct(">BBHIQ")   # magic, version, type, length, corr_id = 16 bytes
MAX_FRAME = 1 << 20

def read_frames(sock):
    buf = bytearray()
    while True:
        chunk = sock.recv(65536)
        if not chunk:
            return                      # EOF / half-close
        buf += chunk
        while True:
            if len(buf) < HEADER.size:
                break
            magic, ver, typ, length, corr = HEADER.unpack_from(buf)
            if magic != 0x9C:
                raise ProtocolError("bad magic")
            if length > MAX_FRAME:
                raise ProtocolError("frame too large")
            if len(buf) < HEADER.size + length:
                break
            payload = bytes(buf[HEADER.size:HEADER.size + length])
            del buf[:HEADER.size + length]
            yield ver, typ, corr, payload

Trace. recv returns 20 bytes: a header with length=4 plus 4 payload bytes. Inner loop: len(buf)=20 >= 16, unpack, length=4, 16+4=20 <= 20, payload is buf[16:20], del buf[:20] empties it, yield. Next inner iteration: len(buf)=0 < 16, break, back to recv. Now suppose recv returns two whole frames in one chunk: the inner loop yields both before the next recv. Suppose it returns only 10 bytes: len(buf)=10 < 16, break, wait. Partial and coalesced reads both fall out of the same loop.

Trade-offs. Length-prefix vs TLV/protobuf: TLV lets a reader skip unknown fields forward-compatibly, so old peers survive new message types; length-prefix needs the version byte and a hard reject on unknown type. I take length-prefix here because the payloads are opaque and I want O(1) sizing; I'd switch to protobuf if the schema churned. TLS vs app-level HMAC: TLS 1.3 gives integrity per record, so an HMAC is redundant unless a middlebox terminates TLS, then HMAC-SHA256 over header+payload with a per-connection key is the only end-to-end guarantee. Max frame: 1 MiB bounds worst-case memory per connection; raise it only if a real message needs it, because it multiplies by connection count.

Failure modes and detection.

  • Desync: a bad magic byte means the stream is unrecoverable. Close the connection. Detect with a framing-error counter; a nonzero rate means a peer bug or an attacker.
  • Allocation DoS: a peer sends length=0xFFFFFFFF. Rejecting before allocation caps memory at 16 bytes per bad frame. Detect with a rejected-frame metric.
  • Partial writes: send returns short; loop until the whole frame is out, or the peer sees a truncated frame.
  • Half-close: peer sends FIN but you still have data queued. recv returns 0, finish your writes, then close.
  • Duplicate retry: corr_id plus an idempotency check on the handler, or a retried request executes twice.

Test fragmentation and coalescing directly by feeding the parser split buffers: don't rely on IP-level packet boundaries, which the kernel won't preserve.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design a robust protocol over UDP.

Answer

Assumptions first. I'll assume a request/response protocol between a client and a server over the public internet, payloads of a few hundred bytes to a few KB, on a network that drops, reorders and duplicates. If you genuinely need reliable ordered streams, use QUIC rather than reinventing it: the design below is the reasoning QUIC encodes.

The core answer. UDP gives you ports and a checksum, nothing else. So the protocol must supply four things itself: framing, authenticity, ordering/replay protection, and a loss-recovery loop. Everything else is tuning.

Framing: keep every datagram under the path MTU so you never rely on IP fragmentation. IPv6's minimum MTU is 1280 bytes; subtract 40 (IPv6 header) + 8 (UDP header) = 1232 bytes of payload. QUIC takes the more conservative 1200-byte floor for its Initial packets. Budget 1200 bytes for header + payload.

fieldsizewhy
version1 bytelets you change the wire format
type/flags1 bytelong vs short header, key phase
connection ID0–20 bytessurvives NAT rebinding; QUIC allows up to 20
packet number1–4 bytesnonce + ordering
length2 bytesframing
AEAD tag16 bytesintegrity

Authenticity: encrypt and authenticate every packet with an AEAD. AES-128-GCM or ChaCha20-Poly1305. The nonce is derived from the packet number, so a replayed packet decrypts to the same plaintext; that is exactly why you need the replay window, not just crypto.

Replay window: keep a sliding bitmap. WireGuard uses a 2048-bit window (256 bytes); IPsec's default is 64 packets (RFC 4303). Trace with the 64-packet window: the window covers [1000, 1063]. Packet 1005 arrives: bit set, accepted. Packet 1005 arrives again: bit already set, dropped. Packet 900 arrives: below the left edge, dropped. Packet 1064 arrives: advance the window, shift the bitmap, accept.

Loss recovery: you cannot retransmit blindly. Estimate RTT (smoothed RTT + 4×RTT variance, RFC 6298), set a retransmission timeout, and back off exponentially on repeated loss. QUIC's initial RTT guess is 333 ms; TCP's initial RTO is 1 s. Retransmit only unacknowledged packets, and make the request idempotent with a request ID so a duplicate retry does not double-charge a card.

Congestion: respond to loss by reducing send rate, and pace packets rather than bursting. Without this you get the classic UDP failure: a burst fills a router queue, everything after it drops, and you retransmit into the same wall.

Amplification: a server must not send more than it received before validating the client's address. QUIC caps this at 3× the bytes received. Otherwise you have built a DNS-style reflection amplifier.

Failure modes and detection.

  • Spoofed source: attacker sends a small packet, server replies large → amplification. Detect via the 3× cap and address validation (token/retry).
  • Replay: a duplicate packet accepted twice → double side effect. Detect via window counters; alert when out-of-window drops spike.
  • MTU black hole: a path silently drops large datagrams. Detect via DPLPMTUD probes (RFC 8899); fall back to 1200.
  • NAT rebinding: the client's address changes mid-flow. Detect via connection ID mismatch; migrate without a new handshake.

Trade-offs. Fragmentation policy: fragment at the app layer (more control, more code) or cap at 1200 and let the app chunk (simpler, one extra round trip for large payloads). Choose app-layer chunking when payloads regularly exceed the MTU; choose the cap when they do not. Congestion control: NewReno is simple and safe; CUBIC and BBR win on high-BDP paths, but BBR can be unfair to loss-based flows sharing a bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Validate a TLS server connection securely.

Answer

What a strong candidate says first

Assume I'm the client and I control the client's TLS config; the server presents a chain. A connection is validated only if four independent checks pass: the chain builds to a root in my trust store with every signature verifying, the leaf's SAN matches the name I intended to reach, the current time is inside every cert's validity window, and the negotiated protocol/cipher is one I accept. Revocation is a fifth, policy-dependent check. If any of the first four fails, abort: never fall back to an unverified connection.

Mechanism

Chain building: start at the leaf, find an issuer whose subject matches the leaf's issuer and whose public key verifies the leaf's signature (RSA PKCS#1 v1.5/PSS, or ECDSA). Repeat toward the root. The root must be in the trust store; intermediates are usually sent by the server, but a missing one can be fetched via the AIA extension. RFC 5280 governs path validation: every CA cert needs basicConstraints CA:TRUE and keyUsage keyCertSign.

Hostname matching (RFC 9525): match the intended DNS name against the leaf's subjectAltName dNSName entries. CN is only a legacy fallback and modern clients ignore it when a SAN is present. Matching is case-insensitive and IDNA-normalized. A wildcard *.example.com matches exactly one leftmost label: a.example.com yes, a.b.example.com no, example.com no.

Validity: notBefore ≤ now ≤ notAfter, with a small clock-skew allowance.

Protocol/cipher: TLS 1.2 minimum, TLS 1.3 preferred. TLS 1.3 dropped RSA key exchange and renegotiation, so a downgrade to 1.0/1.1 or an export cipher is a hard fail.

Trade-offs

Pinning: pin the SPKI of the leaf or intermediate only when you control both ends (mobile apps, internal services). Always ship a backup pin and a rotation plan: a bad pin bricks every client at once. HPKP is dead; don't cite it.

Revocation: OCSP hard-fail turns a responder outage into a site outage, which is why most browsers soft-fail and lean on CRLSets/OneCRL. Choose hard-fail only for high-value internal services where you run the responder.

Internal CAs: add the private root to the client trust store; never set verify_mode to CERT_NONE to "make it work."

Failure modes and detection

  • Expiry / not-yet-valid: alert on notAfter 30 days out; clock skew shows as "certificate is not yet valid."
  • Name mismatch: SSLCertVerificationError at handshake; check SAN, not CN.
  • Missing intermediate: some clients AIA-fetch, others fail. openssl s_client -showcerts shows the chain the server actually sends.
  • Proxy termination: the client validates the proxy's cert, not the origin's; either trust the proxy CA or run end-to-end.
  • Unknown CA: chain doesn't reach a trusted root.

Artefact

Python
import ssl, socket
ctx = ssl.create_default_context()          # CERT_REQUIRED, check_hostname=True, system roots
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.set_alpn_protocols(["h2", "http/1.1"])
with socket.create_connection(("api.example.com", 443), timeout=5) as raw:
    with ctx.wrap_socket(raw, server_hostname="api.example.com") as s:
        print(s.version(), s.cipher()[0], s.selected_alpn_protocol())

Trace: create_default_context sets verify_mode=CERT_REQUIRED and check_hostname=True. server_hostname does double duty: it's the SNI value in the ClientHello and the name checked against the SAN after the handshake. On a mismatch or untrusted chain, wrap_socket raises ssl.SSLCertVerificationError before any application data is written. Output on success looks like TLSv1.3 TLS_AES_128_GCM_SHA256 h2.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Troubleshoot a name that intermittently reaches the wrong service.

Answer

What I'd say first

"Wrong service" is almost never the authoritative zone being wrong. It's a cache, a view, or client-side selection handing back a different valid answer. So the first move is to find out which of those three, then fix that layer.

Assumptions I'd state up front: the name is a normal record (not a wildcard), the client has at least one resolver, and "wrong service" means it connected to a host that answered but served the wrong thing, not a connection failure.

The fastest discriminator is to ask the client what it actually got and ask the authoritative server what it should give:

# on the client
dig +noall +answer +comments api.example.com
# straight to the authoritative server, no recursion
dig @ns1.example.com +norecurse api.example.com

If those differ, it's a cache or view problem. If they match, the name is fine and the fault is downstream: load balancer, SNI, or application host routing.

Why it's intermittent

Three mechanisms produce "sometimes wrong":

  1. Multiple records plus client selection. If the zone has two A records and one is stale, a client that rotates, applies RFC 6724 address selection, or runs happy-eyeballs (RFC 8305) hits the wrong one a fraction of the time. Two records ≈ 50% wrong, five ≈ 20%. That fraction is the intermittency signature.

  2. TTL and negative caching. A record with TTL 300 takes up to 5 minutes to converge after a change; during a rollout, resolvers hold the old answer for the rest of their TTL. Worse, NXDOMAIN is cached per RFC 2308 for the SOA minimum TTL (commonly 300–3600s), so a brief zone reload that returns NXDOMAIN poisons resolvers for up to an hour.

  3. Split-horizon / views. Internal and external resolvers return different answers for the same name. A client whose query leaks to the public resolver (split-tunnel VPN, misconfigured resolv.conf) gets the public IP and lands on the wrong service. Intermittent because it depends on which path the client's traffic takes.

Worked trace

$ dig +noall +answer api.example.com
api.example.com.  47  IN  A  10.0.1.5
api.example.com.  47  IN  A  10.0.2.9

TTL 47 means this was cached 13s ago from a 60s TTL. Two records. Now the authoritative server:

$ dig @ns1.example.com +norecurse +noall +answer api.example.com
api.example.com.  60  IN  A  10.0.1.5

Authoritative has one record; the resolver has two. The extra 10.0.2.9 is a stale record the resolver cached before the change and will keep for 13 more seconds. Every client that picks it lands on the old service. That is the intermittency.

Failure modes and how to detect them

  • Stale A record in a resolver: compare dig @resolver against dig @authoritative; the TTL countdown tells you when it expires.
  • Negative-cache poisoning: dig returns NXDOMAIN with an SOA in the authority section; the SOA minimum is the poison duration. Detect with dig +noall +authority.
  • Search-domain hijack: ndots:1 (glibc default) means api is tried as api.<searchdomain> first. If a search domain resolves api to a different service, you get the wrong one. Detect with dig +search api and read resolv.conf.
  • Split-horizon leak: compare internal vs public resolver answers; find the client's resolver IP with dig +short whoami.akamai.net.
  • DNSSEC validation failure: a validating resolver returns SERVFAIL, and some clients fall back to a secondary resolver with a different answer. Detect with dig +dnssec and check the AD flag.

Trade-off and deciding criterion

Lower TTL (60 vs 3600) shortens the wrong-answer window but multiplies query volume on the authoritative servers: at 10k QPS, TTL 60 is 10k QPS to the auth, TTL 3600 is about 167 QPS. The deciding criterion: if you change records often, lower the TTL; if the zone is stable, keep it high and fix the change process instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Trace an HTTPS request across a routed network.

Answer

Assume a client at 10.0.1.5 fetching https://203.0.113.10, IPv4, TLS 1.3 over TCP, one NAT at the edge, two routed hops. Here is what actually changes at each hop.

The client builds an HTTP request; TLS 1.3 encrypts it into a record: 5-byte header, up to 16 KiB of plaintext, 1 byte content type, 16-byte AEAD tag. TCP segments that, and because the client's Ethernet MTU is 1500 and IPv4 plus TCP headers are 20 + 20, each segment carries at most 1460 bytes of TLS record. That is the MSS. The first frame on the wire: dst MAC = default gateway's MAC, src MAC = client NIC, IP src 10.0.1.5, dst 203.0.113.10, TTL 64, TCP sport 44321, dport 443.

At the gateway, three things happen. TTL drops to 63. The NAT rewrites the source to 198.51.100.7 and the source port to, say, 40001, and because the TCP checksum covers a pseudo-header containing both IP addresses, it must recompute that checksum too. That is why a capture on the client and a capture on the server show different checksums for the same logical packet. Then a new frame is built: src MAC = gateway WAN interface, dst MAC = next hop router.

At the second router, TTL 62, MACs swapped again, IPs untouched. The server sees 198.51.100.7:40001 and has no idea 10.0.1.5 exists.

What survives end to end: the TLS session, the HTTP request, TCP sequence numbers, and the IP addresses only if there is no NAT. MAC addresses never survive a single hop: they are scoped to the link, which is exactly why they change while IP addresses do not.

fieldclient→gwgw→r2r2→server
src MACclient NICgw WANr2 egress
dst MACgw LANr2 ingressserver NIC
src IP10.0.1.5198.51.100.7same
src port4432140001same
TTL646362

Trade-offs. TCP+TLS versus QUIC: QUIC runs over UDP, so an 8-byte UDP header replaces TCP's 20, and QUIC does its own loss recovery and encryption, but UDP mappings in NATs often expire in 30s versus roughly 300s for established TCP, so a QUIC connection can die on an idle NAT where TCP survives. NAT versus explicit proxy: NAT is transparent and per-flow; a proxy terminates TCP and TLS and opens a second connection, so the server sees the proxy's IP and the client's TLS session ends at the proxy. Different trust boundary, different debugging.

Failure modes. PMTUD blackhole: if a path MTU is 1400 (a tunnel) and the ICMP type 3 code 4 is filtered, the sender keeps emitting 1500-byte packets that vanish. Symptom: handshake completes, then the connection stalls the moment a full-size record goes out. Detect with ping -M do -s 1472 (1472 + 20 IP + 8 ICMP = 1500) and step down. TTL expiry returns ICMP type 11 code 0. NAT timeout: the idle mapping is dropped and the next packet gets a RST or silence. Checksum offload: tcpdump on the sending host reports bad TCP checksums because the NIC computes them after capture. Capture on the receiver to see the truth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Trace a request through load balancer, TLS proxy, and backend.

Answer

Assumptions I'd state first: one HTTPS GET /v1/orders/42, client 203.0.113.7, DNS api.example.com → anycast VIP 198.51.100.10, an L4 load balancer in front of a TLS-terminating L7 proxy (Envoy or nginx), backend 10.0.2.9:8080. The point of the trace is that there are two independent transport sessions, and nothing about the client's TCP state survives the proxy.

The trace

  1. Client → VIP. Client resolves api.example.com to 198.51.100.10 and sends SYN from 203.0.113.7:51820 to :443. Anycast routes it to the nearest PoP; the L4 LB (AWS NLB, or IPVS in DSR mode) picks a proxy by 5-tuple hash and DNATs to 10.0.1.5:443. It does not parse TLS: it forwards bytes. With instance/IP targets it preserves the client source IP, so the proxy sees 203.0.113.7 as the peer.

  2. TLS termination at the proxy. The proxy completes the handshake: SNI api.example.com selects the cert, ALPN negotiates h2, TLS 1.3 finishes in 1 RTT. This is session #1. The proxy now has a client identity (cert + source IP) that the backend will never see directly.

  3. L7 routing. :authority maps to a virtual host, then a route, then a cluster. The proxy injects X-Forwarded-For: 203.0.113.7, X-Forwarded-Proto: https, X-Forwarded-Port: 443, and an X-Request-ID (Envoy generates a UUID if absent; nginx uses $request_id).

  4. Proxy → backend. The proxy opens or reuses a pooled connection to 10.0.2.9:8080: new tuple 10.0.1.5:44321 → 10.0.2.9:8080. This is session #2, with its own sequence numbers, its own TLS if the hop is encrypted, and the backend sees the proxy's IP, not the client's. The response streams back through both sessions.

LegPeer seen by serverTLSIdentity source
client → proxy203.0.113.7terminated at proxyclient cert / SNI
proxy → backend10.0.1.5optional, separatemTLS or none

Trade-offs

L4 passthrough vs L7 termination. Passthrough (NLB TCP listener) keeps TLS end-to-end, so the backend does the handshake and no header is injected, but you can't route on path or header, and you can't rewrite. Termination buys routing, header injection and observability, at the cost of the backend having to trust the proxy and of X-Forwarded-For hygiene: only strip and re-set it at the trusted edge, or a client spoofs its own IP.

Retries. Safe only for idempotent methods or with an idempotency key. nginx proxy_next_upstream defaults to error timeout; Envoy retries only when a retry policy is set (retry_on: 5xx,connect-failure, num_retries). Retrying a POST after the backend already committed duplicates the order.

Failure modes and detection

  • Backend resets mid-response → proxy returns 502 (nginx upstream prematurely closed connection) or 503 (Envoy upstream_reset_before_response_started). Detect via upstream_rq_5xx / nginx error log.
  • Slow body → nginx proxy_read_timeout default 60s, Envoy route timeout default 15s → 504. Detect via upstream_response_time p99.
  • Non-idempotent retry → duplicate order; detect via idempotency-key collision count.
  • Cert rotation → SNI/cert mismatch → TLS handshake_failure, clients see a reset. Detect via handshake-failure rate.
  • Drain → in-flight requests finish, new ones route away; watch listener connection count fall to zero before killing the task.

Pooling defaults worth knowing: Envoy circuit breaker max_connections 1024 per host; nginx needs explicit keepalive 32 in the upstream block to reuse backend connections at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Compare TCP+TLS and QUIC for a service.

Answer

Assumptions: HTTP/3-capable clients (browsers, or an app you ship), Linux servers behind a load balancer, TLS 1.3 on both paths, and a path RTT around 85 ms (Frankfurt–Virginia). If your clients are unknown enterprise desktops, the answer changes: see the last paragraph.

Answer: Default to TCP+TLS 1.3. Move to QUIC when you have many concurrent streams on a lossy or mobile path, or you need the connection to survive a network change. QUIC's wins are handshake latency, per-stream loss isolation, and connection migration; its costs are UDP reachability, userspace CPU, and losing middlebox visibility.

DimensionTCP + TLS 1.3QUIC (RFC 9000/9001/9002)
New connection2 RTT (TCP + TLS)1 RTT
Resumption1 RTT (0-RTT early data, replayable)0-RTT (also replayable)
Stream lossOne lost segment blocks all streams (HOL)Loss isolated to its stream
CongestionCUBIC/Reno in kernelCUBIC/Reno in userspace, same cwnd math
Migration4-tuple change kills connectionConnection ID survives NAT rebind / Wi-Fi→LTE
MiddleboxesVisible to conntrack, tcpdumpEncrypted; needs qlog
LB5-tuple hashingNeeds CID-aware LB (Envoy, HAProxy 2.6+, nginx 1.25+)

Handshake arithmetic on an 85 ms path: TCP+TLS 1.3 costs SYN (85 ms) + TLS (85 ms) = 170 ms before the first HTTP byte; QUIC costs 85 ms. On resumption, TLS 1.3 session tickets still cost 1 RTT (85 ms) unless you accept 0-RTT replay risk; QUIC's 0-RTT is 0 ms. That 85 ms is the whole argument for a new-connection-heavy workload.

Why the loss behaviour differs: TCP delivers an ordered byte stream, so a gap at sequence N holds back every byte after it. With HTTP/2, one lost segment stalls all multiplexed streams for a retransmit RTT. QUIC numbers packets and frames streams independently, so a gap on stream B doesn't delay stream A. It is not free capacity: the sender still cuts cwnd (CUBIC β = 0.7) on loss, so a lossy path throttles every stream. QUIC's loss detection uses packet threshold 3 and time threshold 9/8 × max(SRTT, latest_rtt) (RFC 9002), close to TCP's SACK-based logic; the difference is that QUIC packet numbers never repeat, so retransmits are unambiguous.

Failure modes to test, with what breaks and how you see it:

  • UDP/443 blocked by an enterprise firewall: handshake never completes. Detect via Alt-Svc fallback rate and per-network handshake failure counters. Keep the TCP listener.
  • Amplification: a server must not send more than 3× the bytes received before validating the client address (RFC 9000 §8.1). An LB that skips Retry tokens turns you into a reflector.
  • NAT rebinding / path change: TCP dies; QUIC migrates, but PATH_CHALLENGE can fail on a captive portal. Watch migration and path-validation failure counters.
  • Version negotiation and GREASE: middleboxes that drop unknown UDP break the handshake. Track failures by ASN.
  • Key update on long-lived connections: a buggy peer stalls the connection; alert on key-phase counters.

CPU and observability: QUIC runs crypto per packet in userspace; published measurements (Cloudflare, 2018) put it near 2× the per-byte cost of kernel TCP+TLS. Measure on your hardware before committing. You also lose conntrack and passive tcpdump; qlog is the replacement, and it's per-implementation.

Pick TCP+TLS when clients are unknown or enterprise-managed, when you need middlebox visibility, or when the workload is a single stream where HOL blocking can't bite. Pick QUIC when you control the client, run many streams over mobile or lossy paths, and can run a CID-aware LB with a TCP fallback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Use packet captures as reliable evidence.

Answer

Core answer (say this first)

A pcap is not evidence on its own: it is evidence of what one interface saw at one point in time. Before I defend it I state three assumptions: where it was captured (host stack, switch SPAN, or inline tap), what that point can and cannot see, and whether the capture itself dropped packets. Then I answer the real question, where did the loss happen, by corroborating the capture against a second source, usually the other endpoint's sequence numbers or the switch counters.

The capture point decides what you can claim

pointseesblind to
host capture (tcpdump -i eth0)post-kernel, pre-NICNIC offload artifacts; packets the kernel dropped
switch SPAN/mirrorwire truthmirror-port oversubscription drops; may strip VLAN tags
inline TAPwire truth, own clocknothing on the wire, but adds a device

Checksum offload is the trap. The NIC computes the TCP/UDP checksum after the kernel hands the packet over, so a host capture routinely shows bad or zero checksums on outbound packets. That is not wire corruption. Check ethtool -k eth0 | grep tx-checksumming; if it is on, a bad checksum in the capture proves nothing and you need a wire capture to settle it.

Clocks

tcpdump's default timestamp is wall-clock from gettimeofday, microsecond resolution, and it steps when NTP corrects. Two hosts each synced to within 1 ms can sit 2 ms apart; at 10 Gbps that is 2.5 MB of traffic, so "response before request" across two captures is meaningless. Use one capture point with one clock, or hardware/PTP timestamps (--time-stamp-precision=nano, adapter timestamps). Sequence numbers are the clock-free way to correlate: a segment that leaves one side with seq N and never arrives at the other is provable without trusting either clock.

Capture loss vs network loss

tcpdump prints "N packets dropped by kernel" at exit: that counter is the tell. If it is zero, the sender's capture shows a segment leaving, the receiver's never shows it arriving, and switch counters show no drops, that is network loss. If the kernel dropped packets, you cannot make that claim. Size the ring buffer with -B (KiB) and rotate with -C/-W, or use dumpcap -b filesize:102400 -b files:20.

Failure modes and how you detect them

  • Truncated payload: -s snaplen too small. The old default was 65535; tcpdump 4.99+ defaults to 262144, and -s 0 is full packet. Truncation silently cuts payload, so a later parse of a large record fails: check the captured length against the on-wire length.
  • VLAN/tunnel invisibility: capturing on the outer interface misses the inner header. Capture on the tunnel interface or decapsulate; if VLAN offload is on, the tag is inserted by hardware after capture.
  • Decryption: only with authorized ephemeral keys (e.g. SSLKEYLOGFILE), never long-term keys.

Minimize collection: BPF-filter to the tuple, snaplen to header length, and retain the raw pcap plus the exact command line and tool version so the capture is reproducible.

Curated: · Written: · Reviewed:

Difficulty: Hard