Network Troubleshooting Playbook: Connection Refused vs Timeout, DNS Failures, MTU/Fragmentation, conntrack & Ephemeral Port Exhaustion, Packet Capture
"Systems have inertia: we’ve found that a working computer system tends to remain in motion until acted upon by an external force, such as a configuration change or a shift in the type of load served." — Google, Site Reliability Engineering, chapter 12 "Effective Troubleshooting"
Summary: Every network failure a developer meets shows up as one of about fifteen error strings, and each string tells you which layer broke and what to run next; this chapter maps every string to its causes and gives you a method, the commands and the code to prove which one it is. Focus: Refused vs timed out vs unreachable vs reset, DNS and TLS failures, resource errors (EMFILE, EADDRINUSE, EADDRNOTAVAIL), slow-first-request and intermittent failures, MTU black holes, conntrack and ephemeral-port exhaustion, packet capture and Wireshark, latency tools, Docker/Kubernetes/cloud specifics, and the observability that makes the next incident short. Learning goal: Given an error message and five minutes, name the layer, list the two or three likely causes, run the one command that separates them, and write it down as a timeline someone else can follow.
This is the capstone of the networking group: it is organised by symptom → hypotheses → commands → fix and links back to the chapter that owns each mechanism instead of re-teaching it. Read it after (or alongside) network models (the layers we walk), IP addressing and routing (routes, ARP), NAT (translation tables and idle timeouts), DNS resolution (resolvers, ndots, caching), ports, sockets and connections (socket states, ss, TIME_WAIT), firewalls (DROP vs REJECT, security groups), Docker networking, Kubernetes networking, VPNs and tunnels (where MTU shrinks) and TLS in practice (handshake errors). Design topics stay in their own chapters: TCP and UDP, HTTP evolution and keep-alive, load balancing and health checks, timeouts, retries and jitter, observability, connection pooling and service discovery.
Page map
| If you are looking for | Go to |
|---|---|
| The symptom table to memorise | Everything in one minute |
| Why a method beats guessing | Why a playbook |
| Sources: SRE book, USE method, RFCs | Where it comes from |
| Reproduce, localise, bisect, compare, change one thing | The method |
connection refused | Connection refused |
connection timed out, i/o timeout | Connection timed out |
no route to host, network is unreachable | Unreachable |
connection reset by peer, broken pipe, EOF | Reset, broken pipe, EOF |
no such host, NXDOMAIN, SERVFAIL, DNS timeouts | DNS failures |
| TLS handshake timeout / certificate errors | TLS failures |
too many open files, address already in use, cannot assign requested address | Resource errors |
| The first request is slow | Slow first request |
| It fails 1 % of the time | Intermittent failures |
| Small requests work, big ones hang | MTU and fragmentation |
| conntrack full, ephemeral ports, NAT gateway ports | conntrack and ephemeral ports |
| tcpdump, Wireshark, RST, retransmissions | Packet capture |
mtr, traceroute, iperf3, curl -w, ss -ti | Latency and loss tools |
| Every error string per client (Go, PHP, curl, psql, redis-cli) | Error strings |
| Link → IP → route → ARP → firewall → NAT → DNS → TCP → TLS → HTTP | Layer checklist |
| Docker, Kubernetes, cloud | Containers and Kubernetes, Cloud |
Go netdiag, PMTU probe, port-exhaustion reproducer | Solving the classic problems |
Laravel net:diag, HTTP client errors, health endpoints | Laravel |
| Which tool answers which question | Choosing |
| Monolith to distributed | In architecture |
| Metrics and probes to keep | Observability to keep |
| Postmortem-ready timeline | Writing the timeline |
| Six broken Compose scenarios | Lab |
Everything in one minute
The symptom table. The error string is the most precise evidence you have. Read it before you touch anything.
| You see | Errno | What happened on the wire | Usual causes | First command |
|---|---|---|---|---|
connection refused | ECONNREFUSED (111) | SYN answered by RST, within one RTT | Nothing listening on that ip:port; wrong port; app bound to 127.0.0.1; container crashed; REJECT --reject-with tcp-reset | ss -ltnp on the server |
connection timed out / i/o timeout | ETIMEDOUT (110) or your own deadline | SYN sent, nothing came back | Security group/NACL/iptables DROP; wrong route; NAT missing; host down; conntrack full | tcpdump 'tcp[tcpflags] & tcp-syn != 0' on both ends |
no route to host | EHOSTUNREACH (113) | No ARP reply on the local subnet, or ICMP host-unreachable / host-prohibited | Dead IP on the same subnet; firewall REJECT --reject-with icmp-host-prohibited | ip neigh; ip route get IP |
network is unreachable | ENETUNREACH (101) | Nothing sent: no route in the local table | No default route; Docker internal: true network; IPv6 address with no IPv6 route | ip route; ip -6 route |
connection reset by peer | ECONNRESET (104) | RST on an established connection | Idle timeout at LB/NAT then reuse; server crash/abort; proxy limit; RST injection | tcpdump 'tcp[tcpflags] & tcp-rst != 0' |
broken pipe | EPIPE (32) | You wrote after the peer closed or reset | Same as reset, noticed on write | as above |
EOF / unexpected EOF | (none: read returned 0) | FIN arrived before a complete answer | Server closed idle keep-alive connection; crash mid-response; body shorter than Content-Length | curl -v; server logs |
no such host / Could not resolve host | (resolver) NXDOMAIN, SERVFAIL, timeout | DNS answer negative or missing | Typo; wrong search domain; split DNS; resolver down; UDP 53 filtered | dig name; cat /etc/resolv.conf |
TLS handshake timeout / x509 / wrong version number | (TLS) | TCP fine, handshake failed | Plain HTTP on the TLS port; SNI; chain; clock; MTU on the certificate flight | openssl s_client -connect host:443 -servername host |
too many open files | EMFILE (24) | No syscall to the network at all | Low ulimit -n; leaked sockets | ls /proc/PID/fd | wc -l |
address already in use | EADDRINUSE (98) | bind() on a taken ip:port | Second instance; old process still alive; port taken by another app | ss -ltnp 'sport = :8080' |
cannot assign requested address | EADDRNOTAVAIL (99) | No free ephemeral port for that destination | Ephemeral port exhaustion (TIME_WAIT churn, no keep-alive) | ss -tan state time-wait | wc -l |
| Large requests hang, small fine | (none, a hang) | Big packets dropped, ICMP "fragmentation needed" lost | MTU black hole on VPN/overlay/PPPoE | ping -M do -s 1472 host; tracepath host |
| Fails 1 in N | varies | One path, one IP or one table is bad | conntrack full; dead IP in DNS round-robin; LB draining; half-open after NAT timeout | split by destination IP and by host |
The ladder. Every connection climbs the same rungs. The first rung that fails names the layer.
| Rung | Question | Tool | Owner chapter |
|---|---|---|---|
| 1. Resolve | Does the name give the IP I expect, from this host/container? | dig, getent hosts, nslookup | DNS |
| 2. Route | Which interface and gateway would this packet use? | ip route get, ip neigh | IP addressing |
| 3. Connect | Does the SYN get a SYN-ACK? | nc -vz, curl -v, tcpdump | Ports and sockets |
| 4. TLS | Does the handshake complete with the right certificate? | openssl s_client | TLS |
| 5. Application | Does a full, correct response arrive in time? | curl -w, app logs | this chapter |
The three rules.
| Rule | Why |
|---|---|
| Test from where the failing code runs (same container, pod, subnet) | Your laptop has different DNS, routes, firewall and NAT |
| Fast failure and slow failure are different layers | Refused (milliseconds) means a host answered; timeout (seconds) means something dropped |
| Change one thing at a time and write it down | Two changes at once hide which one fixed it, and the timeline is the postmortem |
Why a playbook
Network failures feel random because the network is invisible: a function call returns an error string, and the cause could be the code, the host, a container bridge, a firewall three hops away or a load balancer in another account. Guessing ("restart it", "raise the timeout") sometimes works, which is exactly why it survives. A method is slower for the first minute and much faster for the next sixty.
| Guessing | Method |
|---|---|
| "It's the network" | "The SYN leaves the pod and never reaches the node; a NetworkPolicy drops it" |
| Raise the timeout | Find out what the timeout is waiting for |
| Restart and hope | Reproduce, capture, then fix and verify with the same reproduction |
| Test from your laptop | Test from the failing pod, then bisect towards the server |
| One big change | One change, one observation, one timeline line |
| Fixed but nobody knows why | A postmortem with evidence (capture, counters, error strings) |
The everyday picture. A plumber with no water at the kitchen tap. She does not replace the tap first. She opens the tap next to the meter (is water reaching the house?), then the one halfway (is it reaching the floor?), then the kitchen. Each test halves the pipe that could be broken. "Refused" is the tap answering "no" immediately; "timeout" is no sound at all; "reset" is water that starts and then stops. We will reuse this picture: bisect the pipe, compare with a working tap, change one valve at a time.
Three misunderstandings, up front.
| Misunderstanding | Reality |
|---|---|
| "Timeout and refused are the same: it's down" | Refused proves a host answered with RST; timeout proves packets vanished. They point to different layers and different teams |
| "ping works, so the network is fine" | ICMP echo uses no port, may take another path or priority, and is small. TCP to the real port with the real packet size is what matters |
| "It works from my machine" | Your machine has its own DNS, routes, VPN and NAT. Reproduce from inside the failing container or pod |
Where it comes from
| Source | What it gives this chapter |
|---|---|
| Google SRE book, ch. 12 "Effective Troubleshooting" (2016) | The hypothetico-deductive loop: triage, examine, diagnose, test, treat; "what touched it last"; bisection; "correlation is not causation" |
| Brendan Gregg, the USE method and Linux performance tools | "For every resource, check utilization, saturation, and errors": applied here to fds, ports, conntrack, NAT ports, backlog |
| RFC 1191 (1990), Path MTU Discovery | DF bit and ICMP "fragmentation needed": the mechanism whose failure is the black hole |
| RFC 2923 (2000), TCP problems with PMTUD | Names "the long-standing black hole problem" |
| RFC 4821 (2007), Packetization Layer PMTUD | Probing with real packets instead of trusting ICMP; Linux tcp_mtu_probing |
| RFC 8899 (2020), DPLPMTUD | The same idea for datagram transports (QUIC, UDP) |
| RFC 9293 (2022), TCP | SYN, RST, retransmission and the connection states every capture shows |
Linux man pages: connect(2), tcp(7), ss(8), ip(8), tcpdump(1), pcap-filter(7), ping(8), tracepath(8), mtr(8), traceroute(1), dig(1), conntrack(8), nft(8), iptables(8), nstat(8), strace(1), nsenter(1) | Exact flags and the errno meanings |
Kernel docs ip-sysctl and nf_conntrack-sysctl | Defaults: port range 32768-60999, tcp_mtu_probing, nf_conntrack_max |
| Wireshark User's Guide | Display filters, TCP analysis flags, Follow TCP Stream, TLS decryption with a key log |
| Cloudflare engineering blog | conntrack overfill, ephemeral port exhaustion, PMTUD with ECMP, IP fragmentation |
| Kubernetes, Docker, AWS and Azure docs | kubectl debug, DNS debugging, NetworkPolicy, VPC Flow Logs, NAT gateway limits, SNAT ports |
The SRE book's own words on the strategy we use most: "an alternative, bisection, splits the system in half and examines the communication paths between components on one side and the other." And on recent changes: "Recent changes to a system can be a productive place to start identifying what’s going wrong." Gregg's USE method is one line: "For every resource, check utilization, saturation, and errors."
The concept catalogue
The method: reproduce, localise, bisect, compare, change one thing Must-know
In plain words: Make the failure happen on demand, find the first layer where it breaks by walking from the client to the server, compare with something that works, and change exactly one thing at a time.
Common misunderstanding: "Troubleshooting is knowing the answer." It is a loop. The SRE book frames it as forming hypotheses from observations and then testing them: "Using the experimental method, we can try to rule in or rule out our hypotheses." Experience makes the hypothesis list shorter, not the loop unnecessary.
Definition: a five-step loop.
| Step | What you do | Network example |
|---|---|---|
| 1. Reproduce | One command that fails the same way the app fails, from the same place | kubectl exec pod -- curl -sv --max-time 5 http://orders:8080/health |
| 2. Localise by layer | Walk the ladder: DNS, route, connect, TLS, HTTP | DNS ok, connect times out: stop above TCP |
| 3. Bisect the path | Test from points between client and server | From the pod: timeout. From the node: ok. So the pod-to-node hop (policy, CNI) |
| 4. Compare working vs broken | Same request from a working pod/host/region; diff configs, routes, rules | Pod in namespace A works, B fails: B has a default-deny NetworkPolicy |
| 5. Change one thing | One change, then re-run the reproduction from step 1 | Add an egress rule; re-run; it passes; write the timeline line |
Timeline: bisecting a timeout.
1 10:02 app log: dial tcp 10.0.3.7:5432: i/o timeout (symptom)
2 10:04 pod: nc -vz -w3 10.0.3.7 5432 -> timed out (reproduced)
3 10:05 pod: getent hosts db.internal -> 10.0.3.7 (DNS ok: rung 1 passes)
4 10:06 node: nc -vz -w3 10.0.3.7 5432 -> succeeded (bisect: node ok, pod fails)
5 10:08 node: tcpdump -ni any 'host 10.0.3.7 and port 5432' -> SYN from pod IP leaves node, no SYN-ACK
6 10:10 db: tcpdump shows no SYN arriving (dropped between)
7 10:12 cloud: DB security group allows node SG, not pod CIDR (hypothesis)
8 10:15 add pod CIDR to SG ingress 5432; re-run step 2 -> succeeded (one change, verified)Real scenarios: a staging deploy where only one replica fails (compare that pod's node with the others); a monthly batch job that fails at 02:00 (reproduce at 02:00 load or with the same concurrency); a partner API that fails only from production (bisect: prod NAT IP is not on their allow-list).
What each tool tells you on each side.
| Point on the path | Command | Proves |
|---|---|---|
| Inside the client container | curl -sv, getent hosts, ip route get | What the app sees |
| Client host/node | tcpdump -ni any host IP | Whether packets leave |
| Every middle box you own | flow logs, conntrack -L, LB access logs | Whether packets pass |
| Server host | tcpdump, ss -ltn, nstat | Whether packets arrive and who answers |
| Server process | logs, strace -f -e trace=%network | Whether the app saw it |
Fix / how to use it: the Go netdiag and the Laravel net:diag command automate steps 1 and 2; the timeline section is step 5 written down.
Connection refused Must-know
In plain words: You knocked and someone shouted "nobody lives here" immediately. A host is reachable; the port is not served.
Common misunderstanding: "Refused means a firewall blocked me." Most firewalls DROP silently (you get a timeout). Refused means the target kernel (or a REJECT --reject-with tcp-reset rule) answered your SYN with RST. connect(2) says it exactly: ECONNREFUSED "A connect() on a stream socket found no one listening on the remote address."
Definition: the SYN reached a TCP stack that had no listening socket for that destination ip:port, so it replied RST+ACK. Arrives in about one round trip.
client 10.231.0.2 server 10.231.0.10
1 SYN sport 47494 -> dport 81 ----->
2 <----- RST,ACK (no listener on :81)
3 connect() returns ECONNREFUSED after ~0 msReal scenarios (and the hypothesis each one gives):
| Cause | How you see it | Fix |
|---|---|---|
| Nothing listens: process crashed, not started, still booting | ss -ltnp shows no :PORT | Start/fix it; add a readiness probe so traffic waits |
| Wrong port or IP in config | ss shows :5433, config says 5432 | Fix config; one source of truth |
App bound to 127.0.0.1 inside a container | ss -ltn shows 127.0.0.1:8000, not 0.0.0.0:8000 | Bind 0.0.0.0 (or ::) in containers |
| Container restarted / Service has no endpoints | docker ps restarts; kubectl get endpointslices empty | Fix crash loop; selector labels |
REJECT --reject-with tcp-reset | Server has listener but rule rejects; iptables -L -v counter rises | Allow the source |
| Docker published port with no backend | Through docker-proxy it often becomes reset/empty reply instead | See Lab scenario 1 |
What each client prints. Real output, Linux containers, Go 1.27, curl 8, PostgreSQL 16 psql, Redis 8 redis-cli, PHP 8.5:
Go dial tcp 10.231.0.10:81: connect: connection refused
curl curl: (7) Failed to connect to ntp-web:81 after 0 ms: Could not connect to server
psql psql: error: connection to server at "ntp-web" (10.231.0.10), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
redis-cli Could not connect to Redis at ntp-web:6379: Connection refused
PHP stream_socket_client(): errno=111 errstr="Connection refused"Laravel's ConnectionException carries the same libcurl text (cURL error 7: Failed to connect to ...), because the HTTP client is built on Guzzle and libcurl.
Fix / how to use it: on the server, ss -ltnp (who listens where), then curl -v http://127.0.0.1:PORT from inside the server's own namespace. If that works but the remote test is refused, the bind address or a REJECT rule is the answer. In Go, errors.Is(err, syscall.ECONNREFUSED); in PHP, errno === 111. Refused is cheap and fast, so it is safe to retry with backoff during a deploy (the listener is coming), but a refusal that lasts more than a deploy is a config bug, not a transient.
Connection timed out Must-know
In plain words: You knocked and heard nothing. Something between you and the host threw your packet away, or the host is not there.
Common misunderstanding: "Timeout means the server is slow." For a connect timeout the server never saw you; slow servers accept the connection and then are slow to answer (that is a read/response timeout). Separate the two in your client config and your logs.
Definition: the SYN (or its SYN-ACK) was dropped; the kernel retransmits the SYN until the tcp_syn_retries budget is spent and then fails with ETIMEDOUT, unless your own deadline fires first. The budget changed with kernels: tcp(7) still says default 6 "corresponds to retrying for up to approximately 127 seconds" (pure exponential backoff), while the current kernel ip-sysctl docs say 6 "corresponds to 67seconds (with tcp_syn_linear_timeouts = 4)", because current kernels retransmit the first SYNs every second ("1, 1, 1, 1, 1, 2, 4, ...") before backing off. Go reports its own deadline as i/o timeout; the kernel's give-up as connection timed out.
Real capture (kernel 7.0, tcp_syn_retries=2 in the client's namespace, iptables -j DROP on the server, no Go deadline):
18:23:49.096819 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, win 64240, options [mss 1460,...], length 0
18:23:50.110827 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ... (same seq: a retransmission)
18:23:51.133836 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:52.157367 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:53.181953 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:54.206174 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
FAIL rung 2 (tcp): dial tcp 10.240.1.20:80: connect: connection timed out (after 7.16 s)Six SYNs with the same sequence number, one second apart, no answer at all: that is what a DROP looks like from the client. The firewall's counter (iptables -L INPUT -v -n) showed 6 360 DROP ... tcp dpt:80 for exactly those six packets.
Real scenarios:
| Cause | Where to look | Telltale |
|---|---|---|
| Security group / NACL / iptables / nftables DROP | Cloud console, iptables -L -v -n, nft list ruleset, VPC Flow Logs REJECT | Counter on a DROP rule rises with each SYN |
| Wrong route (asymmetric, missing return route) | ip route get, route tables | SYN arrives at the server, SYN-ACK leaves by another path and dies |
| Missing NAT / no internet gateway route | Subnet route table, NAT gateway | Private subnet: no 0.0.0.0/0 route to a NAT |
| Host down or IP not assigned | ARP: ip neigh shows FAILED/INCOMPLETE on a same-subnet host | Same subnet usually turns into no route to host after ~3 s |
| Kubernetes NetworkPolicy default deny | kubectl get networkpolicy -A | Only pods in one namespace fail |
| conntrack table full on a node | dmesg "nf_conntrack: table full, dropping packet" | Random new connections time out under load |
| Server listen backlog overflow | nstat -az TcpExtListenOverflows rises on the server | Under bursts only |
What each client prints (real output):
Go (own deadline) dial tcp 10.231.0.99:80: i/o timeout
Go (kernel gave up) dial tcp 10.240.1.20:80: connect: connection timed out
curl curl: (28) Connection timed out after 2005 milliseconds
psql psql: error: connection to server at "10.231.0.99", port 5432 failed: timeout expired
PHP (musl) errno=110 errstr="Operation timed out"In Laravel the same two cases arrive as ConnectionException with cURL error 28 in the message.
Fix / how to use it: always set a connect timeout of a few seconds (Go net.Dialer{Timeout}, Laravel connectTimeout(), libpq connect_timeout, curl --connect-timeout), separate from the read/total timeout. Then capture on both ends: tcpdump -ni any 'tcp[tcpflags] & (tcp-syn|tcp-rst) != 0 and host IP'. SYN leaves the client but never arrives: a middle box. SYN arrives, SYN-ACK leaves, never reaches the client: return path. Nothing arrives and nothing leaves: local policy. See firewalls for DROP vs REJECT.
No route to host and network is unreachable Important
In plain words: "Network is unreachable" means your own machine has no road to that address at all. "No route to host" means the road exists but the last step (finding the host on the local network) failed, or a router/firewall explicitly said the host is unreachable or prohibited.
Common misunderstanding: "No route to host means a routing table problem." On Linux it most often means ARP got no answer for a same-subnet IP (a dead container, a stale IP in config), or a firewall used REJECT --reject-with icmp-host-prohibited (a common choice in host firewalls; see Lab step 5).
Definition:
| Error | Errno | Generated by | Wire |
|---|---|---|---|
network is unreachable | ENETUNREACH | Local kernel, before sending | Nothing leaves; immediate |
no route to host | EHOSTUNREACH | Local kernel after ~3 s of failed ARP, or an ICMP type 3 code 1/10/13 from a router/firewall | ARP who-has repeated; or ICMP back |
client 10.231.0.2 (same /24 as 10.231.0.99, which does not exist)
1 ARP who-has 10.231.0.99 tell 10.231.0.2
2 ARP who-has 10.231.0.99 tell 10.231.0.2
3 ARP who-has 10.231.0.99 tell 10.231.0.2
4 connect() -> EHOSTUNREACH after 3.1 s ("dial tcp 10.231.0.99:80: connect: no route to host")Real scenarios: a Docker container whose old IP is hard-coded in another service's config (the new container got a new IP); a host whose firewall rejects with host-prohibited; a container on a Compose network with internal: true that tries to reach the internet (no default route: unreachable); an IPv6 AAAA answer on a host with no IPv6 route (Happy Eyeballs clients fall back, simple clients fail).
| Client | ENETUNREACH | EHOSTUNREACH |
|---|---|---|
| Go | connect: network is unreachable | connect: no route to host |
| curl | (7) Failed to connect ... Could not connect to server | same exit 7 |
| redis-cli (musl) | — | Could not connect to Redis at 10.231.0.99:6379: Host is unreachable |
| PHP (musl) | errno 101 | errno 113 Host is unreachable |
Fix / how to use it: ip route get DEST prints the route and source the kernel would use (or RTNETLINK answers: Network is unreachable); ip neigh shows FAILED/INCOMPLETE for an ARP failure. Replace IPs in config with names; give containers a default route or an egress path; for IPv6-only failures prefer clients with Happy Eyeballs (Go's dialer does it, RFC 8305).
Connection reset by peer, broken pipe and EOF Must-know
In plain words: The call started fine and then the other side (or something in the middle) hung up. A reset is a slammed phone; EOF is a polite goodbye that came too early; broken pipe is you talking into a phone that is already dead.
Common misunderstanding: "Reset by peer means the server crashed." The "peer" is whoever sent the RST, and it is very often a middle box: a load balancer or NAT gateway that forgot your idle connection. The AWS NAT gateway documentation is explicit: after 350 seconds idle, "a NAT gateway returns an RST packet to any resources behind the NAT gateway that attempt to continue the connection (it does not send a FIN packet)."
Definition:
| Error | Meaning | Errno |
|---|---|---|
connection reset by peer | An RST arrived on an established connection; pending data is discarded | ECONNRESET |
broken pipe | You wrote to a socket whose peer already reset it (Linux sends SIGPIPE; Go ignores it and returns EPIPE) | EPIPE |
EOF | Read returned 0: the peer sent FIN | none |
unexpected EOF | FIN before the promised length (Content-Length, protocol frame) | none (library) |
Real Go output, a server that aborts (SetLinger(0)) versus one that closes normally:
read after RST: read tcp 127.0.0.1:40062->127.0.0.1:9101: read: connection reset by peer
write after RST: write tcp 127.0.0.1:40062->127.0.0.1:9101: write: broken pipe
read after FIN: EOF
first write after FIN: <nil> (accepted locally; the peer answers it with RST)
second write after FIN: write tcp 127.0.0.1:46392->127.0.0.1:9102: write: broken pipe
net/http, no response: Post "http://127.0.0.1:9202/": EOF
net/http, short body: unexpected EOFThe "first write succeeds, second write fails" line is why broken pipes appear one request late: the first write only proves the bytes reached your kernel.
The keep-alive race (timeline). The single most common source of sporadic resets and EOFs:
client pool load balancer (idle timeout 60 s) server
1 request A on conn #7 -----> -----> 200
2 conn #7 returned to pool, idle
3 ... 60 s pass ... LB drops state for conn #7 (or sends FIN)
4 request B on conn #7 -----> no state: RST <-----
5 client: "connection reset by peer" / "EOF" on a request that never reached the serverReal scenarios:
| Cause | Telltale | Fix |
|---|---|---|
| Pool keeps idle connections longer than LB/NAT idle timeout | Errors after quiet periods; first request after idle | Client idle timeout below the shortest middlebox timeout; TCP keepalive; retry idempotent requests once |
| Server keep-alive timeout shorter than the client's | Server closes (FIN) while client sends | Server keep-alive timeout > LB/client idle timeout (nginx keepalive_timeout, Node keepAliveTimeout) |
| Server process crashed / OOM-killed mid-request | Kernel resets the orphaned sockets; logs show restart | Fix crash; graceful shutdown that drains |
Proxy limits (body size, header size, proxy_read_timeout) | Reset or 502 at the proxy only | Raise or fix the limit; read proxy logs |
Listen queue full with tcp_abort_on_overflow=1 | Resets under bursts | Bigger backlog, more workers |
| RST injection by middleboxes/DPI | RST with odd TTL/IP ID in captures | Different path, TLS everywhere |
Database killed the session (idle_session_timeout, wait_timeout in MySQL) | "server closed the connection unexpectedly" on the next query | Pool max_idle_time below server timeout; ping/validate before use |
Fix / how to use it: capture RSTs with tcpdump -ni any 'tcp[tcpflags] & tcp-rst != 0' and look at who sends them (source IP and TTL). In Go, set http.Transport.IdleConnTimeout below the smallest idle timeout on the path (see the timing snippet); net/http already retries a request on a reused connection that failed before any response if the request is idempotent. Laravel: Http::retry() for ConnectionException on idempotent calls only.
DNS failures Must-know
In plain words: The name did not turn into an IP. Either the answer was "no such name" (NXDOMAIN), "I failed" (SERVFAIL), or no answer at all (timeout).
Common misunderstanding: "no such host means the record does not exist." It means the resolver your process used, after applying /etc/hosts, search domains and ndots, got a negative answer. The same name may resolve fine from another host, another container or another resolver. Always test from the failing place with the failing resolver. Mechanism and caching live in DNS resolution; this block is the symptom view.
Definition and the strings (all real, from the containers described under Error strings; a dash means not reproduced):
| Answer | dig status | Go | curl | psql (musl) | redis-cli (musl) | PHP (musl) |
|---|---|---|---|---|---|---|
| Name does not exist | NXDOMAIN | lookup x on 127.0.0.11:53: no such host | (6) Could not resolve host: x | could not translate host name "x" to address: Try again | Name has no usable address | getaddrinfo for x failed: Name does not resolve |
| Resolver failed (internal Docker network, external name) | SERVFAIL | — | (6) Could not resolve host: example.com (DNS server returned general failure) | — | — | — |
| No answer in time (cold upstream, first run) | no reply | lookup ntp-wbe: i/o timeout | — | — | — | — |
app (ndots:5 in a Kubernetes pod) asks for "api.partner.com"
1 api.partner.com.default.svc.cluster.local A? -> NXDOMAIN
2 api.partner.com.svc.cluster.local A? -> NXDOMAIN
3 api.partner.com.cluster.local A? -> NXDOMAIN
4 api.partner.com. A? -> 203.0.113.10 (4 queries x A and AAAA)Real scenarios: a typo in DB_HOST (instant NXDOMAIN from Docker's embedded resolver 127.0.0.11); a cold upstream making the first lookup time out (we saw lookup ntp-wbe: i/o timeout on the first run and an instant no such host on the second); CoreDNS overloaded by ndots:5 search expansion; split DNS that resolves a name to a private IP on the VPN and a public one off it; a resolver reachable over UDP but not TCP, so large answers (DNSSEC, many records) fail.
Fix / how to use it: dig +search name, dig @RESOLVER name, getent hosts name (uses the system resolver path, including /etc/hosts and nsswitch.conf), cat /etc/resolv.conf. In Kubernetes, the official DNS debugging page starts with kubectl exec -i -t dnsutils -- nslookup kubernetes.default. Use fully qualified names with a trailing dot for external hosts in pods, or lower ndots, and cache in the app.
TLS failures Important
In plain words: TCP connected, but the two sides could not agree to speak encrypted, or the client did not trust what the server showed.
Common misunderstanding: "TLS handshake timeout is a certificate problem." A timeout in the handshake is usually a network problem: the server's certificate flight is the first large packet of the connection, so an MTU black hole shows up exactly there. Certificate problems fail fast with a specific message.
Definition and the strings (real output where marked):
| Situation | Go | curl |
|---|---|---|
| Plain HTTP on the TLS port (real) | tls: first record does not look like a TLS handshake | (35) TLS connect error: error:0A00010B:SSL routines::wrong version number |
| Handshake stalls (MTU, overloaded server) | net/http: TLS handshake timeout | (28) |
| Unknown CA / self-signed | x509: certificate signed by unknown authority | (60) "Peer certificate cannot be authenticated with known CA certificates" |
| Name mismatch / wrong SNI | x509: certificate is valid for a, not b | (60) |
1 TCP SYN / SYN-ACK / ACK fine (small packets)
2 ClientHello (~300-600 bytes) fine
3 ServerHello + Certificate (3-5 KB, full-size segments) -> dropped at a 1400-byte hop
4 client waits ... "TLS handshake timeout"Fix / how to use it: openssl s_client -connect host:443 -servername host -showcerts, then the TLS chapter for chains, SNI and clocks. If s_client hangs after CONNECTED(00000003), test the MTU with ping -M do -s 1372 host.
Resource errors: too many open files, address already in use, cannot assign requested address Must-know
In plain words: These are not the network saying no. Your own machine ran out of something: file descriptors, a free listening port, or free source ports.
Common misunderstanding: "cannot assign requested address is a DNS or IP problem." In a client, EADDRNOTAVAIL from connect() means, in the connect(2) page's words, "all port numbers in the ephemeral port range are currently in use". It is port exhaustion towards one destination.
Definition:
| Error | Errno | Syscall | Means |
|---|---|---|---|
too many open files | EMFILE / ENFILE | socket, accept, open | Process (ulimit -n) or system (fs.file-max) fd limit |
address already in use | EADDRINUSE | bind/listen | Someone else holds ip:port (or a TIME_WAIT without SO_REUSEADDR, rare for servers in Go/Linux) |
cannot assign requested address | EADDRNOTAVAIL | connect (or bind to a non-local IP) | No ephemeral port left for this destination 4-tuple, or binding to an address the host does not have |
Real Go output in a container with ulimit -n 30:
listen tcp 127.0.0.1:9101: bind: address already in use
dial tcp 127.0.0.1:9102: socket: too many open files (connection #21)
dial tcp 10.231.0.20:8080: connect: cannot assign requested address (port range 40000-40009, see Lab)Real scenarios: a PHP-FPM or Go service that creates a new HTTP client per request (every request a new connection, every close a TIME_WAIT: ports run out at a few hundred requests per second to one upstream); a load test from one machine; a service that leaks response bodies (Go: forgetting resp.Body.Close() leaks fds and keeps connections out of the pool); a second php artisan serve on port 8000; binding a container to the host's public IP that only exists on the host.
| Error | Check | Fix |
|---|---|---|
EMFILE | ls /proc/PID/fd | wc -l vs cat /proc/PID/limits | Fix leaks; raise LimitNOFILE (systemd), ulimits (Docker/Compose) |
EADDRINUSE | ss -ltnp 'sport = :PORT', lsof -i :PORT | Stop the other process; choose a port; SO_REUSEPORT only on purpose |
EADDRNOTAVAIL | ss -tan state time-wait | wc -l, ss -tan 'dst IP:PORT' | wc -l | Keep-alive and pooling; widen net.ipv4.ip_local_port_range; more source IPs; spread destinations |
Fix / how to use it: the port-exhaustion reproducer shows the exact error; the fix is almost always connection reuse, covered under conntrack and ephemeral ports.
Slow first request Important
In plain words: The first call after a deploy or a quiet period takes seconds; the next ones take milliseconds. Something is being set up once and then reused.
Common misunderstanding: "The server is slow to warm up." Measure before blaming: split the time into DNS, connect, TLS, server time. Very often it is DNS search expansion or a TLS handshake that only the first request pays.
Definition: curl -w exposes the phases (from the curl manual: time_namelookup, time_connect "until the TCP connect to the remote host (or proxy) was completed", time_appconnect "until the SSL/SSH/etc connect/handshake to the remote host was completed", time_starttransfer "until the first byte was received").
curl -s -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' URL
1 dns=5.012 connect=5.013 tls=5.040 ttfb=5.080 -> 5 s in DNS: a resolver timeout then retry (first nameserver dead)
2 dns=0.001 connect=0.090 tls=0.300 ttfb=0.310 -> connect 90 ms RTT, TLS 2 RTT: far region, new connection
3 dns=0.001 connect=0.001 tls=0.002 ttfb=1.900 -> network fine; server cold (JIT, cache, pool)Real scenarios and causes:
| Cause | Phase | Fix |
|---|---|---|
ndots:5 search walk in Kubernetes (4 extra NXDOMAIN round trips, A and AAAA) | dns | FQDN with trailing dot, dnsConfig.options ndots: 2, NodeLocal DNSCache |
First nameserver in resolv.conf dead: 5 s timeout default then next | dns | Fix resolver list; options timeout:1 attempts:2 |
| AAAA answer but no IPv6 route; client tries IPv6 first | connect | Happy Eyeballs; fix IPv6 or do not publish AAAA |
| New TLS connection per request (no keep-alive, no session resumption) | tls | Reuse connections; TLS 1.3 resumption |
| Cold connection pool (database, Redis, HTTP) | connect + tls | Warm the pool at start; min idle connections |
| Lazy app boot (Laravel config/route cache missing, opcache cold, Octane worker start) | ttfb | php artisan optimize; warm-up request in readiness |
| Conntrack/ARP entry missing on first packet in some CNIs | connect | Usually small; measure |
Fix / how to use it: Go timing snippet prints the same phases and reused=true/false for each request.
Intermittent failures Must-know
In plain words: It works most of the time. That means most paths are fine and one path, one IP or one table is not. The job is to find the variable that separates good from bad attempts.
Common misunderstanding: "Intermittent means random." Nothing in a network is random; it is a hidden variable you have not split by yet: destination IP, source pod, node, time of day, payload size, connection age.
Definition: a failure rate between 0 and 100 % on otherwise identical requests. Split the failures by every dimension you log until one value has 100 % failures.
| Hidden variable | Cause | How to split | Fix |
|---|---|---|---|
| Destination IP | DNS round-robin includes a dead or draining IP | Log resolved IP per request; dig +short name shows several | Health-checked LB instead of plain RR; remove the record; client tries next IP |
| Connection age | Half-open connection after NAT/LB idle timeout (reset/EOF on first use after idle) | Error vs idle time before request | Idle timeout below middlebox timeout; keepalive |
| Payload size | MTU black hole: only large bodies hang | Error vs request/response size | MSS clamp, fix ICMP, lower MTU (MTU) |
| Load / time | conntrack full, ephemeral ports, NAT gateway ports, listen backlog | Error vs connection rate | conntrack and ports |
| Node / pod | One node with broken iptables/CNI state or a full conntrack | Error vs node name | Cordon and compare; fix node |
| Deploys | LB connection draining too short; pods killed with open connections | Error vs deploy timestamps | preStop sleep; deregistration delay > longest request; graceful shutdown |
| UDP vs TCP DNS | Truncated answers retried over TCP that is blocked | Error vs answer size | Allow TCP 53 |
requests to api.internal (A records 10.0.1.10, 10.0.1.11, 10.0.1.12; .12 terminated)
1 req 1 -> 10.0.1.10 200
2 req 2 -> 10.0.1.11 200
3 req 3 -> 10.0.1.12 connect timeout <- 1 in 3 fails; all failures share one IPFix / how to use it: log the resolved peer IP, local port, connection reuse flag and phase timings with every outbound error (the netdiag output has all of them). Then group by each field.
MTU and fragmentation Must-know
In plain words: Every link has a maximum packet size. When a path contains a smaller link than the endpoints know about, big packets must be shrunk. The safety net is an ICMP message that says "too big, use this size". If someone blocks that message, big packets vanish silently while small ones pass: connections open, small requests work, big ones hang.
Common misunderstanding: "If ping works, MTU is fine." Default ping is 64 bytes. You must ping with the DF bit and a full-size payload (ping -M do -s 1472) to test the path MTU. Also: "lowering the MTU on my container fixes it." Lowering the MTU on both endpoints only lowers the TCP MSS they announce; the black hole is caused by a smaller link in the middle that the endpoints do not know about.
Definition. RFC 1191: when a router cannot forward a datagram "because it exceeds the MTU of the next-hop network and its Don't Fragment bit is set, the router is required to return an ICMP Destination Unreachable message to the source of the datagram, with the Code indicating 'fragmentation needed and DF set'"; the sender then "reduces its assumed PMTU for the path." (That is ICMP type 3 code 4 for IPv4; ICMPv6 "Packet Too Big" for IPv6, where routers never fragment.) RFC 2923 calls the failure mode "the long-standing black hole problem". RFC 4821 answers it with a method "that relies on TCP or some other Packetization Layer to probe an Internet path with progressively larger packets"; RFC 8899 does the same for datagram protocols (QUIC, UDP) and defines a black hole as when "a sender is unaware that packets are not being delivered to the destination endpoint."
| Term | Value / meaning |
|---|---|
| MTU (Ethernet) | 1500 bytes of IP packet |
| MSS (TCP over IPv4) | MTU − 20 (IP) − 20 (TCP) = 1460; with timestamps 1448 bytes of payload per segment |
ping -s | ICMP payload; 1472 + 8 (ICMP) + 20 (IP) = 1500 |
| DF bit | "Don't Fragment"; Linux sets it on TCP by default (PMTUD on) |
| WireGuard | Below 1500: 60 (IPv4) or 80 (IPv6) bytes of overhead (outer IP 20/40 + UDP 8 + WireGuard 32); see VPNs and tunnels |
| VXLAN (Flannel, Calico VXLAN, Docker overlay) | 50 bytes by header arithmetic (outer Ethernet 14 + IP 20 + UDP 8 + VXLAN 8): 1450 inside a 1500 underlay |
| GRE, PPPoE, IPsec | 24 (IP 20 + GRE 4), 8 (PPPoE header), IPsec varies with mode and cipher: measure it |
| AWS | 9001 inside a VPC (jumbo), 1500 over an internet gateway / VPN / inter-region peering |
Timeline (real, from Lab step 6):
1 client -> GET /small.txt small: 200 6 bytes 0.000290s
2 client -> GET /big.bin (response 200,000 bytes)
3 server sends 1448-byte segments, DF=1 -> router: next hop MTU 1400, drop, ICMP frag-needed suppressed
4 server retransmits seq 0:1448 at +0.2 s, +0.4 s, +0.8 s, +1.6 s (RTO backoff); nothing arrives
5 curl: (28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes receivedReal scenarios: a site-to-site VPN where SSH logins work but scp hangs; Kubernetes on VXLAN where pod MTU was left at 1500; a Docker host on a cloud VM whose own MTU is below 1500 while docker0 defaults to 1500; TLS handshakes that time out only through the corporate VPN; Cloudflare's write-up of PMTUD in practice, where ECMP load balancing sent the ICMP to the wrong server (their post shows the filter tcpdump -s0 -p -ni eth0 'icmp and icmp[0] == 3 and icmp[1] == 4').
| Fix | Where | How | Cost |
|---|---|---|---|
| Allow ICMP type 3 code 4 / ICMPv6 type 2 | Every firewall/SG on the path | Never "block all ICMP" | None; the proper fix |
| MSS clamping | The tunnel/router | iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu; nftables tcp option maxseg size set rt mtu | TCP only; UDP/QUIC still affected |
| Lower MTU on the overlay | CNI / Docker daemon / WireGuard | Docker com.docker.network.driver.mtu, "mtu" in daemon.json; Calico/Flannel MTU settings | Slightly more packets |
| Packetization-layer PMTUD | Sender hosts | net.ipv4.tcp_mtu_probing=1 ("enabled when an ICMP black hole detected") | Detection takes a few RTOs |
Commands: ping -M do -s 1472 host (the ping man page: do means "prohibit fragmentation, even local one"); bisect the size down until it passes; tracepath host ("traces path to a network host discovering MTU along this path"); ip route get IP shows a cached mtu after an ICMP was received; ss -ti prints pmtu: per connection. Fragmentation itself (when DF is off) is a different problem: fragments are dropped by many firewalls and need reassembly state; Cloudflare's post "Broken packets: IP fragmentation is flawed" explains why modern protocols avoid it.
conntrack and ephemeral ports Must-know
In plain words: Each outbound connection uses up an entry in several tables: a file descriptor in your process, a source port on your host, a row in the Linux connection-tracking table on every NATing node, and a port on the NAT gateway. Any one of them can fill up, and each fills up with a different error.
Common misunderstanding: "We have 65,535 ports, so 65,535 connections." Linux uses 32768-60999 for outgoing connections by default (28,232 ports), the limit applies per destination ip:port (the same source port can talk to many destinations), TIME_WAIT keeps a closed port busy for 60 seconds, and behind SNAT the limit is per public IP for everyone sharing it.
Definition. Kernel docs: ip_local_port_range "Defines the local port range that is used by TCP and UDP to choose the local port... The default values are 32768 and 60999 respectively." nf_conntrack_max: "Maximum number of allowed connection tracking entries"; nf_conntrack_count: "Number of currently allocated flow entries"; nf_conntrack_tcp_timeout_established default 432000 seconds (5 days). Cloudflare's "Conntrack tales" shows what happens at the limit: packets “were hard dropped. Conntrack on overfill does exactly that. It even complains in the "dmesg"”; the message in the kernel source (net/netfilter/nf_conntrack_core.c) is nf_conntrack: table full, dropping packet. Their ephemeral-ports post: "When the range is exhausted (against a single destination), we'll see EADDRNOTAVAIL error."
one pod, 1,000 req/s to partner:443 with a new connection per request (no keep-alive)
1 t=0 s each request: connect (new port) ... close (this side: TIME_WAIT 60 s)
2 t=28 s 28,000 ports in TIME_WAIT towards 203.0.113.10:443 on this host
3 t=29 s connect() -> EADDRNOTAVAIL "cannot assign requested address"
behind the node's SNAT: the same story with the node IP as the shared source
behind a NAT gateway: ~55,000 concurrent per public IP per destination (AWS), then ErrorPortAllocationReal scenarios:
| Table | Limit | Error/telltale | Counter | Fix |
|---|---|---|---|---|
| fds | ulimit -n (often 1024) | too many open files | /proc/PID/fd | raise limit; fix leaks |
| Ephemeral ports | 28,232 per destination ip:port per source IP | EADDRNOTAVAIL | ss -tan state time-wait | keep-alive/pool; wider range; more source IPs |
| conntrack | nf_conntrack_max | SYNs silently dropped: timeouts; dmesg table full, dropping packet | nf_conntrack_count, conntrack -S (drop, early_drop, insert_failed) | raise max and buckets; shorter timeouts; NOTRACK for known heavy flows |
| Docker/K8s node SNAT | source ports of the node IP shared by all pods | timeouts; insert_failed races | conntrack -S | masquerade with --random-fully (iptables-extensions: "Fully randomize source port mapping"); fewer, longer connections |
| AWS NAT gateway | "Each IPv4 address can support up to 55,000 simultaneous connections to each unique destination" (destination IP + port + protocol) | timeouts to one destination | CloudWatch ErrorPortAllocation ("could not allocate a source port") | more IPs on the NAT GW; connection reuse; VPC endpoints |
| AWS NAT gateway idle | 350 s idle | RST on next use | IdleTimeoutCount | keepalive < 350 s |
| Azure LB outbound | "64,000 ports are eligible for SNAT" per frontend IP, allocated per backend | SNAT port exhaustion | portal metrics | Azure NAT Gateway; more frontend IPs |
Fix / how to use it: connection reuse fixes every row at once (HTTP keep-alive, connection pools, gRPC/HTTP2 multiplexing). Then widen the specific limit. Tuning tcp_tw_reuse is mostly unnecessary on modern kernels (default 2: "enable for loopback traffic only"), and the kernel docs warn it "should not be changed without advice/request of technical experts". tcp_tw_recycle no longer appears in the kernel's ip-sysctl documentation and must not appear in a modern tuning guide. Cloudflare's post shows the IP_BIND_ADDRESS_NO_PORT socket option for clients that bind a source IP before connecting, so port selection still happens per destination.
Packet capture Must-know
In plain words: When logs disagree, the packets decide. tcpdump records what actually crossed an interface; Wireshark helps you read it.
Common misunderstanding: "Capture on the client and you have seen everything." You have seen what the client's interface saw. Capture on both ends (and on the node/host for containers) to prove where a packet disappears. Also: with TLS you see the handshake and sizes, not the HTTP, unless you decrypt with a key log from your own client.
Definition: the filters you need. pcap-filter(7) lists the flag constants "tcp-fin, tcp-syn, tcp-rst, tcp-push, tcp-ack, tcp-urg, tcp-ece, tcp-cwr".
| Goal | tcpdump (capture) filter | Wireshark display filter |
|---|---|---|
| One conversation | host 10.0.3.7 and port 5432 | ip.addr==10.0.3.7 && tcp.port==5432 |
| Connection attempts | 'tcp[tcpflags] & tcp-syn != 0' | tcp.flags.syn==1 && tcp.flags.ack==0 |
| Resets | 'tcp[tcpflags] & tcp-rst != 0' | tcp.flags.reset==1 |
| Retransmissions | (not expressible) | tcp.analysis.retransmission |
| Duplicate ACKs / zero window | — | tcp.analysis.duplicate_ack, tcp.analysis.zero_window |
| All TCP problems | — | tcp.analysis.flags |
| ICMP frag-needed | 'icmp[0] == 3 and icmp[1] == 4' | icmp.type==3 && icmp.code==4 |
| DNS | port 53 | dns, dns.flags.rcode != 0 |
| TLS ClientHello | 'tcp[((tcp[12]&0xf0)>>2)] = 0x16' | tls.handshake.type==1 |
Practice.
# write a file, full packets, no name resolution, all interfaces
tcpdump -ni any -s 0 -w /tmp/cap.pcap 'host 10.0.3.7 and port 5432'
# rotating capture for an intermittent problem: 10 files of 100 MB, oldest overwritten
tcpdump -ni eth0 -s 0 -C 100 -W 10 -w /var/tmp/ring.pcap 'port 443'
# read it back with relative timestamps and hex
tcpdump -nr /tmp/cap.pcap -ttt -X
# inside a container: share its network namespace
docker run --rm -it --net container:app nicolaka/netshoot tcpdump -ni eth0 port 8080
# inside a pod: ephemeral debug container
kubectl debug -it pod/app --image=nicolaka/netshoot --target=app -- tcpdump -ni eth0 port 8080
# from the node into a container's namespace
nsenter -t "$(docker inspect -f '{{.State.Pid}}' app)" -n tcpdump -ni eth0 port 8080Reading a capture. Wireshark's TCP analysis flags (from its user guide): "TCP Retransmission" when "the next expected sequence number is greater than the current sequence number"; "TCP Dup ACK" when "the segment size is zero" and the ACK repeats; "TCP ZeroWindow" when "the receive window size is zero" (the receiver's application is not reading: an application problem, not a network one). Follow TCP Stream (Analyze → Follow → TCP Stream) shows one conversation's payload. For TLS from your own client: set SSLKEYLOGFILE=/tmp/keys.log before running curl, Firefox or Chrome; the Wireshark wiki explains that their TLS library "writes the required per-session secrets to a file", which you load in Preferences → Protocols → TLS → "(Pre)-Master-Secret log filename". Go has the same: tls.Config{KeyLogWriter: f} (only in debug builds).
A real RST, annotated (from the Lab, tcpdump -X, client 10.240.1.5 to fw port 81 with REJECT --reject-with tcp-reset): see the hex dump in Lab step 7.
Latency and loss tools Important
In plain words: Some failures are not errors but slowness or loss. These tools tell you where along the path time goes and packets disappear.
Common misunderstanding: "mtr shows 30 % loss at hop 5, so hop 5 is the problem." Routers rate-limit the ICMP they generate for TTL-expired probes. Loss at a middle hop that does not continue to the final hop is just a busy router control plane. Only loss that persists to the destination is real.
Definition:
| Tool | What it sends | Answers | Watch out |
|---|---|---|---|
ping | ICMP echo | RTT, loss to one host | ICMP may be blocked or deprioritised; not your port |
traceroute | UDP to high ports by default; -I ICMP; -T TCP SYN (to port 80 or -p) | Hops by TTL expiry | Firewalls treat each protocol differently: use -T -p 443 to see the path your HTTPS takes |
tracepath | UDP, no root | Hops and PMTU | |
mtr | Continuous traceroute (--tcp, --udp, -P port) | Per-hop loss and latency over time | "mtr combines the functionality of the traceroute and ping programs"; read loss at the last hop |
iperf3 | TCP/UDP bulk | Throughput, retransmits, jitter | Needs a server end (iperf3 -s) |
curl -w | Your real request | DNS/connect/TLS/TTFB split | The best first tool for HTTP |
ss -ti | — | Per-connection rtt:, retrans:, cwnd:, pmtu: | Live sockets only |
nstat / netstat -s | — | Kernel counters: retransmits, resets, listen overflows | Use deltas: nstat prints changes since the last run |
illustrative (not from this lab): mtr --tcp -P 443 -r -c 50 api.example.com
1 gw 0.0% loss 0.4 ms
2 isp-edge 0.0% 3.1 ms
3 core-a 40.0% 9.0 ms <- ICMP rate limit; next hops are fine
4 peer 0.0% 11.2 ms
5 api 0.0% 11.5 ms <- destination: 0 % loss, so the path is fineReal scenarios: an API that is slow only from one region (mtr from that region; RTT jump at the peering hop); upload throughput far below the link (iperf3 shows retransmits; ss -ti shows retrans:); a service whose p99 rises while CPU is idle (nstat TcpRetransSegs rising).
Fix / how to use it: ss -tino dst IP on a live connection prints lines like this real one from the Lab: rtt:10.303/18.066 ato:40 mss:1348 pmtu:1400 ... retrans:0/1 ... rwnd_limited:1982ms(98.0%); the ss man page defines rtt:<rtt>/<rttvar> as "the average round trip time" and its mean deviation. nstat -az | grep -E 'Retrans|ListenOverflows|ListenDrops|TCPTimeouts|AttemptFails|EstabResets' gives the counters to alert on.
Mechanics
Error strings per client
Every cell below was produced in Linux containers on this machine (Docker 29 on a 7.0 kernel, Go 1.27 static binary on Alpine 3.24, curl 8 in curlimages/curl and Alpine, psql from postgres:16-alpine, redis-cli from redis:8-alpine, PHP 8.5 from php:8.5-cli-alpine). A dash means we did not reproduce that client for that case; do not guess its text, reproduce it. Laravel wraps libcurl, so its ConnectionException message carries the same cURL error N text as the curl CLI.
| Symptom | Go | curl | psql | redis-cli | PHP stream_socket_client |
|---|---|---|---|---|---|
| Refused | dial tcp 10.231.0.10:81: connect: connection refused | (7) Failed to connect to ntp-web:81 after 0 ms: Could not connect to server | connection to server at "ntp-web" (10.231.0.10), port 5432 failed: Connection refused | Could not connect to Redis at ntp-web:6379: Connection refused | errno=111 "Connection refused" |
| Timeout (client deadline) | dial tcp 10.231.0.99:80: i/o timeout | (28) Connection timed out after 2005 milliseconds | ... port 5432 failed: timeout expired | — | errno=110 "Operation timed out" |
| Timeout (kernel gave up) | dial tcp 10.240.1.20:80: connect: connection timed out | — | — | — | — |
| No route (ARP failed) | connect: no route to host (after 3.1 s) | (7) Failed to connect to 10.231.0.99:80 after 3093 ms: Could not connect to server | — | Could not connect to Redis at 10.231.0.99:6379: Host is unreachable | errno=113 "Host is unreachable" |
| ICMP admin prohibited | dial tcp 10.240.1.20:82: connect: no route to host | (7) Failed to connect to 10.240.1.20:82 after 0 ms | — | — | — |
| No default route | connect: network is unreachable | (7) Failed to connect to 1.1.1.1:80 after 0 ms | — | — | — |
| NXDOMAIN | lookup ntp-wbe on 127.0.0.11:53: no such host | (6) Could not resolve host: ntp-wbe | could not translate host name "postgress" to address: Try again | Could not connect to Redis at postgress:6379: Name has no usable address | getaddrinfo for ntp-wbe failed: Name does not resolve |
| SERVFAIL (internal network, external name) | — | (6) Could not resolve host: example.com (DNS server returned general failure) | — | — | — |
| Not TLS on TLS port | tls: first record does not look like a TLS handshake | (35) TLS connect error: error:0A00010B:SSL routines::wrong version number | — | — | — |
| Reset | read: connection reset by peer | — | — | — | — |
| Broken pipe | write: broken pipe | — | — | — | — |
| Empty reply / closed without response | Post "http://127.0.0.1:9202/": EOF | (52) Empty reply from server | — | — | — |
| Body shorter than Content-Length | unexpected EOF | — | — | — | — |
| fds | dial tcp 127.0.0.1:9102: socket: too many open files | — | — | — | — |
| Ports | connect: cannot assign requested address | — | — | — | — |
| Client timeout waiting for headers | context deadline exceeded (Client.Timeout exceeded while awaiting headers) | — | — | — | — |
| Body stalls after headers (MTU black hole) | — | (28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes received | — | — | — |
For the rest, the curl manual documents the exit codes: 6 "Could not resolve host", 7 "Failed to connect to host", 28 "Operation timeout", 52 "The server did not reply anything", 55 "Failed sending network data", 56 "Failure in receiving network data" (the last two are what a reset or broken pipe produce mid-transfer). Note also that the curl on macOS prints Couldn't connect to server where curl 8 on Linux prints Could not connect to server: one more reason to grep for the exit code, not the sentence.
Why the same errno prints differently
The kernel returns a number; the text comes from whoever formats it. Go has its own table (syscall.Errno.Error()), glibc and musl each have one, and drivers add their own prefix. Grep logs for the errno name or the stable fragment, not the whole sentence.
| Errno | Go | glibc (strerror, Ubuntu) | musl (Alpine) | PHP/Laravel (via libcurl) |
|---|---|---|---|---|
ECONNREFUSED 111 | connection refused | Connection refused | Connection refused | cURL error 7 |
ETIMEDOUT 110 | connection timed out | Connection timed out | Operation timed out | cURL error 28 |
EHOSTUNREACH 113 | no route to host | No route to host | Host is unreachable | cURL error 7 |
ENETUNREACH 101 | network is unreachable | Network is unreachable | Network unreachable | cURL error 7 |
ECONNRESET 104 | connection reset by peer | Connection reset by peer | Connection reset by peer | cURL error 56 |
EADDRNOTAVAIL 99 | cannot assign requested address | Cannot assign requested address | Address not available | cURL error 7 |
EAI_NONAME (resolver: name not found) | no such host (Go's own resolver) | Name or service not known | Name does not resolve (or Try again, EAI_AGAIN, seen from psql and nc for the same typo) | cURL error 6 |
Every cell was printed on this machine: Go by the netdiag runs, glibc by perl -MPOSIX in an Ubuntu-based image (mongo:8.0), musl by posix_strerror() in php:8.5-cli-alpine. The errno numbers are Linux's; macOS uses other numbers (ECONNREFUSED is 61 there), which is one more reason to reproduce in the same OS as production. In Go, never match strings: use errors.Is(err, syscall.ECONNREFUSED), errors.As(err, &dnsErr) (*net.DNSError has IsNotFound, IsTimeout, IsTemporary) and net.Error.Timeout().
The layer-by-layer checklist
Run it top to bottom from the failing place. Stop at the first "no".
| # | Layer | Question | Command | Good answer |
|---|---|---|---|---|
| 1 | Link | Is the interface up, with the expected MTU? | ip -br link, ip link show eth0 | UP, mtu 1500 (or the overlay's value) |
| 2 | IP | Do I have the address I think? | ip -br addr | Expected subnet |
| 3 | Route | Which route and source would be used? | ip route get 10.0.3.7 | via GW dev eth0 src ... |
| 4 | ARP/NDP | Is the next hop resolvable? | ip neigh | REACHABLE/STALE, not FAILED |
| 5 | Firewall (local) | Is anything dropping on this host? | iptables -L -v -n, nft list ruleset | No growing DROP counter for this flow |
| 6 | NAT | Is the flow translated as expected? | conntrack -L -d IP, iptables -t nat -S | Reply tuple shows the backend |
| 7 | DNS | Does the name resolve here, to the right IP? | getent hosts name, dig name | Expected IP, fast |
| 8 | Transport | Does the SYN get an answer? | nc -vz -w3 IP PORT | succeeded |
| 9 | TLS | Handshake and certificate ok? | openssl s_client -connect IP:443 -servername name | Verify return code: 0 (ok) |
| 10 | HTTP | Full response, in time? | curl -sv -w '%{http_code} %{time_total}\n' URL | Expected status and time |
Kernel knobs and defaults
| Knob | Default | Affects | Source |
|---|---|---|---|
net.ipv4.tcp_syn_retries | 6 (67 s with linear timeouts; ~127 s on older kernels) | How long a dropped SYN takes to fail | kernel ip-sysctl, tcp(7) |
net.ipv4.tcp_syn_linear_timeouts | 4 | SYN retransmissions at a fixed 1 s before exponential backoff | kernel ip-sysctl |
net.ipv4.ip_local_port_range | 32768 60999 | Ephemeral ports | kernel ip-sysctl |
net.ipv4.ip_local_reserved_ports | empty | Ports excluded from automatic assignment | kernel ip-sysctl |
net.ipv4.tcp_tw_reuse | 2 (loopback only) | Reusing TIME_WAIT ports for new outbound connections | kernel ip-sysctl |
net.ipv4.tcp_mtu_probing | 0 | Packetization-layer PMTUD (1 = after a black hole is detected) | kernel ip-sysctl |
net.ipv4.ip_no_pmtu_disc | 0 | Disables PMTUD (do not) | kernel ip-sysctl |
net.netfilter.nf_conntrack_max | nf_conntrack_buckets (memory-based) | conntrack table size | kernel nf_conntrack-sysctl |
net.netfilter.nf_conntrack_tcp_timeout_established | 432000 (5 days) | How long idle established flows stay | kernel nf_conntrack-sysctl |
net.core.somaxconn | 4096 (kernel 5.4+) | Listen backlog cap | listen(2) |
ulimit -n | 1024 soft on many distros | fds per process | shell/systemd |
Counters worth knowing
| Counter | Where | Means when it rises |
|---|---|---|
TcpRetransSegs | nstat | Loss or congestion somewhere on the path |
TcpExtListenOverflows, TcpExtListenDrops | nstat (server) | Accept queue full: app not accepting fast enough |
TcpAttemptFails | nstat | Outbound connects failing (refused, reset in SYN-SENT) |
TcpEstabResets | nstat | Established connections reset |
TcpExtTCPTimeouts | nstat | RTO fired: packets unacknowledged |
nf_conntrack_count vs nf_conntrack_max | /proc/sys/net/netfilter/ | Saturation of the conntrack table |
drop, early_drop, insert_failed | conntrack -S | conntrack full, or NAT port allocation races |
retrans: / rtt: / pmtu: | ss -ti | Per-connection health |
Flow log REJECT records | AWS VPC Flow Logs | Security group/NACL denied the flow |
ErrorPortAllocation, IdleTimeoutCount, PacketsDropCount | CloudWatch NAT gateway | NAT port exhaustion, idle resets, drops |
Containers and Kubernetes
| Question | Docker | Kubernetes |
|---|---|---|
| Get a shell with tools in the app's network namespace | docker run --rm -it --net container:app nicolaka/netshoot | kubectl debug -it pod/app --image=nicolaka/netshoot --target=app |
| Same, from the host | nsenter -t PID -n (PID from docker inspect) | nsenter on the node, or kubectl debug node/NODE -it --image=... |
| What listens inside? | docker exec app ss -ltn or via netshoot | same via ephemeral container |
| Is the port published? | docker port app, docker ps PORTS column | Service port/targetPort, kubectl get svc |
| Does the name resolve inside? | Embedded DNS 127.0.0.11: nslookup svc | kubectl exec -i -t dnsutils -- nslookup kubernetes.default |
| Does the Service have backends? | — | kubectl get endpointslices -l kubernetes.io/service-name=svc (empty: selector or readiness) |
| Bypass Service/Ingress/policy to test the pod itself | docker exec / curl the container IP | kubectl port-forward pod/app 8080:8080 then curl localhost:8080 |
| Who is dropping? | iptables -L DOCKER-USER -v, docker network inspect | kubectl get networkpolicy -A; kube-proxy rules iptables -t nat -L KUBE-SERVICES, ipvsadm -Ln |
| MTU | docker network inspect option com.docker.network.driver.mtu (bridge driver option: "Set the containers network Maximum Transmission Unit") | CNI MTU (Calico/Flannel/Cilium setting), ip link inside pod |
Ephemeral containers became stable in Kubernetes v1.25; the docs describe them as useful "when kubectl exec is insufficient because a container has crashed or a container image doesn't include debugging utilities, such as with distroless images." kubectl port-forward is the best bisection tool in Kubernetes: if the pod answers through port-forward but not through the Service, the problem is Service selector, endpoints, kube-proxy or NetworkPolicy, not the app. NetworkPolicy semantics in one line from the docs: "By default, a pod is non-isolated for ingress"; as soon as any policy with Ingress in policyTypes selects it, only allowed traffic passes.
Cloud: security group vs NACL vs route table vs NAT gateway
| Layer (AWS names; Azure/GCP have equivalents) | Stateful? | Typical symptom when wrong | Evidence |
|---|---|---|---|
| Security group | Yes: "Return traffic: Automatically allowed (stateful)" | Connect timeout | Flow Logs REJECT; Reachability Analyzer |
| Network ACL | No: return traffic "Must be explicitly allowed (stateless)", rules evaluated "in ascending order until a match" | Timeout, often only for replies to ephemeral ports | Flow Logs REJECT on the return direction |
| Route table | — | Timeout (no route to NAT/IGW/peering), or asymmetric path | Route table of the subnet; traceroute -T |
| NAT gateway | Yes (it is NAT) | Timeouts under load (ErrorPortAllocation), RST after 350 s idle | CloudWatch NAT metrics |
| Load balancer | — | 502/503/504, resets after the idle timeout (ALB default 60 s), targets "unhealthy" | LB access logs, target health reason codes |
| Target health check | — | Healthy app marked unhealthy: wrong path/port, SG not allowing the LB, HealthCheckTimeoutSeconds (default 5 s for instance/ip targets) too short | Target group health description |
AWS VPC Flow Logs "capture information about the IP traffic going to and from network interfaces", and the docs list "Diagnosing overly restrictive security group rules" as the first use. Each record carries the 5-tuple, bytes, packets and ACCEPT/REJECT. A NACL problem looks like this in flow logs: the inbound SYN is ACCEPT, the outbound reply to an ephemeral port is REJECT.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| "It fails" with no detail | Run the ladder from the failing place | Go netdiag, Laravel net:diag | Names the rung and errno in one run | Needs a shell or an Artisan command in the target environment |
| Connect hangs for minutes | Connect timeout separate from read timeout | net.Dialer{Timeout}, connectTimeout(), connect_timeout | Fails in seconds, frees workers | Too short a value fails on slow but healthy paths |
| Sporadic reset/EOF after idle | Client idle timeout below middlebox idle timeout; keepalive | IdleConnTimeout: 50s behind a 60 s ALB | Removes the keep-alive race | Slightly more connections |
| Ephemeral port / NAT port exhaustion | Connection reuse | One shared client, pool sizes, HTTP/2 | Fixes fds, ports, conntrack, NAT at once | Must bound pools; long-lived connections need rebalancing |
| MTU black hole | Allow ICMP frag-needed; clamp MSS; set overlay MTU | See MTU | Fixes all sizes | Needs access to the middle box |
| Can't prove where packets die | Capture on both ends | tcpdump -w + Wireshark | Hard evidence for other teams | Needs root/caps; privacy of payloads |
| Health checks restart healthy pods during a DB outage | Split liveness (/up) from readiness (/ready) with dependency checks and timeouts | Laravel controller below | Outage removes traffic, not processes | Readiness must not flap: use timeouts and thresholds |
| Next incident takes as long as this one | Keep the counters and probes | Observability to keep | Detection before users notice | Storage and alert hygiene |
Go: netdiag, the ladder in one binary
It resolves, connects to every returned IP with a timeout, does the TLS handshake with SNI, sends one HTTP request, and stops at the first failing rung with the errno and its meaning. errors.Is/errors.As see through *net.OpError and *os.SyscallError, so the classification never parses strings.
// Command netdiag walks the connection ladder for one URL:
// resolve -> TCP connect -> TLS handshake -> HTTP request,
// and stops at the first rung that fails, naming the errno and what it implies.
//
// netdiag -timeout 3s https://api.example.com/health
// netdiag tcp://db:5432 (stops after the TCP rung)
package main
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"syscall"
"time"
)
func main() {
timeout := flag.Duration("timeout", 3*time.Second, "timeout per rung")
flag.Parse()
if flag.NArg() != 1 {
fmt.Fprintln(os.Stderr, "usage: netdiag [-timeout 3s] https://host[:port]/path | tcp://host:port")
os.Exit(64)
}
u, err := url.Parse(flag.Arg(0))
if err != nil || u.Hostname() == "" {
fmt.Fprintln(os.Stderr, "bad URL:", flag.Arg(0))
os.Exit(64)
}
port := u.Port()
if port == "" {
port = map[string]string{"http": "80", "https": "443"}[u.Scheme]
}
// Rung 1: DNS. The resolver Go uses honours /etc/hosts, resolv.conf and ndots.
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
start := time.Now()
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, u.Hostname())
cancel()
if err != nil {
fail(1, "dns", err)
}
fmt.Printf("[1/4] dns %s -> %v (%s)\n", u.Hostname(), addrs, since(start))
// Rung 2: TCP. Try every address, like a real client; report each failure.
var conn net.Conn
for _, a := range addrs {
target := net.JoinHostPort(a.IP.String(), port)
d := net.Dialer{Timeout: *timeout}
start = time.Now()
conn, err = d.Dial("tcp", target)
if err == nil {
fmt.Printf("[2/4] tcp %s connected from %s (%s)\n", target, conn.LocalAddr(), since(start))
break
}
fmt.Printf(" tcp %s failed after %s: %s\n", target, since(start), classify(err))
}
if conn == nil {
fail(2, "tcp", err)
}
defer conn.Close()
if u.Scheme == "tcp" {
return
}
// Rung 3: TLS (https only). SNI and verification use the hostname, not the IP.
if u.Scheme == "https" {
tc := tls.Client(conn, &tls.Config{ServerName: u.Hostname(), NextProtos: []string{"http/1.1"}})
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
start = time.Now()
err = tc.HandshakeContext(ctx)
cancel()
if err != nil {
fail(3, "tls", err)
}
st := tc.ConnectionState()
fmt.Printf("[3/4] tls %s, cert CN=%q (%s)\n", tls.VersionName(st.Version), st.PeerCertificates[0].Subject.CommonName, since(start))
conn = tc
} else {
fmt.Println("[3/4] tls skipped (plain http)")
}
// Rung 4: HTTP. One request on the connection we already proved.
req, _ := http.NewRequest(http.MethodGet, u.String(), nil)
req.Header.Set("User-Agent", "netdiag/1")
req.Close = true
_ = conn.SetDeadline(time.Now().Add(*timeout))
start = time.Now()
if err = req.Write(conn); err != nil {
fail(4, "http", err)
}
resp, err := http.ReadResponse(bufio.NewReader(conn), req)
if err != nil {
fail(4, "http", err)
}
n, _ := io.Copy(io.Discard, resp.Body)
resp.Body.Close()
fmt.Printf("[4/4] http %s, %d body bytes (%s)\n", resp.Status, n, since(start))
if resp.StatusCode >= 500 {
os.Exit(5) // the network is fine; the server is not
}
}
// classify turns an error into "ERRNO: meaning" using errors.Is/As,
// which see through *net.OpError, *os.SyscallError and *url.Error wrappers.
func classify(err error) string {
var dnsErr *net.DNSError
var certErr *tls.CertificateVerificationError
var hostErr x509.HostnameError
var recErr tls.RecordHeaderError
switch {
case errors.As(err, &dnsErr) && dnsErr.IsNotFound:
return fmt.Sprintf("NXDOMAIN/no such host (server %s): name typo, wrong search domain, record missing", dnsErr.Server)
case errors.As(err, &dnsErr) && dnsErr.IsTimeout:
return fmt.Sprintf("DNS timeout (server %s): resolver unreachable or UDP/53 filtered", dnsErr.Server)
case errors.As(err, &dnsErr):
return fmt.Sprintf("DNS failure %q (server %s): SERVFAIL or a broken upstream", dnsErr.Err, dnsErr.Server)
case errors.Is(err, syscall.ECONNREFUSED):
return "ECONNREFUSED: the host answered with RST; nothing listens on that ip:port (wrong port, bound to 127.0.0.1, process down) or a REJECT rule"
case errors.Is(err, syscall.EHOSTUNREACH):
return "EHOSTUNREACH: no ARP answer on the local subnet, or an ICMP host-unreachable/host-prohibited from a router or firewall"
case errors.Is(err, syscall.ENETUNREACH):
return "ENETUNREACH: no route to that network in the local routing table (missing default route, IPv6 without connectivity)"
case errors.Is(err, syscall.EADDRNOTAVAIL):
return "EADDRNOTAVAIL: no free local ephemeral port for this destination (port exhaustion) or binding a non-local address"
case errors.Is(err, syscall.EMFILE), errors.Is(err, syscall.ENFILE):
return "EMFILE/ENFILE: out of file descriptors (ulimit -n); leaked connections or too low a limit"
case errors.Is(err, syscall.ECONNRESET):
return "ECONNRESET: the peer (or a middlebox: LB, NAT, firewall) sent RST on an established connection"
case errors.Is(err, syscall.EPIPE):
return "EPIPE: wrote to a connection the peer already closed/reset"
case errors.Is(err, syscall.ETIMEDOUT):
return "ETIMEDOUT: the kernel gave up retransmitting (SYN or data never acknowledged)"
case errors.As(err, &certErr), errors.As(err, &hostErr):
return "certificate rejected: " + err.Error() + " (see the TLS chapter)"
case errors.As(err, &recErr):
return "not TLS: the server answered with plain bytes (wrong port or plain HTTP on 443)"
case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
return "EOF: the peer closed the connection without a full answer (crash, idle-timeout close, proxy limit)"
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return "timeout: no answer within our deadline; packets are being dropped (firewall/SG/NACL DROP, wrong route, host down) or the peer is stalled"
}
return "unclassified: " + err.Error()
}
func fail(rung int, name string, err error) {
fmt.Printf("FAIL rung %d (%s): %v\n %s\n", rung, name, err, classify(err))
os.Exit(rung)
}
func since(t time.Time) time.Duration { return time.Since(t).Round(time.Millisecond) }Real runs (Linux container, Docker network ntplab, nginx at 10.231.0.10):
$ netdiag http://ntp-web/
[1/4] dns ntp-web -> [{10.231.0.10 }] (1ms)
[2/4] tcp 10.231.0.10:80 connected from 10.231.0.2:47494 (0s)
[3/4] tls skipped (plain http)
[4/4] http 200 OK, 896 body bytes (0s)
$ netdiag tcp://ntp-web:81
[1/4] dns ntp-web -> [{10.231.0.10 }] (1ms)
FAIL rung 2 (tcp): dial tcp 10.231.0.10:81: connect: connection refused
ECONNREFUSED: the host answered with RST; nothing listens on that ip:port (wrong port, bound to 127.0.0.1, process down) or a REJECT rule
$ netdiag -timeout 15s tcp://10.231.0.99:80
tcp 10.231.0.99:80 failed after 3.101s: EHOSTUNREACH: no ARP answer on the local subnet, ...
FAIL rung 2 (tcp): dial tcp 10.231.0.99:80: connect: no route to host
$ netdiag http://ntp-wbe/
FAIL rung 1 (dns): lookup ntp-wbe on 127.0.0.11:53: no such host
NXDOMAIN/no such host (server 127.0.0.11:53): name typo, wrong search domain, record missing
$ netdiag -timeout 2s https://ntp-web:80/
[2/4] tcp 10.231.0.10:80 connected from 10.231.0.2:42402 (0s)
FAIL rung 3 (tls): tls: first record does not look like a TLS handshake
not TLS: the server answered with plain bytes (wrong port or plain HTTP on 443)
$ ip route del default; netdiag -timeout 2s tcp://1.1.1.1:443
FAIL rung 2 (tcp): dial tcp 1.1.1.1:443: connect: network is unreachableThe exit code is the rung number, so a CI smoke test or a Kubernetes init container can tell "DNS broken" (1) from "port closed" (2) from "server error" (5).
Go: timing and a client that survives middleboxes
// Command timing prints a curl -w style breakdown for one HTTP request with
// net/http/httptrace, and shows the client settings that prevent the classic
// "connection reset by peer" on reused idle connections.
package main
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptrace"
"os"
"time"
)
// newClient: every timeout set, idle connections retired BEFORE the shortest
// idle timeout on the path (AWS ALB default 60 s, AWS NAT gateway 350 s).
func newClient() *http.Client {
dialer := &net.Dialer{
Timeout: 3 * time.Second, // connect timeout: a dropped SYN fails fast
KeepAlive: 30 * time.Second, // TCP keepalive probes on idle sockets
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
IdleConnTimeout: 50 * time.Second, // < 60 s ALB idle timeout
MaxIdleConns: 100,
MaxIdleConnsPerHost: 32, // default is 2: bursts open (and TIME_WAIT) many ports
ForceAttemptHTTP2: true,
}
return &http.Client{Transport: tr, Timeout: 15 * time.Second}
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "usage: timing URL")
os.Exit(64)
}
client := newClient()
for i := 1; i <= 2; i++ { // the second request shows connection reuse
var t0, dnsStart, dnsDone, connStart, connDone, tlsStart, tlsDone, firstByte time.Time
var reused bool
trace := &httptrace.ClientTrace{
DNSStart: func(httptrace.DNSStartInfo) { dnsStart = time.Now() },
DNSDone: func(httptrace.DNSDoneInfo) { dnsDone = time.Now() },
ConnectStart: func(_, _ string) { connStart = time.Now() },
ConnectDone: func(_, _ string, _ error) { connDone = time.Now() },
TLSHandshakeStart: func() { tlsStart = time.Now() },
TLSHandshakeDone: func(tls.ConnectionState, error) { tlsDone = time.Now() },
GotConn: func(i httptrace.GotConnInfo) { reused = i.Reused },
GotFirstResponseByte: func() { firstByte = time.Now() },
}
req, _ := http.NewRequest(http.MethodGet, os.Args[1], nil)
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
t0 = time.Now()
resp, err := client.Do(req)
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
fmt.Printf("request %d: %s reused=%v dns=%s connect=%s tls=%s ttfb=%s total=%s\n",
i, resp.Status, reused, d(dnsStart, dnsDone), d(connStart, connDone),
d(tlsStart, tlsDone), firstByte.Sub(t0).Round(time.Millisecond), time.Since(t0).Round(time.Millisecond))
}
}
func d(a, b time.Time) time.Duration {
if a.IsZero() {
return 0 // phase skipped: cached DNS or a reused connection
}
return b.Sub(a).Round(time.Millisecond)
}$ timing http://ntp-web/
request 1: 200 OK reused=false dns=1ms connect=0s tls=0s ttfb=3ms total=3ms
request 2: 200 OK reused=true dns=0s connect=0s tls=0s ttfb=0s total=0sThe second request skips DNS, connect and TLS because the connection was reused. If you see reused=false on every request in production, you are paying the handshake each time and burning ephemeral ports (usual causes: not draining/closing resp.Body, a new http.Client per request, or MaxIdleConnsPerHost left at its default of 2 under concurrency).
Go: a PMTU probe that does not trust ICMP
//go:build linux
// Command pmtuprobe finds the largest datagram that really crosses a path,
// in the spirit of RFC 8899 (DPLPMTUD): it does not trust ICMP; it sends
// probes with the DF bit set and counts only sizes that the far end echoes.
//
// pmtuprobe -listen :9999 (on the far end: a UDP echo)
// pmtuprobe -target 10.0.2.20:9999 (on the near end)
package main
import (
"errors"
"flag"
"fmt"
"net"
"os"
"syscall"
"time"
)
const ipUDPHeaders = 28 // 20-byte IPv4 header + 8-byte UDP header
func main() {
listen := flag.String("listen", "", "run the UDP echo responder on this address")
target := flag.String("target", "", "probe the path to this echo responder")
flag.Parse()
switch {
case *listen != "":
echo(*listen)
case *target != "":
probe(*target)
default:
flag.Usage()
os.Exit(64)
}
}
func echo(addr string) {
pc, err := net.ListenPacket("udp4", addr)
if err != nil {
panic(err)
}
buf := make([]byte, 65535)
for {
n, from, err := pc.ReadFrom(buf)
if err != nil {
continue
}
// Echo only the length (4 bytes), so the reply itself never hits the limit.
_, _ = pc.WriteTo([]byte(fmt.Sprintf("%04d", n%10000)), from)
}
}
func probe(target string) {
conn, err := net.Dial("udp4", target)
if err != nil {
panic(err)
}
defer conn.Close()
raw, _ := conn.(*net.UDPConn).SyscallConn()
// IP_PMTUDISC_DO: set DF on every packet and never fragment locally.
_ = raw.Control(func(fd uintptr) {
err = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_MTU_DISCOVER, syscall.IP_PMTUDISC_DO)
})
if err != nil {
panic(err)
}
lo, hi := 576, 9000 // RFC 791 minimum datagram every host must accept .. jumbo frames
for lo < hi {
mid := (lo + hi + 1) / 2
switch ok, why := try(conn, mid); {
case ok:
fmt.Printf("probe %5d bytes: echoed\n", mid)
lo = mid
default:
fmt.Printf("probe %5d bytes: %s\n", mid, why)
hi = mid - 1
}
}
fmt.Printf("path MTU (confirmed by echo): %d bytes\n", lo)
fmt.Printf("kernel's cached PMTU (from ICMP, IP_MTU): %d bytes\n", kernelMTU(raw))
fmt.Printf("largest TCP MSS that fits: %d bytes\n", lo-40)
}
func try(conn net.Conn, size int) (bool, string) {
payload := make([]byte, size-ipUDPHeaders)
for attempt := 0; attempt < 3; attempt++ {
if _, err := conn.Write(payload); err != nil {
if errors.Is(err, syscall.EMSGSIZE) {
return false, "EMSGSIZE (bigger than the local/cached PMTU, refused before sending)"
}
if errors.Is(err, syscall.ECONNREFUSED) {
return false, "ECONNREFUSED (ICMP port unreachable: no echo responder)"
}
return false, err.Error()
}
_ = conn.SetReadDeadline(time.Now().Add(400 * time.Millisecond))
buf := make([]byte, 16)
if _, err := conn.Read(buf); err == nil {
return true, ""
}
}
return false, "no echo after 3 tries (dropped: black hole or ICMP frag-needed filtered)"
}
func kernelMTU(raw syscall.RawConn) int {
mtu := -1
_ = raw.Control(func(fd uintptr) {
mtu, _ = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_MTU)
})
return mtu
}//go:build !linux
package main
import (
"fmt"
"os"
)
// The DF bit and IP_MTU are Linux socket options; run the probe in a Linux
// container (docker run --rm -v "$PWD":/w -w /w golang go run ./pmtuprobe ...).
func main() {
fmt.Fprintln(os.Stderr, "pmtuprobe needs Linux (IP_MTU_DISCOVER / IP_MTU)")
os.Exit(1)
}The probe sets IP_PMTUDISC_DO (DF on, never fragment locally), binary-searches the datagram size and counts a size as good only when the far end echoes it: the RFC 8899 idea of confirming with acknowledgements instead of waiting for ICMP. It also prints the kernel's cached PMTU (IP_MTU), which only changes if an ICMP "fragmentation needed" arrived. Through a black hole the two numbers disagree; that disagreement is the diagnosis. Real output is in Lab step 6.
Go: reproducing ephemeral port exhaustion
// Command portexhaust reproduces ephemeral-port exhaustion against ONE
// destination ip:port. Run it in a container with a tiny port range:
//
// docker run --rm --sysctl net.ipv4.ip_local_port_range="40000 40009" ...
// portexhaust -serve :8080 (accept and hold)
// portexhaust -target srv:8080 -n 50 (open and keep 50 connections)
// portexhaust -target srv:8080 -churn (open+close: TIME_WAIT version)
package main
import (
"errors"
"flag"
"fmt"
"net"
"os"
"syscall"
"time"
)
func main() {
serve := flag.String("serve", "", "accept connections on this address and hold them")
target := flag.String("target", "", "destination ip:port")
n := flag.Int("n", 100, "connections to attempt")
churn := flag.Bool("churn", false, "close each connection right away (client side ends in TIME_WAIT)")
flag.Parse()
if *serve != "" {
ln, err := net.Listen("tcp", *serve)
if err != nil {
panic(err)
}
var held []net.Conn
for {
c, err := ln.Accept()
if err == nil {
held = append(held, c) // hold: never close
}
}
}
if *target == "" {
flag.Usage()
os.Exit(64)
}
var open []net.Conn
for i := 1; i <= *n; i++ {
c, err := net.DialTimeout("tcp", *target, 2*time.Second)
if err != nil {
fmt.Printf("connection %d failed: %v\n", i, err)
if errors.Is(err, syscall.EADDRNOTAVAIL) {
fmt.Println("=> EADDRNOTAVAIL: every local port for this 4-tuple is taken.")
fmt.Println(" Fix: reuse connections (keep-alive/pool), widen ip_local_port_range, add source IPs, or spread destinations.")
}
os.Exit(1)
}
if *churn {
c.Close() // active close: this side keeps the port in TIME_WAIT for 60 s
} else {
open = append(open, c)
}
if i%5 == 0 {
fmt.Printf("%d connections ok (last local port %s)\n", i, c.LocalAddr())
}
}
fmt.Printf("all %d ok\n", *n)
}Real run, a client container with only ten ephemeral ports:
$ docker run --rm --network ntplab --sysctl net.ipv4.ip_local_port_range="40000 40009" ... portexhaust -target 10.231.0.20:8080 -n 50
5 connections ok (last local port 10.231.0.2:40002)
connection 10 failed: dial tcp 10.231.0.20:8080: connect: cannot assign requested address
=> EADDRNOTAVAIL: every local port for this 4-tuple is taken.
$ ... portexhaust -target 10.231.0.10:80 -churn -n 50 (open + close each time)
connection 10 failed: dial tcp 10.231.0.10:80: connect: cannot assign requested address
$ awk 'NR>1 && $4=="06"' /proc/net/tcp | wc -l (state 06 = TIME_WAIT)
9The -churn run is the surprising one: every connection was closed, yet the ports are gone, because the side that closes first keeps each port in TIME_WAIT. Holding connections open and closing them quickly exhaust the same range; only reuse avoids both.
Laravel and PHP
Diagnose from Artisan. The command runs the same ladder against the database and Redis hosts from the app's own config, from the same container, then lets the real driver do its handshake (authentication, TLS, protocol), so "TCP works but PDO fails" is visible as its own rung. It uses stream_socket_client(), whose $errno/$errstr are the kernel's errno and the C library's text (real: errno=111 "Connection refused", errno=110 "Operation timed out", errno=113 "Host is unreachable" on Alpine/musl).
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;
/**
* php artisan net:diag
* php artisan net:diag --url=https://partner.example.com/health
*
* Runs the ladder (DNS -> TCP -> driver handshake) for every dependency the
* app is configured with, FROM the same container/pod/env the app runs in.
*/
class NetDiagCommand extends Command
{
protected $signature = 'net:diag {--url=* : Extra HTTP(S) URLs to test} {--timeout=3 : Seconds per rung}';
protected $description = 'Diagnose connectivity to the database, Redis and HTTP dependencies rung by rung';
public function handle(): int
{
$timeout = (float) $this->option('timeout');
$failed = 0;
$db = config('database.connections.'.config('database.default'));
$redis = config('database.redis.default');
$targets = [
['db', $db['host'] ?? '127.0.0.1', (int) ($db['port'] ?? 5432)],
['redis', $redis['host'] ?? '127.0.0.1', (int) ($redis['port'] ?? 6379)],
];
foreach ($this->option('url') as $url) {
$p = parse_url($url);
$targets[] = [$url, $p['host'], (int) ($p['port'] ?? (($p['scheme'] ?? 'http') === 'https' ? 443 : 80))];
}
foreach ($targets as [$name, $host, $port]) {
$this->line("<info>{$name}</info> {$host}:{$port}");
$failed += $this->ladder($name, $host, $port, $timeout) ? 0 : 1;
}
return $failed === 0 ? self::SUCCESS : self::FAILURE;
}
private function ladder(string $name, string $host, int $port, float $timeout): bool
{
// Rung 1: DNS. gethostbynamel() uses the system resolver (hosts file, resolv.conf).
$t = microtime(true);
$ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : gethostbynamel($host);
if ($ips === false) {
$this->error(' [dns] cannot resolve '.$host.' (NXDOMAIN, SERVFAIL or resolver timeout): check the name, search domains, /etc/resolv.conf');
return false;
}
$this->line(sprintf(' [dns] %s (%.0f ms)', implode(', ', $ips), (microtime(true) - $t) * 1000));
// Rung 2: TCP. errno/errstr are the kernel's: 111 refused, 113 no route, 110 timed out.
$t = microtime(true);
$sock = @stream_socket_client("tcp://{$ips[0]}:{$port}", $errno, $errstr, $timeout);
if ($sock === false) {
$this->error(sprintf(' [tcp] errno %d "%s" after %.1f s: %s', $errno, $errstr, microtime(true) - $t, $this->hint($errno, $errstr)));
return false;
}
fclose($sock);
$this->line(sprintf(' [tcp] connected (%.0f ms)', (microtime(true) - $t) * 1000));
// Rung 3: the real driver (auth, TLS, protocol) with the app's own config.
try {
match ($name) {
'db' => DB::connection()->select('select 1'),
'redis' => Redis::connection()->ping(),
default => null,
};
$this->line(' [app] driver handshake ok');
} catch (Throwable $e) {
$this->error(' [app] '.class_basename($e).': '.$e->getMessage());
return false;
}
return true;
}
private function hint(int $errno, string $errstr): string
{
return match (true) {
$errno === 111 => 'RST: nothing listens there (wrong port, bound to 127.0.0.1, container down) or a REJECT rule',
$errno === 113 => 'no route to host: ARP failed on the subnet, or an ICMP host-prohibited from a firewall',
$errno === 101 => 'network unreachable: no route (missing default route, internal-only network)',
$errno === 110, str_contains($errstr, 'timed out') => 'SYN dropped: security group/NACL/iptables DROP, wrong route, host down',
default => 'see the troubleshooting table',
};
}
}The shape of its output (the DNS and TCP rungs use exactly the PHP calls whose real results are quoted above; the Artisan command itself was reviewed, not run here):
$ php artisan net:diag --url=https://partner.example.com/health
db postgres:5432
[dns] 10.240.2.3 (1 ms)
[tcp] connected (0 ms)
[app] driver handshake ok
redis redis:6379
[dns] cannot resolve redis (NXDOMAIN, SERVFAIL or resolver timeout): check the name, search domains, /etc/resolv.confFor one-off checks php artisan tinker works too: DB::connection()->getPdo() and Redis::connection()->ping() raise the driver's exception with the libpq or Redis message inside (SQLSTATE[08006] [7] connection to server at ... failed: Connection refused is the shape PDO gives a libpq connection failure).
Map HTTP client errors to layers. The Laravel 13 docs: when a timeout is exceeded "an instance of Illuminate\Http\Client\ConnectionException will be thrown"; connectTimeout defaults to 10 seconds and timeout to 30. RequestException means the network worked and a 4xx/5xx came back (after throw()). Retry the first kind (idempotent calls only), not the second.
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;
/**
* Map transport failures (no HTTP response at all) and HTTP failures
* (a response with 4xx/5xx) to different handling. They need different fixes.
*/
class PartnerClient
{
public function quote(array $payload): array
{
try {
return Http::baseUrl(config('services.partner.url'))
->connectTimeout(2) // a dropped SYN fails in 2 s, not 10
->timeout(5) // whole request, including TLS and body
->retry(3, 200, function (Throwable $e, PendingRequest $request) {
// Retry transport errors and 502/503/504; never retry 4xx.
return $e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [502, 503, 504], true));
})
->post('/quotes', $payload)
->throw()
->json();
} catch (ConnectionException $e) {
// The message carries libcurl's text, e.g.
// "cURL error 7: Failed to connect to partner port 443 ... Couldn't connect to server"
// "cURL error 28: Connection timed out after 2002 milliseconds"
// "cURL error 6: Could not resolve host: partner"
Log::warning('partner transport failure', [
'curl_errno' => preg_match('/cURL error (\d+)/', $e->getMessage(), $m) ? (int) $m[1] : null,
'message' => $e->getMessage(),
]);
throw new RuntimeException('Partner unreachable (network layer)', 0, $e);
} catch (RequestException $e) {
// The network worked: we have a status code and a body to log.
Log::warning('partner http failure', ['status' => $e->response->status()]);
throw $e;
}
}
}Health endpoints with timeouts. Laravel ships GET /up: "will return a 200 HTTP response if the application has booted without exceptions". Keep that for liveness. Add a readiness endpoint that checks dependencies, each bounded by a short connect timeout, so a database outage takes the pod out of the load balancer rather than into a restart loop.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;
/**
* GET /ready: readiness, dependencies included, each with its own short timeout.
* Keep Laravel's built-in GET /up as liveness (process booted, no dependencies),
* so a database outage removes pods from the load balancer instead of restarting them.
*/
class HealthController extends Controller
{
public function __invoke(): JsonResponse
{
$checks = [
'database' => fn () => DB::connection()->select('select 1'),
'redis' => fn () => Redis::connection()->ping(),
'partner_dns' => fn () => gethostbynamel(parse_url(config('services.partner.url'), PHP_URL_HOST))
?: throw new \RuntimeException('cannot resolve'),
];
$result = [];
$ok = true;
foreach ($checks as $name => $check) {
$t = microtime(true);
try {
$check();
$result[$name] = ['ok' => true, 'ms' => (int) ((microtime(true) - $t) * 1000)];
} catch (Throwable $e) {
$ok = false;
$result[$name] = ['ok' => false, 'ms' => (int) ((microtime(true) - $t) * 1000), 'error' => class_basename($e).': '.$e->getMessage()];
}
}
return response()->json(['ok' => $ok, 'checks' => $result], $ok ? 200 : 503);
}
}<?php
// config/database.php (excerpt): fail fast and survive idle-timeout middleboxes.
// pgsql: PDO passes these DSN keys to libpq (connect_timeout, keepalives_idle).
// redis (phpredis): 'timeout' is the connect timeout, 'read_timeout' the socket read timeout.
return [
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'app'),
'username' => env('DB_USERNAME', 'app'),
'password' => env('DB_PASSWORD', ''),
'options' => [
PDO::ATTR_TIMEOUT => 3, // seconds; for pgsql it maps to connect_timeout
],
],
],
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', '6379'),
'timeout' => 2,
'read_timeout' => 5,
'persistent' => false,
],
],
];libpq documents connect_timeout and keepalives_idle ("the number of seconds of inactivity after which TCP should send a keepalive message to the server"); pdo_pgsql turns PDO::ATTR_TIMEOUT into connect_timeout. Set keepalives below any NAT/LB idle timeout on the path to the database.
Writing the timeline (SQL)
A postmortem-ready timeline is a table of timestamped observations and actions, each with evidence. Keep it while you debug, not after. If your team logs probes or incidents in PostgreSQL, the schema is small and makes "what changed when" queryable:
CREATE TABLE incident_event (
id bigserial PRIMARY KEY,
incident_id text NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
kind text NOT NULL CHECK (kind IN ('symptom','test','hypothesis','change','verify','note')),
layer text CHECK (layer IN ('link','ip','route','arp','firewall','nat','dns','tcp','tls','http','app')),
source text, -- pod/host/region the observation came from
detail text NOT NULL,
evidence text -- command + output excerpt, pcap path, dashboard link
);
-- every change and the first verification after it: did the change fix it?
SELECT c.at AS changed_at, c.detail AS change, v.at AS verified_at, v.detail AS result
FROM incident_event c
LEFT JOIN LATERAL (
SELECT at, detail FROM incident_event v
WHERE v.incident_id = c.incident_id AND v.kind = 'verify' AND v.at > c.at
ORDER BY at LIMIT 1) v ON true
WHERE c.incident_id = 'INC-2026-11-25-db' AND c.kind = 'change'
ORDER BY c.at;| Column of a good timeline | Example |
|---|---|
| Time (UTC, to the minute or second) | 10:06Z |
| Who/where | "from pod orders-7d9 on node ip-10-0-2-4" |
| Observation or action | "nc -vz 10.0.3.7 5432 timed out" |
| Evidence | command, output, pcap file name, graph link |
| Layer conclusion | "TCP: SYN unanswered; DNS ok" |
| Change (one at a time) | "added pod CIDR to sg-db inbound 5432" |
| Verification | "same nc succeeded at 10:15Z; error rate 0 at 10:20Z" |
Choosing
| Question | First tool | Second tool | Why |
|---|---|---|---|
| Is it DNS? | getent hosts name (system path) | dig @resolver name +search | getent sees /etc/hosts and nsswitch like the app; dig shows rcode and server |
| Does anything listen? | ss -ltnp on the server | curl -v 127.0.0.1:PORT inside the server namespace | Separates bind address from network |
| Is the port reachable from here? | nc -vz -w3 IP PORT | curl -v --connect-timeout 3 | Fast vs refused vs timeout in one line |
| Where do packets die? | tcpdump on both ends | Flow logs, conntrack -L, firewall counters | Evidence, not inference |
| Which hop is slow/lossy? | mtr --tcp -P 443 host | traceroute -T -p 443 | Same protocol/port as the app |
| Path MTU? | ping -M do -s 1472 host | tracepath host, pmtuprobe | DF set, full size |
| Throughput? | iperf3 -c host | ss -ti during the transfer | Retransmits and cwnd |
| HTTP phase timing? | curl -w | Go httptrace | DNS/connect/TLS/TTFB split |
| What is the app doing? | strace -f -e trace=%network -p PID | app logs with peer IP and phase | Sees connect() errno directly |
| Kernel-wide symptoms? | nstat -az | conntrack -S, dmesg | Retransmits, overflows, drops |
| Kubernetes Service broken? | kubectl port-forward pod/... | kubectl get endpointslices, netshoot via kubectl debug | Bisect Service vs pod |
| Cloud path? | VPC Flow Logs | Reachability Analyzer / connectivity tests, LB target health | SG/NACL/route evidence |
| Situation | Recommended approach | Extra technique | Reason |
|---|---|---|---|
| Hard failure, every request | Ladder from the failing place | netdiag / net:diag | Deterministic: the first rung names the layer |
| Intermittent, low rate | Log peer IP, local port, reuse flag, phase timings; group by each | Ring-buffer capture -C -W | Find the hidden variable |
| Only under load | USE method on fds, ports, conntrack, NAT ports, backlog | nstat, conntrack -S, NAT metrics | Saturation, not errors in code |
| Only large payloads | MTU tests | MSS clamp | Black hole |
| Only after idle | Idle timeouts on the path | Keepalive, pool idle timeout | Keep-alive race |
| Only after deploy | LB draining, readiness | preStop, deregistration delay | Connections cut mid-flight |
| Only from one environment | Compare configs: DNS, routes, SG, egress IP | diff of resolv.conf, ip route, rules | Environment, not code |
In architecture: from a single process to a distributed system
The more hops a request crosses, the more places can produce each error string, and the more the "where" question dominates. The method does not change; the number of points you bisect between does.
Everyday example. A developer's Laravel app in Docker Compose cannot reach Postgres: SQLSTATE[08006] ... could not translate host name "postgress". Rung 1 fails; the fix is a one-letter typo in .env. Five minutes with the ladder, an afternoon without it.
Production example (a worked scenario assembled from the documented behaviour above, not a specific published incident). An order service in Kubernetes on AWS calls a payment provider. Under the evening peak, 0.5 % of calls fail with i/o timeout on connect. Split by node: all nodes. Split by destination IP: all. Split by time: only at peak. USE method on the NAT gateway: CloudWatch ErrorPortAllocation > 0. Each pod opened a new TLS connection per payment (a client constructed per request), so thousands of short connections per second went to one destination ip:port through one NAT IP. Fix: one shared client with keep-alive (ports in use fell by two orders of magnitude) and a second Elastic IP on the NAT gateway as headroom. Timeline, graphs and the CloudWatch metric went into the postmortem.
Monolith (one process, one database)
Example. One VM: nginx → PHP-FPM → PostgreSQL on localhost, Redis on localhost. The error strings are few and local: connection refused to 127.0.0.1:5432 (Postgres down or listening on another port), too many open files (FPM workers × connections > ulimit -n), address already in use when a second nginx starts. The external edges are DNS and the provider firewall. The ladder runs on one host; ss -ltnp, journalctl and curl -w cover almost everything. The one network trap even here: the cloud firewall or provider security group that silently drops (timeout) while the local ufw rejects (refused): two layers, two behaviours.
Modular monolith
Example. The same codebase now runs as web, worker and scheduler containers sharing Postgres and Redis on a Compose or ECS network, and calls three external APIs. New failure surfaces: container DNS (service names, the embedded resolver 127.0.0.11), bind addresses (a module's admin server listening on 127.0.0.1 inside its container), and outbound egress through one NAT. Give every module the same net:diag command and health endpoint; log the module name with every outbound error so "only the worker fails" is visible at once. Keep one HTTP client per external API per process, configured with timeouts and idle limits, instead of ad-hoc clients in each module.
Microservices
Example. Twenty services in Kubernetes, a service mesh or plain Services, Ingress at the edge, NAT gateway for egress. A request crosses: client → CDN → LB → Ingress controller → Service (kube-proxy rules) → pod (sidecar) → another Service → pod → database through a NetworkPolicy and a security group. Every arrow is a place where refused, timeout, reset or 503 can be generated (a sidecar can answer 503 for an upstream connect failure; an Ingress returns 502 for an upstream reset). Rules that keep this debuggable:
| Rule | Why |
|---|---|
| Propagate trace IDs and log the peer IP and phase on every outbound error | Bisecting needs to know which hop produced the error |
| Distinguish "error generated by a proxy" from "error from the app" (response headers, proxy access logs) | A 503 from Envoy and a 503 from the app are different incidents |
Test with kubectl port-forward to the pod, then the Service, then the Ingress | Bisect the in-cluster path in three steps |
| Default-deny NetworkPolicies come with a test per allowed edge | The first symptom of a missing rule is a connect timeout |
| Idle timeouts ordered: client < sidecar < LB < server keep-alive | Prevents the keep-alive race on every hop |
The design side of retries and timeouts belongs to timeouts, retries and jitter and load balancing; this chapter gives you the evidence that tells you which timeout fired.
Distributed data: replicas, caches, multi-region
Example. A primary database in one region, a read replica and a Redis cache in another, connected by peering or a VPN. Failures here are dominated by long-lived connections and middleboxes: a replication or pooled connection idles past a NAT/firewall timeout and dies with a reset on the next query; the VPN's smaller MTU turns large result sets into hangs while SELECT 1 health checks pass (health checks are small: they never test the MTU); a DNS failover record with a long TTL keeps clients on the old primary. Defences: TCP keepalives below every idle timeout (keepalives_idle in libpq), MSS clamping on the tunnel, health checks that move a realistic payload size, and low TTLs on failover names. Connection pooling owns pool sizing; replication and failover owns the failover itself.
Scaling path
| Load | What breaks first | What to change |
|---|---|---|
| 1× (tens of requests per second) | Config: names, ports, bind addresses, firewall rules | The ladder; health endpoints; timeouts on every client |
| 10× (hundreds per second) | fds and pools; keep-alive races; first TIME_WAIT pile-ups | Shared clients, pool limits, idle timeouts below LB/NAT; alert on ListenOverflows, retransmits |
| 100× (thousands per second per host) | Ephemeral ports per destination, node conntrack, NAT gateway ports, DNS QPS (ndots) | Connection reuse everywhere, HTTP/2, more NAT IPs or VPC endpoints, NodeLocal DNSCache, conntrack sizing |
| Global | Per-region paths, MTU across tunnels, asymmetric routing, anycast | Synthetic probes per region and per path, flow logs, MTU standards per overlay, runbooks per error string |
Observability to keep
Most of an incident is spent collecting evidence that could have been collected already. Keep these (design of the stack is in observability):
| Signal | Source | Alert / use |
|---|---|---|
| Outbound errors by class (refused, timeout, reset, DNS, TLS) and by peer | App logs/metrics using the classify mapping | Spike in one class names the layer before anyone logs in |
| Connect, TLS and TTFB latency per dependency | httptrace, Guzzle on_stats, curl -w in probes | p99 connect time rising = network or SYN backlog |
| Pool stats: open, idle, waiting, created/s | sql.DB.Stats(), Laravel/Horizon metrics, PgBouncer | Created/s high = no reuse |
| DNS: query rate, NXDOMAIN, SERVFAIL, latency | CoreDNS metrics, resolver logs | ndots storms, upstream failures |
| TCP counters: retransmits, resets, listen overflows | nstat, node exporter | Path loss, accept queue saturation |
conntrack count / max, insert_failed, drop | node exporter (nf_conntrack_entries), conntrack -S | Saturation before drops |
| fds per process vs limit | /proc/PID/fd, process exporter | Leaks |
| TIME_WAIT count per destination | ss -tan state time-wait | Churn |
| NAT gateway and LB metrics | CloudWatch / cloud equivalent | Port allocation errors, idle timeouts, unhealthy targets |
| Synthetic probes from each region/network to each dependency | Blackbox exporter, netdiag in a cron job | Detects path problems with no user traffic |
| Flow logs | VPC Flow Logs | Proof of SG/NACL rejects |
Lab
Six broken scenarios (bind address, publish, internal network, DNS typo, firewall, MTU) in one Compose file, plus capture practice. Everything below ran on Docker Desktop (Linux VM, kernel 7.0); the output is real and trimmed only where marked with .... Every step uses the ladder: name, route, connect, TLS/HTTP. The fixes for steps 1-5 are the one-line changes named in each step and were not re-run here; the three MTU fixes in step 6 were run and their output is shown.
# Six broken scenarios plus an MTU black hole. Run:
# docker compose -p ntplab up -d --build
# docker compose -p ntplab exec client sh (then follow the lab steps)
# docker compose -p ntplab down
name: ntplab
x-tools: &tools
build:
context: .
dockerfile_inline: |
FROM alpine:3
RUN apk add --no-cache iptables iproute2 tcpdump curl bind-tools conntrack-tools \
iputils iputils-tracepath mtr strace netcat-openbsd busybox-extras
image: ntplab-tools
services:
# A client with every tool, on the "front" network and the internal "back" network.
client:
<<: *tools
command: sh -c "ip route add 10.240.3.0/24 via 10.240.1.254 && sleep infinity"
cap_add: [NET_ADMIN, NET_RAW]
networks:
front: { ipv4_address: 10.240.1.5 }
back: {}
environment:
DB_HOST: postgress # scenario 4: a typo, the service is "postgres"
# 1. Wrong bind address: listens on 127.0.0.1 inside the container, port published.
bind-wrong:
<<: *tools
command: busybox-extras httpd -f -p 127.0.0.1:8000 -h /etc
ports: ["127.0.0.1:8001:8000"]
networks: [front]
# 2. Missing port publish: the service works, but no host port maps to it.
no-publish:
image: nginx:alpine
networks: [front]
# 3. Internal network: postgres is reachable from client, the internet is not from postgres.
postgres:
image: postgres:16-alpine
environment: { POSTGRES_PASSWORD: secret }
networks: [back]
# 5. A firewall: DROP on 80, RST on 81, ICMP host-prohibited on 82.
fw:
<<: *tools
cap_add: [NET_ADMIN]
networks:
front: { ipv4_address: 10.240.1.20 }
command: >
sh -c "iptables -A INPUT -p tcp --dport 80 -j DROP &&
iptables -A INPUT -p tcp --dport 81 -j REJECT --reject-with tcp-reset &&
iptables -A INPUT -p tcp --dport 82 -j REJECT --reject-with icmp-host-prohibited &&
for p in 80 81 82 8080; do busybox-extras httpd -p $$p -h /etc; done &&
sleep infinity"
# 6. MTU black hole: client (front) -> router -> bigserver (mtu network).
# The router lowers its front-side link to 1400 and drops the ICMP
# "fragmentation needed" it would send back to bigserver.
router:
<<: *tools
cap_add: [NET_ADMIN]
sysctls: { net.ipv4.ip_forward: 1 }
networks:
front: { ipv4_address: 10.240.1.254 }
mtu: { ipv4_address: 10.240.3.254 }
command: >
sh -c "ip -o -4 addr show | awk '/10.240.1.254/ {print $$2}' > /tmp/if &&
ip link set dev $$(cat /tmp/if) mtu 1400 &&
iptables -A OUTPUT -p icmp --icmp-type fragmentation-needed -j DROP &&
sleep infinity"
bigserver:
<<: *tools
cap_add: [NET_ADMIN]
networks:
mtu: { ipv4_address: 10.240.3.10 }
command: >
sh -c "ip route add 10.240.1.0/24 via 10.240.3.254 &&
mkdir -p /srv && head -c 200000 /dev/urandom > /srv/big.bin && echo small > /srv/small.txt &&
busybox-extras httpd -f -p 8080 -h /srv"
networks:
front:
ipam: { config: [{ subnet: 10.240.1.0/24 }] }
back:
internal: true # scenario 3
ipam: { config: [{ subnet: 10.240.2.0/24 }] }
mtu:
ipam: { config: [{ subnet: 10.240.3.0/24 }] }docker compose -p ntplab up -d --build
docker compose -p ntplab exec client sh # the client has every tool and NET_ADMIN
# the Go tools from this chapter, cross-compiled for the Linux containers and copied in
cd docs/snippets/foundations/network-troubleshooting-playbook/go
for p in netdiag pmtuprobe portexhaust timing; do
GOOS=linux GOARCH=$(docker info -f '{{.Architecture}}' | sed 's/x86_64/amd64/;s/aarch64/arm64/') CGO_ENABLED=0 go build -o /tmp/ntp-bin/$p ./$p
done
for c in ntplab-client-1 ntplab-bigserver-1; do for p in netdiag pmtuprobe portexhaust; do docker cp /tmp/ntp-bin/$p $c:/usr/local/bin/$p; done; done1. Wrong bind address
bind-wrong serves on 127.0.0.1:8000 inside its container and publishes 127.0.0.1:8001:8000.
curl -sS http://127.0.0.1:8001/passwd # from the host
# curl: (52) Empty reply from server <- docker-proxy accepted, the backend refused, the proxy closed
docker compose -p ntplab exec client curl -sS http://bind-wrong:8000/passwd
# curl: (7) Failed to connect to bind-wrong:8000 after 0 ms: Could not connect to server
docker compose -p ntplab exec bind-wrong ss -ltn
# LISTEN 0 9 127.0.0.1:8000 0.0.0.0:* <- the diagnosis: loopback onlyTwo different symptoms for one cause: from the host the published port answers (the proxy listens) and then closes, so you see an empty reply, not a refusal; from another container it is a plain refusal. Fix: bind 0.0.0.0 (httpd -p 8000, php artisan serve --host=0.0.0.0, --bind 0.0.0.0).
2. Missing port publish
no-publish is a working nginx with no ports:.
docker compose -p ntplab port no-publish 80 # invalid IP:0 <- nothing published
curl -sS http://127.0.0.1:8002/ # curl: (7) Failed to connect to 127.0.0.1 port 8002 after 0 ms: Couldn't connect to server
docker compose -p ntplab exec client curl -s -o /dev/null -w '%{http_code}\n' http://no-publish/ # 200Works inside the network, refused from the host: the service is fine, the publish is missing. Fix: ports: ["8002:80"].
3. Internal network, no egress
back is internal: true; postgres is only on it.
docker compose -p ntplab exec postgres sh -c 'ip route; wget -q -T 3 -O /dev/null http://1.1.1.1/'
# 10.240.2.0/24 dev eth0 scope link src 10.240.2.3 <- no default route at all
# wget: can't connect to remote host (1.1.1.1): Network unreachable
docker run --rm --network ntplab_back ntplab-tools curl -sS -m 3 https://example.com/
# curl: (6) Could not resolve host: example.com (DNS server returned general failure)
docker compose -p ntplab exec client nc -vz -w3 postgres 5432
# Connection to postgres (10.240.2.3) 5432 port [tcp/postgresql] succeeded!Two rungs fail at once on an internal network: DNS for external names returns SERVFAIL and routing returns unreachable. Internal traffic is fine. Fix (if egress is intended): attach a second, non-internal network or route through an egress proxy.
4. DNS typo
The client's DB_HOST is postgress.
docker compose -p ntplab exec client sh -c 'nc -vz -w3 $DB_HOST 5432; getent hosts postgress; echo "getent exit=$?"; dig postgress @127.0.0.11 | grep status'
# nc: getaddrinfo for host "postgress" port 5432: Try again
# getent exit=2
# ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 29853Rung 1 fails; nothing below it matters. Note the musl text "Try again" for an NXDOMAIN, which misleads people into retrying. Fix the name.
5. Firewall: DROP vs REJECT
fw listens on 80, 81, 82 and 8080 with DROP on 80, REJECT --reject-with tcp-reset on 81 and REJECT --reject-with icmp-host-prohibited on 82.
for p in 80 81 82 8080; do netdiag -timeout 3s tcp://10.240.1.20:$p; done
# FAIL rung 2 (tcp): dial tcp 10.240.1.20:80: i/o timeout (after 3.002 s)
# FAIL rung 2 (tcp): dial tcp 10.240.1.20:81: connect: connection refused (0 s)
# FAIL rung 2 (tcp): dial tcp 10.240.1.20:82: connect: no route to host (0 s)
# [2/4] tcp 10.240.1.20:8080 connected from 10.240.1.4:56980 (0s)
docker compose -p ntplab exec fw iptables -L INPUT -v -n
# 6 360 DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
# 2 120 REJECT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:81 reject-with tcp-reset
# 2 120 REJECT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:82 reject-with icmp-host-prohibitedThe same listening service gives three different errors depending only on the rule in front of it. The counters prove which rule matched. Fix: allow the source (and prefer REJECT internally so clients fail fast).
6. MTU black hole
The router's link towards the client is 1400 and it drops the ICMP "fragmentation needed" it should send to bigserver.
docker compose -p ntplab exec client sh -c '
curl -sS -m 5 -o /dev/null -w "small: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.10:8080/small.txt
curl -sS -m 5 -o /dev/null -w "big: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.10:8080/big.bin'
# small: 200 6 bytes 0.000290s
# curl: (28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes received
docker compose -p ntplab exec bigserver sh -c 'ping -c2 -W1 -M do -s 1472 10.240.1.5; ping -c2 -W1 -M do -s 1372 10.240.1.5; tracepath -n 10.240.1.5'
# 2 packets transmitted, 0 received, 100% packet loss <- 1500-byte DF packets vanish
# 2 packets transmitted, 2 received, 0% packet loss <- 1400 fits
# 1?: [LOCALHOST] pmtu 1500
# 1: 10.240.3.254 0.048ms
# 2: no reply ... Resume: pmtu 1500 <- tracepath never learns: the ICMP is eaten
pmtuprobe -listen :9999 # on client
pmtuprobe -target 10.240.1.5:9999 # on bigserver
# probe 1629 bytes: EMSGSIZE (bigger than the local/cached PMTU, refused before sending)
# probe 1398 bytes: echoed
# probe 1401 bytes: no echo after 3 tries (dropped: black hole or ICMP frag-needed filtered)
# path MTU (confirmed by echo): 1400 bytes
# kernel's cached PMTU (from ICMP, IP_MTU): 1500 bytes <- the kernel still believes 1500: the black hole
# largest TCP MSS that fits: 1360 bytesThe stuck connection on the server tells the same story in ss -tino: retransmissions with exponential backoff, a congestion window of 1, and a PMTU that never dropped.
CLOSE-WAIT 1 47288 [::ffff:10.240.3.10]:8080 [::ffff:10.240.1.5]:50864 timer:(on,,9)
ts sack cubic wscale:10,10 rto:102912 backoff:9 ... mss:1448 pmtu:1500 ... cwnd:1 ssthresh:7 bytes_retrans:14480 ... unacked:11 retrans:1/10 lost:10The server-side capture shows the retransmissions (the 7240-byte "segments" are GSO super-packets, split by the kernel below tcpdump):
18:26:59.136047 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [P.], seq 513740315:513747555, ack 4171154710, ... length 7240: HTTP
18:26:59.140223 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP
18:26:59.350835 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP (+0.21 s)
18:26:59.761298 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP (+0.41 s)
18:27:00.575930 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP (+0.81 s)
$ nstat -az TcpRetransSegs TcpExtTCPTimeouts
TcpRetransSegs 15 0.0
TcpExtTCPTimeouts 13 0.0Three fixes, each verified with the same curl:
# fix A: MSS clamping on the router
docker compose -p ntplab exec router iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
# big: 200 200000 bytes 0.000454s (counter: 2 SYNs rewritten)
docker compose -p ntplab exec router iptables -t mangle -F FORWARD # undo before the next fix
# fix B: packetization-layer PMTUD on the sender: a second server with tcp_mtu_probing=1
docker run -d --name ntp-probe-srv --network ntplab_mtu --ip 10.240.3.11 --cap-add NET_ADMIN \
--sysctl net.ipv4.tcp_mtu_probing=1 ntplab-tools sh -c 'ip route add 10.240.1.0/24 via 10.240.3.254 &&
mkdir -p /srv && head -c 200000 /dev/urandom > /srv/big.bin && httpd -f -p 8080 -h /srv'
docker compose -p ntplab exec client curl -sS -m 30 -o /dev/null -w "big (tcp_mtu_probing=1) run 1: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.11:8080/big.bin
# big (tcp_mtu_probing=1) run 1: 200 200000 bytes 3.098087s <- works, but pays a few RTOs to detect the hole
docker exec ntp-probe-srv nstat -az TcpExtTCPMTUPFail TcpExtTCPMTUPSuccess
# TcpExtTCPMTUPFail 6 TcpExtTCPMTUPSuccess 6
# fix C (the real one): stop dropping ICMP frag-needed on the router
docker compose -p ntplab exec router iptables -D OUTPUT -p icmp --icmp-type fragmentation-needed -j DROP
# big (ICMP allowed): 200 200000 bytes 0.000587s
ip route get 10.240.1.5 # on bigserver
# 10.240.1.5 via 10.240.3.254 dev eth0 src 10.240.3.10 uid 0
# cache expires 599sec mtu 1400 <- the kernel learned the PMTU from ICMP
# kernel's cached PMTU (from ICMP, IP_MTU): 1400 bytes (pmtuprobe again: the two numbers now agree)Inside a container sysctl -w net.ipv4.tcp_mtu_probing=1 fails with "Read-only file system"; set it at start with --sysctl / Compose sysctls: or on the host.
7. Capture and annotate a RST, a retransmission and an ICMP rejection
tcpdump -ni eth0 -X -c 2 'host 10.240.1.20 and port 81' & nc -vz -w2 10.240.1.20 81
# nc: connect to 10.240.1.20 port 81 (tcp) failed: Connection refused
18:23:58.270410 IP 10.240.1.6.37238 > 10.240.1.20.81: Flags [S], seq 4263478037, win 64240, options [mss 1460,sackOK,TS val 3980363860 ecr 0,nop,wscale 10], length 0
0x0000: 4500 003c f8c6 4000 4006 29fc 0af0 0106 E..<..@.@.).....
0x0010: 0af0 0114 9176 0051 fe1f 8315 0000 0000 .....v.Q........
0x0020: a002 faf0 1828 0000 0204 05b4 0402 080a .....(..........
0x0030: ed3f 8854 0000 0000 0103 030a .?.T........
18:23:58.270448 IP 10.240.1.20.81 > 10.240.1.6.37238: Flags [R.], seq 0, ack 4263478038, win 0, length 0
0x0000: 4500 0028 0000 4000 4006 22d7 0af0 0114 E..(..@.@.".....
0x0010: 0af0 0106 0051 9176 0000 0000 fe1f 8316 .....Q.v........
0x0020: 5014 0000 1814 0000 P.......| Bytes (RST packet) | Field | Value | Meaning |
|---|---|---|---|
45 | IP version + header length | 4, 5 words | IPv4, 20-byte header |
0028 | Total length | 40 | 20 IP + 20 TCP, no payload |
4000 | Flags + fragment offset | DF set | Linux sets DF |
40 | TTL | 64 | Sent by a Linux host one hop away (a middle box would show a different TTL) |
06 | Protocol | 6 | TCP |
0af0 0114 → 0af0 0106 | Source → destination | 10.240.1.20 → 10.240.1.6 | The server's IP answered (not a proxy) |
0051 → 9176 | Ports | 81 → 37238 | Reply to our SYN's port pair |
0000 0000 | Sequence | 0 | A RST answering a SYN carries seq 0 |
fe1f 8316 | Acknowledgment | SYN seq + 1 | Acknowledges exactly our SYN (fe1f8315 + 1): it is a direct reply, not injected noise |
50 | Data offset | 5 words | 20-byte TCP header, no options |
14 | Flags | 0x14 = RST + ACK | The [R.] in the summary line |
0000 | Window | 0 | Nothing to receive |
In the SYN above, a002 is data offset 10 words (40 bytes with options) and flags 0x002 (SYN); 0204 05b4 is the MSS option, 0x05b4 = 1460. The ICMP variant (port 82) shows the rejection type in clear text:
18:24:39.997104 IP (tos 0xc0, ttl 64, id 38260, offset 0, flags [none], proto ICMP (1), length 88)
10.240.1.20 > 10.240.1.6: ICMP host 10.240.1.20 unreachable - admin prohibited, length 68
IP (tos 0x0, ttl 64, id 55472, offset 0, flags [DF], proto TCP (6), length 60)
10.240.1.6.57478 > 10.240.1.20.82: Flags [S], ... length 0 <- the ICMP quotes our SYNThe retransmissions, annotated. Two real captures on this page show them; read them with the same eye:
| Capture | What repeats | Spacing | What it proves |
|---|---|---|---|
| Timeout block, DROP on port 80 | Flags [S], seq 2957620591 six times, same source port 49622 | 1.01, 1.02, 1.02, 1.02, 1.02 s | SYN retransmissions (linear 1 s timeouts): nothing answered, not even a RST; a filter drops |
| Step 6, MTU black hole | seq 0:1448 (relative) from port 8080 | +0.21, +0.41, +0.81 s ... | Data retransmissions with exponential RTO backoff: the connection exists, the full-size segment never gets ACKed |
Step 6, nstat | TcpRetransSegs 15, TcpExtTCPTimeouts 13 | — | Kernel-wide confirmation of the same retransmissions |
Wireshark's rule is the one quoted in Packet capture: a segment is a "TCP Retransmission" when "the next expected sequence number is greater than the current sequence number". Write the capture with tcpdump -w, open it and apply tcp.analysis.retransmission or tcp.analysis.flags to see these packets marked.
8. Ephemeral ports and TIME_WAIT
Run the reproducer with --sysctl net.ipv4.ip_local_port_range="40000 40009": connection 10 fails with cannot assign requested address. Then look at a server that closes first:
docker compose -p ntplab exec fw ss -tano state time-wait
# [::ffff:10.240.1.20]:8080 [::ffff:10.240.1.5]:38162 timer:(timewait,59sec,0)
# [::ffff:10.240.1.20]:8080 [::ffff:10.240.1.5]:34004 timer:(timewait,23sec,0)The active closer holds each 4-tuple for 60 seconds (timewait,59sec one second after closing).
Clean up
docker rm -f ntp-probe-srv
docker compose -p ntplab downCommon misconceptions
| Belief | Reality |
|---|---|
| "Refused and timeout both mean the service is down" | Refused: a host answered RST (no listener, wrong port/bind, REJECT). Timeout: packets were dropped. Different layers, different owners |
| "ping works, so TCP will work" | ICMP has no port, is small, and is filtered and prioritised differently. Test the real port with the real size |
| "Connection reset by peer means the server crashed" | Any middle box (LB, NAT gateway, firewall, sidecar) can send the RST; look at who sent it |
| "Raising the timeout fixes timeouts" | A connect timeout means a drop; waiting longer just holds workers longer |
| "65,535 ports means 65,535 connections" | 28,232 ephemeral ports by default, per destination ip:port, per source IP; TIME_WAIT holds them 60 s |
| "Closing connections quickly saves ports" | The side that closes first keeps the port in TIME_WAIT; reuse saves ports |
| "Lowering MTU on my containers fixes the black hole" | A black hole is a smaller link in the middle with ICMP blocked; fix ICMP, clamp MSS or set the overlay MTU |
| "Blocking all ICMP is safer" | It breaks PMTUD (black holes) and makes every failure a slow timeout |
| "mtr shows loss at hop 3, hop 3 is broken" | Only loss that continues to the last hop is real; middle hops rate-limit ICMP |
| "It works from my laptop, so the network is fine" | Your laptop has different DNS, routes, VPN and NAT. Test from the failing pod/container |
"no such host means the record does not exist" | It means this resolver, with these search domains, said so; another resolver may disagree |
| "Health checks passing means the path is healthy" | Health checks are small and on one port; they do not test MTU, egress or the dependency under load |
| "tcp_tw_recycle fixes TIME_WAIT" | It broke clients behind NAT and no longer exists in current kernels (absent from the ip-sysctl docs); use connection reuse |
Cheat sheet
| Topic | Remember |
|---|---|
| Method | Reproduce → localise by layer → bisect client to server → compare working vs broken → change one thing |
| Refused | RST in ~1 RTT; ss -ltnp; bind 0.0.0.0 in containers |
| Timeout | SYN dropped; capture both ends; SG/NACL/iptables/route/NAT/conntrack |
| No route / unreachable | ARP failed or ICMP prohibited / no route at all; ip route get, ip neigh |
| Reset / EOF / broken pipe | Idle timeouts on the path; client idle < LB/NAT idle; see who sent the RST |
| DNS | getent hosts, dig +search, resolv.conf, ndots; NXDOMAIN vs SERVFAIL vs timeout |
| TLS | Fast failure = certificate/SNI; slow failure = network/MTU; openssl s_client |
| EMFILE / EADDRINUSE / EADDRNOTAVAIL | fds / listener port taken / ephemeral ports gone |
| MTU | ping -M do -s 1472, tracepath; allow ICMP type 3 code 4; clamp MSS; overlay MTU |
| conntrack | nf_conntrack_count vs max; conntrack -S; dmesg "table full" |
| NAT gateway | AWS: 55,000 concurrent per IP per destination; 350 s idle then RST |
| Capture | tcpdump -ni any -w f.pcap 'host X and port Y'; tcp[tcpflags] & tcp-rst != 0; ring -C -W |
| Wireshark | tcp.analysis.flags, tcp.flags.reset==1, Follow TCP Stream, SSLKEYLOGFILE |
| Latency | curl -w, mtr --tcp, ss -ti, nstat, iperf3 |
| Containers | --net container:X nicolaka/netshoot, kubectl debug --target, nsenter -n, kubectl port-forward |
| Write it down | UTC time, where, observation, evidence, one change, verification |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A client gets connection refused in 1 ms and another gets i/o timeout after 3 s to the same IP and port. What does each prove? Must-know
Answer
Answer: Refused proves the SYN reached a TCP stack (or a REJECT rule) that answered RST: the host is reachable and nothing listens, or a rule rejects. Timeout proves the SYN or the SYN-ACK was dropped: a firewall DROP, route, NAT or a down host. If both happen to the same target from different clients, compare the clients' paths (one passes a DROP rule the other does not).
2 — A container publishes -p 8080:8080 but curl localhost:8080 from the host fails, while docker exec app curl localhost:8080 works. Most likely cause? Must-know
Answer
Answer: The app binds 127.0.0.1 inside the container, so it only accepts connections from inside its own network namespace. Traffic arriving via the bridge targets the container's eth0 address. Bind 0.0.0.0. docker exec app ss -ltn shows 127.0.0.1:8080.
3 — Why does connection reset by peer appear mostly on the first request after a quiet period? Important
Answer
Answer: The pooled connection outlived an idle timeout on the path (ALB default 60 s, AWS NAT gateway 350 s, or the server's keep-alive timeout). The middle box dropped its state and answers the next packet with RST (or the server closed with FIN, giving EOF). Set the client idle timeout below the shortest one on the path and use keepalives.
4 — Small API responses work through the VPN; a 2 MB export hangs. What do you test and what are the fixes? Important
Answer
Answer: An MTU black hole. Test with ping -M do -s 1472 then lower sizes, and tracepath. Fixes: allow ICMP type 3 code 4 (and ICMPv6 Packet Too Big), clamp TCP MSS to the PMTU on the tunnel, set the tunnel/overlay MTU correctly, or enable tcp_mtu_probing=1 on senders.
5 — What does EADDRNOTAVAIL from connect() mean, and why can closing connections quickly make it worse? Important
Answer
Answer: No free ephemeral port for that destination ip:port (default range 32768-60999). The side that closes first keeps each port in TIME_WAIT for 60 s, so open-close churn consumes ports as fast as holding connections. Reuse connections (keep-alive, pools), widen the range, add source IPs.
6 — What happens when the conntrack table is full, and how would you see it? Important
Answer
Answer: New flows are dropped before they get an entry: clients see connect timeouts, not errors. The kernel logs "nf_conntrack: table full, dropping packet"; nf_conntrack_count equals nf_conntrack_max; conntrack -S shows drop/early_drop. Raise the limit and buckets, shorten timeouts, reuse connections, exempt known heavy flows with NOTRACK.
7 — mtr shows 40 % loss at hop 3 and 0 % at the destination. Is there packet loss? Must-know
Answer
Answer: No. Hop 3 rate-limits the ICMP TTL-exceeded replies it generates. Forwarded traffic is fine, which is why the destination shows 0 %. Only loss that persists to the final hop matters.
8 — Which tcpdump filter shows only resets, and which Wireshark filter shows every TCP problem? Good to know
Answer
Answer: tcpdump -ni any 'tcp[tcpflags] & tcp-rst != 0'. In Wireshark, tcp.analysis.flags (retransmissions, dup ACKs, zero window, out-of-order and more); tcp.flags.reset==1 for resets.
9 — A Kubernetes pod cannot reach orders:8080. kubectl port-forward pod/orders-x 8080 works. What next? Must-know
Answer
Answer: The pod answers, so the app and its bind address are fine. Check the Service: kubectl get endpointslices -l kubernetes.io/service-name=orders (empty means selector mismatch or pods not ready), the Service targetPort, NetworkPolicies selecting either pod, and DNS from the caller pod (kubectl debug with netshoot, then nslookup orders).
10 — Why separate the connect timeout from the request timeout in Laravel's HTTP client? Important
Answer
Answer: A connect timeout fires when the SYN is dropped (network problem) and should be short (2-3 s); a request timeout covers TLS, server processing and body transfer (server or payload problem). One long timeout makes a dropped SYN hold a worker for as long as a slow report. Both raise ConnectionException, but the message (cURL error 28: Connection timed out vs Operation timed out ... with N bytes received) tells them apart.
11 — What makes a timeline "postmortem-ready"? Important
Answer
Answer: UTC timestamps, where each observation was made, the exact command and output (or capture file) as evidence, one change per line, and the verification that followed each change. It lets someone else replay the reasoning and see which change fixed it.
Glossary
| Term | Meaning |
|---|---|
| Bisection | Testing at the middle of the path to halve the search space each step |
| USE method | Utilization, saturation, errors for every resource (Brendan Gregg) |
| RST | TCP reset segment: abort a connection or refuse a SYN |
ECONNREFUSED | Errno 111: RST in reply to SYN; nothing listening |
ETIMEDOUT | Errno 110: the kernel gave up retransmitting |
i/o timeout | Go's message when your own deadline fired |
EHOSTUNREACH | Errno 113: no ARP reply or ICMP host unreachable/prohibited |
ENETUNREACH | Errno 101: no route to the network |
ECONNRESET | Errno 104: RST on an established connection |
EPIPE | Errno 32: write after the peer closed/reset (broken pipe) |
| EOF | Read returned zero bytes: the peer sent FIN |
EMFILE | Errno 24: too many open files in the process |
EADDRINUSE | Errno 98: address already in use on bind |
EADDRNOTAVAIL | Errno 99: cannot assign requested address (no ephemeral port) |
| NXDOMAIN | DNS rcode 3: the name does not exist |
| SERVFAIL | DNS rcode 2: the resolver failed to answer |
| ndots | resolv.conf option: names with fewer dots go through the search list first |
| MTU | Maximum transmission unit: largest IP packet on a link |
| MSS | Maximum segment size: largest TCP payload, announced in the SYN |
| PMTUD | Path MTU Discovery with DF bit and ICMP "fragmentation needed" (RFC 1191) |
| PLPMTUD / DPLPMTUD | Probing the path with real packets instead of trusting ICMP (RFC 4821, RFC 8899) |
| DF bit | IPv4 "Don't Fragment" flag |
| Black hole | Packets silently dropped while the sender is unaware (RFC 8899 definition) |
| MSS clamping | Rewriting the MSS option in SYNs on a router to fit the path (TCPMSS --clamp-mss-to-pmtu) |
| Fragmentation | Splitting an IP packet into fragments; fragile through firewalls and NAT |
| conntrack | Linux netfilter's connection-tracking table, needed for NAT and stateful rules |
nf_conntrack_max / nf_conntrack_count | conntrack table limit and current use |
| Ephemeral port | Source port picked by the kernel for outbound connections (ip_local_port_range) |
| TIME_WAIT | State the active closer keeps for 60 s on Linux to absorb late segments |
| SNAT port collision | Two flows mapped to the same NAT source port; insert_failed, mitigated by --random-fully |
| NAT gateway port limit | AWS: 55,000 concurrent connections per IP per destination (ErrorPortAllocation) |
| Half-open connection | One side believes the connection is alive, the other (or a middle box) forgot it |
| Connection draining | LB keeps existing connections to a deregistering target for a delay |
| Keep-alive race | A client reuses an idle connection the server or a middle box is closing |
| tcpdump / pcap | Packet capture tool and its file format |
| Display filter | Wireshark's post-capture filter language (tcp.analysis.flags) |
| Retransmission | A segment sent again because it was not acknowledged |
| Dup ACK | Repeated ACK signalling a gap (loss or reordering) |
| Zero window | Receiver advertises no buffer space: the application is not reading |
SSLKEYLOGFILE | Environment variable that makes TLS libraries write session secrets for Wireshark |
mtr | Continuous traceroute with per-hop loss and latency |
tracepath | Traceroute that also discovers the path MTU |
iperf3 | Throughput and loss tester (client and server) |
ss -ti | Socket statistics with per-connection TCP info (rtt, retrans, cwnd, pmtu) |
nstat | Kernel SNMP counters as deltas |
strace | System-call tracer; -e trace=%network shows connect/accept errors |
| netshoot | Container image with network debugging tools (nicolaka/netshoot) |
nsenter | Run a program in another process's namespaces (e.g. its network namespace) |
| Ephemeral container | Temporary debug container added to a running pod (kubectl debug) |
kubectl port-forward | Tunnel a local port to a pod, bypassing Service, Ingress and policies |
| Security group | Stateful cloud firewall attached to interfaces |
| Network ACL | Stateless subnet firewall; return traffic must be allowed explicitly |
| VPC Flow Logs | Records of accepted/rejected flows per interface |
| Synthetic probe | Scheduled test request from a known place to a dependency |
| Postmortem timeline | Timestamped observations, evidence, changes and verifications |
References
Every URL was fetched and its text saved under scratchpad/sources/network-troubleshooting-playbook/; each returned HTTP 200 when fetched.
- Google SRE book, Effective Troubleshooting: https://sre.google/sre-book/effective-troubleshooting/
- Brendan Gregg, The USE Method: https://www.brendangregg.com/usemethod.html; Linux Performance: https://www.brendangregg.com/linuxperf.html
- RFC 1191 (Path MTU Discovery): https://www.rfc-editor.org/rfc/rfc1191; RFC 2923 (TCP problems with PMTUD): https://www.rfc-editor.org/rfc/rfc2923; RFC 4821 (PLPMTUD): https://www.rfc-editor.org/rfc/rfc4821; RFC 8899 (DPLPMTUD): https://www.rfc-editor.org/rfc/rfc8899; RFC 4459 (MTU and fragmentation issues with in-the-network tunneling): https://www.rfc-editor.org/rfc/rfc4459; RFC 9293 (TCP): https://www.rfc-editor.org/rfc/rfc9293
- Linux kernel, IP sysctl: https://docs.kernel.org/networking/ip-sysctl.html; netfilter conntrack sysctl: https://docs.kernel.org/networking/nf_conntrack-sysctl.html
- man pages: connect(2) https://man7.org/linux/man-pages/man2/connect.2.html; listen(2) https://man7.org/linux/man-pages/man2/listen.2.html; errno(3) https://man7.org/linux/man-pages/man3/errno.3.html; tcp(7) https://man7.org/linux/man-pages/man7/tcp.7.html; ip(7) https://man7.org/linux/man-pages/man7/ip.7.html; ss(8) https://man7.org/linux/man-pages/man8/ss.8.html; ip(8) https://man7.org/linux/man-pages/man8/ip.8.html; ip-route(8) https://man7.org/linux/man-pages/man8/ip-route.8.html; nstat(8) https://man7.org/linux/man-pages/man8/nstat.8.html; tracepath(8) https://man7.org/linux/man-pages/man8/tracepath.8.html; strace(1) https://man7.org/linux/man-pages/man1/strace.1.html; nsenter(1) https://man7.org/linux/man-pages/man1/nsenter.1.html
- Debian man pages: ping(8) https://manpages.debian.org/bookworm/iputils-ping/ping.8.en.html; traceroute(1) https://manpages.debian.org/bookworm/traceroute/traceroute.1.en.html; mtr(8) https://manpages.debian.org/bookworm/mtr-tiny/mtr.8.en.html; dig(1) https://manpages.debian.org/bookworm/bind9-dnsutils/dig.1.en.html; conntrack(8) https://manpages.debian.org/bookworm/conntrack/conntrack.8.en.html; nft(8) https://manpages.debian.org/bookworm/nftables/nft.8.en.html; iptables(8) https://manpages.debian.org/bookworm/iptables/iptables.8.en.html; iptables-extensions(8) https://manpages.debian.org/bookworm/iptables/iptables-extensions.8.en.html
- tcpdump(1): https://www.tcpdump.org/manpages/tcpdump.1.html; pcap-filter(7): https://www.tcpdump.org/manpages/pcap-filter.7.html
- Wireshark User's Guide, display filters: https://www.wireshark.org/docs/wsug_html_chunked/ChWorkBuildDisplayFilterSection.html; TCP analysis: https://www.wireshark.org/docs/wsug_html_chunked/ChAdvTCPAnalysis.html; Follow stream: https://www.wireshark.org/docs/wsug_html_chunked/ChAdvFollowStreamSection.html; Wireshark wiki TLS: https://wiki.wireshark.org/TLS
- curl manual (exit codes,
--write-out): https://curl.se/docs/manpage.html; everything curl, write-out: https://everything.curl.dev/usingcurl/verbose/writeout.html; SSLKEYLOGFILE: https://everything.curl.dev/usingcurl/tls/sslkeylogfile.html - iperf3 invoking: https://software.es.net/iperf/invoking.html
- Cloudflare blog: "Conntrack tales - one thousand and one flows": https://blog.cloudflare.com/conntrack-tales-one-thousand-and-one-flows/; "How to stop running out of ephemeral ports and start to love long-lived connections" (Marek Majkowski, 2022-02-02): https://blog.cloudflare.com/how-to-stop-running-out-of-ephemeral-ports-and-start-to-love-long-lived-connections/; "Path MTU discovery in practice": https://blog.cloudflare.com/path-mtu-discovery-in-practice/; "Broken packets: IP fragmentation is flawed" (2017-08-18): https://blog.cloudflare.com/ip-fragmentation-is-broken/
- netshoot README: https://github.com/nicolaka/netshoot
- Kubernetes: debug running pods: https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/; debug Services: https://kubernetes.io/docs/tasks/debug/debug-application/debug-service/; DNS debugging: https://kubernetes.io/docs/tasks/administer-cluster/dns-debugging-resolution/; port-forward: https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/; NetworkPolicy: https://kubernetes.io/docs/concepts/services-networking/network-policies/
- Docker: networking overview: https://docs.docker.com/engine/network/; bridge driver options: https://docs.docker.com/engine/network/drivers/bridge/; packet filtering and firewalls: https://docs.docker.com/engine/network/packet-filtering-firewalls/
- AWS: NAT gateway troubleshooting: https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateway-troubleshooting.html; NAT gateway CloudWatch metrics: https://docs.aws.amazon.com/vpc/latest/userguide/metrics-dimensions-nat-gateway.html; VPC Flow Logs: https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html; security groups vs network ACLs: https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html; ALB attributes (idle timeout): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-load-balancer-attributes.html; target group health checks: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html; EC2 network MTU: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/network_mtu.html
- AWS, NAT gateway basics (55,000 per unique destination): https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateway-basics.html; Docker, Docker with iptables (DOCKER-USER): https://docs.docker.com/engine/network/firewall-iptables/; Linux kernel source
nf_conntrack_core.c(the "table full" message): https://github.com/torvalds/linux/blob/master/net/netfilter/nf_conntrack_core.c - Azure: SNAT for outbound connections: https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-outbound-connections
- PostgreSQL libpq connection parameters: https://www.postgresql.org/docs/current/libpq-connect.html; php-src
pdo_pgsqldriver (PDO_ATTR_TIMEOUT→connect_timeout): https://github.com/php/php-src/blob/master/ext/pdo_pgsql/pgsql_driver.c - redis-cli: https://redis.io/docs/latest/develop/tools/cli/
- Laravel 13: HTTP client: https://laravel.com/docs/13.x/http-client; deployment (
/uphealth route): https://laravel.com/docs/13.x/deployment; Artisan: https://laravel.com/docs/13.x/artisan; database: https://laravel.com/docs/13.x/database; Redis: https://laravel.com/docs/13.x/redis - PHP manual, fsockopen/stream sockets: https://www.php.net/manual/en/function.fsockopen.php
- Go:
go doc net.OpError,net.DNSError,net.Dialer,net/http/httptrace.ClientTrace(Go 1.27 toolchain, saved asgo-doc.txt)