Networking for backend engineers: DNS, TCP, TLS and debugging connections
How one API call goes through DNS, TCP, TLS 1.3 and keep-alive, the TCP details that bite, connect vs read timeouts, L4/L7 load balancers, NAT, MTU, mTLS, and a toolkit of dig, curl, ss, tcpdump and openssl.
On this page
1. The problem
Every morning the service logs a few dozen Connection reset errors calling an internal API through an ALB, then they stop. At the same time, the first report job of the day hangs for 15 minutes on its first PostgreSQL query.
2. Key idea
An API call is like shipping a parcel: look up the address (DNS), pass the gate (TCP), show papers (TLS), then deliver (HTTP). Each step costs about one RTT. With a 48 ms RTT: a new connection takes ~166 ms, a reused one (keep-alive) ~52 ms. Hence connection pools.
Two consequences:
- DNS is only asked when opening a new connection. The JVM also caches results for 30 seconds (
networkaddress.cache.ttlinjava.security). If a DB fails over by changing a CNAME, the pool keeps the old IP until connections reachmaxLifetime. - Middleboxes forget idle connections. AWS NAT and NLB drop them after 350 seconds, ALB after 60; Linux TCP keepalive waits 7200 seconds. The next use gets a reset or hangs.
2.1 What does the error name tell you?
| Java says | Meaning | Usually |
|---|---|---|
Connection refused (a few ms) |
reached the host, nobody on the port | app not running, wrong port |
Connect timed out |
the SYN went into the void | firewall/security group DROP, wrong IP, full backlog |
Read timed out |
connected, the other side didn't answer in time | slow or stuck upstream |
Connection reset |
the other side (or an LB) sent RST | stale pooled connection, server crash |
read() returns -1, then Broken pipe |
the other side closed politely (FIN) | server closed an idle keep-alive |
Set the connect timeout to 1–2 seconds and the read timeout from the other side's p99.
2.2 TIME_WAIT and load balancers
| Topic | Use when | Don't use when |
|---|---|---|
Kernel tuning (tcp_tw_reuse) |
you already use keep-alive and still run out of ports | instead of keep-alive and pools |
| L4 LB (NLB, kube-proxy) | plain TCP, balances per connection | gRPC, HTTP/2: long-lived connections stick to one backend |
| L7 LB (ALB, Nginx, Envoy) | balances per request, routes by URL | you need TLS passthrough |
TIME_WAIT: the side that closes first holds the socket for 60 seconds. One connection per request to the same destination exhausts ports: Cannot assign requested address.
3. Sample configuration
# HikariCP: lifetime shorter than every idle timeout on the path (ALB 60 s, NAT 350 s)
spring.datasource.hikari.max-lifetime=300000 # 5 minutes
spring.datasource.hikari.keepalive-time=30000 # probe idle connections every 30 s
spring.datasource.hikari.connection-timeout=2000
# PostgreSQL: a stuck query doesn't wait for tcp_retries2 (~15 minutes)
spring.datasource.url=jdbc:postgresql://db:5432/app?socketTimeout=30curl -o /dev/null -sS -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} new=%{num_connects}\n' https://example.com/
# dns=0.0019 connect=0.0479 tls=0.1066 ttfb=0.1660 new=1 (cumulative marks: subtract to get each phase)HTTP clients: evict idle connections before the server's keep-alive timeout, and retry once for idempotent requests.
A debugging toolkit and a few TCP details
| Question | Command |
|---|---|
| Which IP, what TTL | dig +noall +answer api.example.com |
| Which phase is slow | curl -w as above, curl -v --trace-time |
| Certificate, TLS, ALPN | openssl s_client -connect host:443 -servername host -alpn h2 |
| Socket states | ss -tan state time-wait | wc -l, ss -tnp dst :5432 |
| Who sent the RST, did the SYN leave | tcpdump -i any -nn 'port 5432 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)' |
- Backlog: a full accept queue (app out of workers, long GC) makes Linux drop SYNs; clients see connect timeouts. Check
ss -lnt, columnRecv-Q. - Nagle + delayed ACK: writing headers and body as two small writes can add ~40 ms per request;
setTcpNoDelay(true). - MTU: a firewall blocking ICMP "fragmentation needed" lets small requests through while large responses hang. Try
ping -M do -s 1472 host. - Kubernetes
ndots:5: short names are tried against every search domain, so one outbound call becomes 4–5 lookups; use a trailing dot. - mTLS: expired certificates are the most common incident; automate rotation and alert weeks ahead.
4. Working with AI
Delegate to AI: reading tcpdump/curl -v output, writing pool and timeout configuration, scripts that time each phase.
Check yourself:
- Every client has a connect timeout and a read timeout.
- The pool's
maxLifetimeis shorter than LB/NAT idle timeouts; keepalive is on. - The HTTP client is a shared bean, not created per request.
- Port exhaustion isn't "fixed" with kernel tuning while the app lacks keep-alive.
5. Exercises
Exercise 1: Read the morning-reset incident
A service calls an internal API through an ALB. Every morning at 8:00 there are ~40 Connection reset errors in the first 2 minutes, then all is normal. The HTTP client pool keeps idle connections up to 5 minutes. AI suggests "raise retries to 5". Diagnose and fix.
Solution to Exercise 1
- Diagnosis: the ALB closes idle connections after 60 seconds but the pool keeps them for 5 minutes. After a quiet night, the first request on each connection hits one the ALB has forgotten. Errors only hit the first request per connection;
tcpdumpshows RSTs from the LB side. - Five retries hide the bug, and are dangerous for POSTs.
- Fix: evict idle connections after ~50 seconds (under 60), retry once for idempotent requests when a reused connection is reset.
Exercise 2: Connect timeout after a security-group change
After a security-group change the service reports Connect timed out to the DB (not Connection refused). Why a timeout, and what do you check, in order?
Solution to Exercise 2
- Security groups drop packets instead of sending RST, so the client sees a timeout. Refused would mean the host was reached and nobody listened.
- Check:
digthe DB name resolves to the right IP;nc -vz -w 2 db-host 5432from the app host itself;tcpdumpshows SYNs leaving with no SYN-ACK; the DB's inbound rule allows the app's security group on port 5432.
Summary
- A new HTTPS call costs 3 RTTs after DNS; keep-alive cuts about two thirds.
- DNS is only asked for new connections; the JVM caches for 30 seconds.
- Refused, connect timeout, read timeout, reset: each points to one layer.
- Fix TIME_WAIT with keep-alive and pools before tuning the kernel.
- Pool lifetimes shorter than LB/NAT idle timeouts; always set socket timeouts.
Further reading: Connection pools and HikariCP.
Self-compiled notes from official documentation and hands-on practice.
Practice interview questions on this topic
- What happens when your service calls https://api.example.com/orders?
- What is TIME_WAIT, and what causes do you suspect when logs show "Connection reset by peer"?
- How do L4 and L7 load balancers differ, and why do new pods get no traffic when you scale a gRPC service?
- Why does a Java service keep failing for minutes after DB failover, or hang 15 minutes on the first query after a quiet night?
- A Spring Boot service is overloaded: where do requests queue, and why do clients see connect timeouts, 502, 503 or 504?
- How do services authenticate each other? What is mTLS, and how does it compare with API keys and JWT?
Comments
Community rules