Skip to main content

TCP & UDP

Learning objectives
  • Walk through the TCP handshake, teardown and state machine, and explain why TIME_WAIT exists
  • Distinguish flow control (receiver window) from congestion control (cwnd) and estimate throughput from window and RTT
  • Explain slow start, CUBIC and BBR at a level an interviewer expects from an architect
  • Diagnose Nagle/delayed-ACK stalls, head-of-line blocking, dead idle connections and ephemeral port exhaustion
  • Configure connection pooling and keep-alive in Go for a high-volume partner integration
  • Choose UDP deliberately, with the reliability you then have to build yourself

TL;DR​

  • TCP gives a reliable, ordered byte stream at the cost of a 1-RTT handshake, per-connection state, and head-of-line blocking (one lost segment stalls everything behind it). UDP gives independent datagrams with no handshake, no ordering, no retransmission.
  • The side that closes first sits in TIME_WAIT for 2×MSL (60 s on Linux). Lots of short-lived outbound connections → thousands of TIME_WAIT sockets → ephemeral port exhaustion (cannot assign requested address).
  • Flow control (receiver window, rwnd) protects the receiver; congestion control (cwnd) protects the network. Throughput ≈ min(cwnd, rwnd) / RTT.
  • New connections start slow (initial cwnd ≈ 10 segments ≈ 14 KB). This is why connection reuse matters more than raw bandwidth for API latency.
  • Nagle + delayed ACK can add ≈40 ms+ stalls to small request/response patterns; Go sets TCP_NODELAY by default.
  • Middleboxes (NAT, firewalls, load balancers) silently drop idle connections. Keep pool idle timeouts below the shortest middlebox idle timeout, or use keep-alive probes.
  • Go's http.Transport keeps only 2 idle connections per host by default — raise MaxIdleConnsPerHost for any service that calls one host at high concurrency.

Why it matters​

Most "the network is slow" incidents in backend systems are not bandwidth problems. They are TCP behaviour problems:

  • A payment service calls an acquirer at 2,000 requests/s through a NAT gateway with default HTTP client settings. Every burst opens new connections, the pool keeps only 2, the rest close and sit in TIME_WAIT, and after a minute the NAT or the host runs out of source ports. Authorizations start timing out during the evening peak.
  • A core-banking adapter keeps a pool of database connections. A firewall between the data centers drops flows idle for more than 30 minutes without telling anyone. The first transfer of the morning hangs for minutes on a dead socket.
  • An e-commerce mobile API serves product listings from a region 150 ms away. Each fresh connection pays the TCP handshake, TLS handshake and slow start before the first useful byte — the user sees a second of spinner before any product appears.

An architect who can name the mechanism (TIME_WAIT, idle timeout, slow start) and the fix (pooling, keep-alive, edge termination) solves these in an hour instead of a week.

Core concepts​

The three-way handshake​

What the handshake does:

  1. Synchronizes sequence numbers. Each side picks a random initial sequence number (ISN) so that old or forged segments do not fit.
  2. Negotiates options: MSS, window scaling (lets the window exceed 64 KB), SACK (selective acknowledgment of out-of-order data), timestamps (RTT measurement and protection against wrapped sequence numbers).
  3. Costs one RTT. At 150 ms RTT, that is 150 ms before the first request byte. TLS adds at least another RTT on top (see TLS & HTTPS).

On the server, completed connections wait in the accept queue until the application calls accept(). Its size is capped by net.core.somaxconn (default 4096 on Linux 5.4+, 128 before). If the app accepts too slowly during a spike, the queue overflows and SYNs or ACKs are dropped; clients see connect times of ≈1 s, 3 s, 7 s — the signature of SYN retransmissions with exponential backoff.

SYN flood and SYN cookies: an attacker sends SYNs without completing handshakes to fill the half-open queue. SYN cookies encode the connection state into the server's ISN so no state is stored until the final ACK arrives.

TCP Fast Open (TFO) lets a returning client send data in the SYN using a cookie, saving one RTT, but middlebox interference limited adoption. QUIC solved the same problem more robustly.

The state machine and TIME_WAIT​

Two states cause most production confusion:

TIME_WAIT (on the side that closed first — the active closer). The socket lingers for 2 × MSL (maximum segment lifetime); Linux hard-codes 60 seconds. It exists for two reasons:

  1. If the final ACK is lost, the peer retransmits its FIN; the TIME_WAIT socket can re-ACK it instead of answering with a RST.
  2. It prevents delayed segments from an old connection being accepted by a new connection with the same 4-tuple (src IP, src port, dst IP, dst port).

TIME_WAIT is cheap in memory but it holds the 4-tuple. A client that opens and closes many connections to the same destination burns through source ports.

CLOSE_WAIT (on the side that received FIN but has not called close() yet). A pile of CLOSE_WAIT sockets is almost always an application bug: a leaked connection, an HTTP response body never closed, a pool that never notices the peer went away.

# Count sockets per state on a Linux host
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn
# Who holds CLOSE_WAIT sockets?
ss -tanp state close-wait

Abortive close: a RST tears down immediately without TIME_WAIT. Setting SO_LINGER with a zero timeout forces this; it avoids TIME_WAIT but discards unsent data and can confuse the peer. Treat it as a last resort.

Flow control: the receiver window​

Each ACK carries the receiver's advertised window (rwnd): how many more bytes it can buffer. A slow consumer shrinks the window; at zero the sender stops and periodically probes. The 16-bit window field caps at 64 KB, so the window scale option (shift up to 14) allows windows up to ≈1 GiB.

The window must cover the bandwidth-delay product (BDP) to fill a pipe:

  • BDP = bandwidth × RTT. A 1 Gbit/s link with 100 ms RTT holds 125 MB/s × 0.1 s = 12.5 MB in flight.
  • With a 64 KB window on that path, throughput is capped at 64 KB / 0.1 s ≈ 640 KB/s, no matter how fat the link is.

Linux auto-tunes buffers (net.ipv4.tcp_rmem, tcp_wmem), so this mostly bites when someone hard-codes small socket buffers, or on cross-region replication and backup links where BDP is large.

Congestion control​

Congestion control limits how much unacknowledged data the sender keeps in flight (cwnd) to avoid overloading the network. The sender may have at most min(cwnd, rwnd) bytes outstanding, so:

Throughput ≈ min(cwnd, rwnd) / RTT

Phase / algorithmBehaviourPractical meaning
Slow startStarts at initial cwnd (10 segments ≈ 14 KB, RFC 6928) and roughly doubles every RTTA fresh connection needs several RTTs to reach full speed; a 100 KB response takes ≈3 RTTs on a cold connection
Congestion avoidanceGrows cwnd roughly linearly after crossing the slow-start thresholdSteady state for long transfers
Fast retransmit / recoveryThree duplicate ACKs → retransmit the missing segment without waiting for a timeoutSingle losses cost one RTT, not a timeout
Retransmission timeout (RTO)No ACK at all → wait RTO (min ≈200 ms on Linux, initial 1 s), then retransmit and shrink cwndShows up as p99 latency spikes of 200 ms+ under packet loss
Reno / NewRenoLoss-based AIMD: halve cwnd on lossClassic textbook model
CUBICLoss-based; after a loss, cwnd follows a cubic curve that quickly regrows toward the previous maximumDefault on Linux and on modern Windows and macOS; good on high-BDP paths
BBR (Google)Model-based: estimates bottleneck bandwidth and minimum RTT, then paces at that rate; loss is not the primary signalBetter throughput on lossy, long-haul or mobile paths; v1 had fairness issues against CUBIC; later versions address them

Two knobs worth knowing:

  • net.ipv4.tcp_slow_start_after_idle (default 1): a pooled connection idle longer than an RTO drops back to slow start. For latency-sensitive long-lived connections (e.g. a gateway to a backend over a long RTT), setting it to 0 keeps the window warm.
  • net.ipv4.tcp_congestion_control: switch to bbr for edge servers serving mobile users. Measure before and after; benefits vary by path.

Nagle's algorithm and delayed ACK​

  • Nagle (RFC 896): if there is unacknowledged data in flight, buffer small writes until an ACK arrives or a full segment accumulates. Great for telnet, bad for RPC.
  • Delayed ACK: the receiver waits a short time (Linux ≈40 ms minimum, up to 200 ms on some stacks) hoping to piggyback the ACK on response data.

Together they deadlock briefly: the client writes a request in two small writes (headers, then body). Nagle holds the second write waiting for the ACK of the first; the server delays the ACK waiting for more data. Result: a ≈40 ms (or 200 ms) stall per request. Fixes: write the request in one buffer, or set TCP_NODELAY. Go sets TCP_NODELAY on TCP connections by default ((*net.TCPConn).SetNoDelay(true)), as do most modern HTTP clients — but check older Java/C clients and proxies.

Head-of-line blocking​

TCP delivers bytes in order. If segment 5 of 20 is lost, segments 6–20 sit in the kernel buffer until 5 is retransmitted, even if they belong to completely independent HTTP/2 streams. On a lossy mobile network, multiplexing everything over one TCP connection can be worse than six HTTP/1.1 connections. This is the main motivation for QUIC, which runs streams over UDP with per-stream ordering — see HTTP/1.1, HTTP/2, HTTP/3.

Keep-alive: two different things​

TCP keep-aliveHTTP keep-alive (persistent connections)
WhatKernel sends empty probes on an idle connectionReuse one TCP connection for many HTTP requests
GoalDetect dead peers; keep NAT/firewall state aliveAvoid handshake + slow start per request
Linux defaultsFirst probe after 7200 s idle, then every 75 s, 9 probesHTTP/1.1 is persistent by default
Gonet.Dialer.KeepAlive (enabled by default, 15 s in current versions)http.Transport pool, IdleConnTimeout

Middlebox idle timeouts are the reason keep-alive matters. Examples (approximate, vendor-specific, verify for your setup): AWS NAT gateway ≈350 s, AWS NLB TCP idle ≈350 s, AWS ALB default 60 s, many enterprise firewalls 30–60 minutes. When a middlebox drops the flow state silently, the next write on that connection either gets a RST or vanishes; without application timeouts, the kernel keeps retransmitting for up to ≈15 minutes (tcp_retries2 = 15) before giving up.

Connection pooling​

Reusing connections removes handshake, TLS and slow-start cost and keeps the TIME_WAIT rate low. Rules of thumb:

  1. Size the pool to concurrency, not to RPS. By Little's law, concurrent requests ≈ RPS × latency. 2,000 RPS × 50 ms ≈ 100 connections in use.
  2. Idle timeout below every middlebox timeout on the path (e.g. 50 s if an ALB with 60 s is in front of the server; the server's keep-alive timeout should be longer than the load balancer's to avoid 502s).
  3. Cap per-host connections so a slow dependency cannot make you open thousands of sockets (and so you do not DDoS a partner).
  4. Rotate long-lived connections occasionally (max connection age) so DNS changes and load balancer scale-outs take effect.
  5. Always close or drain response bodies, or the connection never returns to the pool.

Ephemeral port exhaustion​

Each outbound connection needs a unique 4-tuple. With one source IP calling one destination IP:port, only the source port varies. Linux picks it from net.ipv4.ip_local_port_range, default 32768–60999 ≈ 28,000 ports.

If every request opens a new connection and the client closes first, each port is stuck in TIME_WAIT for 60 s:

≈28,000 ports / 60 s ≈ 470 new connections per second, sustained, to one destination — beyond that, connect() fails with EADDRNOTAVAIL ("cannot assign requested address").

A NAT gateway has the same problem for all hosts behind it combined. Fixes, in order of preference:

  1. Reuse connections (pooling, HTTP keep-alive, HTTP/2 multiplexing). This is the real fix.
  2. Let the server close the connection where the protocol allows, so TIME_WAIT lands on the server side.
  3. Widen ip_local_port_range (e.g. 10000–65000).
  4. Enable net.ipv4.tcp_tw_reuse=1 for outbound connections (safe with TCP timestamps; recent kernels default to loopback-only). Do not look for tcp_tw_recycle — it broke clients behind NAT and was removed in Linux 4.12.
  5. Add more source IPs or more destination IPs (each new 4-tuple dimension multiplies capacity).

UDP​

UDP adds only ports and a checksum (8-byte header) to IP. No connection, no ordering, no retransmission, no congestion control. You choose UDP when:

Use caseWhy UDP
DNSOne small request, one small response; a handshake would triple latency
QUIC / HTTP/3Builds reliability, ordering per stream and congestion control in user space, avoiding TCP head-of-line blocking and kernel ossification
Voice/video, WebRTCA late packet is useless; better to drop it than to stall the stream
Online games, live telemetryLatest state supersedes old state
Metrics (StatsD), syslogFire-and-forget; losing a sample is acceptable
Market data multicast (exchanges)One packet reaches many subscribers; receivers detect gaps by sequence number and recover from a snapshot or retransmission service
NTP, DHCP, SNMPSimple request/response or broadcast

If you pick UDP you own: packet size (stay below the path MTU, ≈1,200 bytes is a safe payload), loss detection, retransmission or forward error correction, ordering, congestion control and amplification abuse (open DNS/NTP/memcached servers have been used in large reflection DDoS attacks).

Trade-offs​

OptionStrengthsWeaknessesChoose when
New TCP connection per requestSimple, no stale-connection bugsHandshake + slow start each time; TIME_WAIT and port exhaustion at volumeRare, low-volume calls
Pooled persistent connections (HTTP/1.1)Amortizes setup; predictablePool tuning; stale connections behind middleboxes; one request per connection at a timeDefault for service-to-service HTTP
Single multiplexed connection (HTTP/2, gRPC)Very few sockets, many concurrent streamsTCP head-of-line blocking; per-connection load-balancing imbalanceInternal RPC on low-loss networks
QUIC (UDP)No TCP HOL blocking, 0/1-RTT setup, connection migrationUDP blocked on some networks, more CPU, less mature toolingMobile clients, lossy networks, edge
Raw UDPLowest latency, multicastYou build reliability and congestion controlMedia, telemetry, market data feeds
CUBICDefault, well understood, fair with itselfLoss-based: suffers on lossy pathsData-center and general traffic
BBRHigher throughput on lossy/long pathsFairness and tuning concerns; measure firstCDN/edge servers, mobile-heavy egress

In practice​

A tuned HTTP client for a high-volume partner (card scheme, acquirer, core banking gateway):

package partner

import (
"context"
"fmt"
"io"
"net"
"net/http"
"time"
)

// NewClient returns an HTTP client for many concurrent calls to one host.
func NewClient() *http.Client {
dialer := &net.Dialer{
Timeout: 2 * time.Second, // TCP connect timeout
KeepAlive: 30 * time.Second, // TCP keep-alive probe interval
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 100, // default is 2
MaxConnsPerHost: 200, // protect the partner and our ports
IdleConnTimeout: 50 * time.Second, // below the shortest middlebox idle timeout
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
ExpectContinueTimeout: time.Second,
}
return &http.Client{Transport: transport, Timeout: 10 * time.Second}
}

// Authorize shows the body-handling rule that keeps connections reusable.
func Authorize(ctx context.Context, c *http.Client, url string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, nil)
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Drain even when ignoring the body, or the connection is not reused.
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authorize: unexpected status %d", resp.StatusCode)
}
return nil
}

For database/sql, the equivalent knobs are SetMaxOpenConns (default unlimited — always set it), SetMaxIdleConns (default 2), SetConnMaxIdleTime (below firewall idle timeouts) and SetConnMaxLifetime (rotate connections so failovers and DNS changes are picked up).

Kernel settings you may touch on busy proxies and gateways (Linux; measure before changing):

sysctl net.core.somaxconn # accept queue cap
sysctl net.ipv4.tcp_max_syn_backlog # half-open queue
sysctl net.ipv4.ip_local_port_range # ephemeral ports
sysctl net.ipv4.tcp_tw_reuse # reuse TIME_WAIT for outbound
sysctl net.ipv4.tcp_congestion_control # cubic or bbr
sysctl net.ipv4.tcp_slow_start_after_idle # 0 keeps cwnd warm on idle pools
nstat -az TcpExtListenOverflows TcpExtListenDrops TcpRetransSegs

Server side in Go: set http.Server.ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout. A missing ReadHeaderTimeout lets slow clients (Slowloris) hold connections open indefinitely.

Common pitfalls​

  • Default MaxIdleConnsPerHost (2) under high concurrency. Symptom: thousands of TIME_WAIT sockets on the client, rising connect latency, eventually cannot assign requested address.
  • Not draining/closing response bodies. Symptom: connection count grows with traffic, goroutine leaks, CLOSE_WAIT on the server side.
  • Pool idle timeout longer than the NAT/firewall/LB idle timeout. Symptom: the first request after a quiet period fails with connection reset by peer or hangs until a timeout; retries succeed.
  • Server keep-alive timeout shorter than the load balancer's idle timeout. Symptom: sporadic 502s at the load balancer, because the backend closes a connection exactly as the LB reuses it.
  • No application-level timeouts. Symptom: requests hang for ≈15 minutes during a network partition because the kernel is still retransmitting.
  • Accept queue too small or app accepts too slowly. Symptom: connect latency clustered at ≈1 s and ≈3 s during spikes, ListenOverflows counter increasing.
  • Fragmented UDP. Symptom: large DNS responses or UDP payloads silently lost on some networks; keep datagrams small.
  • Treating TCP as message-oriented. TCP is a byte stream: one Write can arrive as several Reads and vice versa. Length-prefix or delimit your frames (e.g. ISO 8583 over TCP uses a length header).

Interview angle​

  • "Explain the TCP handshake" — give the three steps, then add why: ISN synchronization, option negotiation, and the 1-RTT cost that motivates connection reuse, TLS 1.3 and QUIC.
  • "What is TIME_WAIT and why do I have 30,000 of them?" — active closer, 2×MSL, protects against delayed duplicates; caused by per-request connections; fix with pooling before touching sysctls.
  • "Why is our cross-region replication slow on a 10 Gbit/s link?" — bandwidth-delay product, window sizes, loss + CUBIC; check ss -ti for cwnd, rtt and retransmits.
  • "TCP or UDP for X?" — show you know what you lose with UDP and what you must rebuild.
  • Follow-ups: Nagle vs delayed ACK, TCP vs HTTP keep-alive, head-of-line blocking and how QUIC fixes it, what BBR changes.
  • Red flags: "UDP is faster" with no qualification, "just increase the timeout", tuning tcp_tw_recycle, or not knowing that TCP is a byte stream.

Self-check​

1. Why does TIME_WAIT exist, and which side of the connection ends up in it?

The side that sends the first FIN (the active closer) enters TIME_WAIT for 2×MSL (60 s on Linux). It lets the socket re-acknowledge a retransmitted FIN if the final ACK was lost, and it keeps the 4-tuple reserved so delayed segments from the old connection cannot corrupt a new connection with the same addresses and ports.

2. A client calls one API at 1,500 new connections per second and starts failing with “cannot assign requested address”. Explain and fix.

Each connection uses a unique source port to the same destination; the client closes first, so each port sits in TIME_WAIT for 60 s. With ≈28,000 ephemeral ports, the sustainable rate is ≈470 new connections/s, so ports run out. Fix by reusing connections (raise MaxIdleConnsPerHost, drain bodies, use HTTP/2), then optionally widen the port range, enable tcp_tw_reuse, or add source IPs.

3. What is the difference between flow control and congestion control?

Flow control (receiver window, rwnd) prevents the sender from overrunning the receiver's buffer; the receiver advertises it in every ACK. Congestion control (cwnd) prevents the sender from overloading the network path; the sender infers it from ACKs, losses and RTT. The sender is limited by the smaller of the two.

4. Estimate the maximum throughput of a single TCP flow with a 256 KB window over a 50 ms RTT path.

Throughput ≈ window / RTT = 256 KB / 0.05 s ≈ 5 MB/s ≈ 40 Mbit/s, regardless of link capacity. To fill a 1 Gbit/s link at 50 ms you need ≈6.25 MB in flight (the bandwidth-delay product), so you would need larger windows or multiple parallel flows.

5. Why can the first request after a quiet night fail, while retries succeed?

A NAT, firewall or load balancer dropped the idle connection's state without notifying either end. The client's pool still thinks the connection is alive, writes to it, and gets a RST or no answer. Retries open a fresh connection. Fix: pool idle timeout below the middlebox timeout, TCP keep-alive probes more frequent than the timeout, connection max lifetime, and safe retries for idempotent requests.

6. How do Nagle's algorithm and delayed ACK interact to produce latency?

Nagle holds a small write while earlier data is unacknowledged; the receiver delays its ACK hoping to piggyback it on a response. If a request is written in two small pieces, the second piece waits for an ACK that the receiver is deliberately delaying, adding ≈40–200 ms. Write in one buffer or disable Nagle with TCP_NODELAY (the Go default).

7. An exchange distributes prices over UDP multicast. What must a consumer implement?

Gap detection using per-message sequence numbers, a recovery path (request retransmission or load a snapshot and replay), handling of duplicates and out-of-order packets, and monitoring of drop rates. The consumer must also be fast enough to keep socket buffers from overflowing, since UDP has no flow control to slow the sender down.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Goal: see TIME_WAIT and port exhaustion happen, then fix them with pooling.

  1. Capture a handshake and teardown:

    sudo tcpdump -i any -nn 'tcp port 443 and host example.com' -c 20 &
    curl -s -o /dev/null https://example.com

    Identify SYN, SYN-ACK, ACK, the FINs, and which side closed first.

  2. Write a Go load generator that sends 5,000 requests with 200 goroutines to a local Go HTTP server, first with http.DefaultClient, then with the tuned client from this page. During each run, on Linux:

    watch -n1 "ss -tan state time-wait | wc -l"
    ss -s
  3. Repeat run 1 with MaxIdleConnsPerHost left at the default and with the response body not drained. Compare TIME_WAIT counts and total duration.

  4. Optional (Linux): add ≈100 ms RTT (50 ms each way on loopback) and 1% loss with sudo tc qdisc add dev lo root netem delay 50ms loss 1%, rerun, and inspect ss -ti for rtt, cwnd and retrans. Remove with sudo tc qdisc del dev lo root.

Done when: you can show a table of TIME_WAIT count and p99 latency for default vs tuned clients, and explain each difference using concepts from this page.

Further reading​

  • TCP/IP Illustrated, Volume 1 (2nd ed.) — Kevin Fall & W. Richard Stevens (connection management, timeouts, congestion control).
  • High Performance Browser Networking — Ilya Grigorik, chapters "Building Blocks of TCP" and "Building Blocks of UDP" (hpbn.co).
  • RFC 9293 — Transmission Control Protocol (the 2022 consolidated TCP spec).
  • RFC 6928 — Increasing TCP's Initial Window.
  • "BBR: Congestion-Based Congestion Control" — Cardwell et al., ACM Queue, 2016.
  • Systems Performance (2nd ed.) — Brendan Gregg, networking chapter.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).