TCP & UDP
"This protocol provides a procedure for application programs to send messages to other programs with a minimum of protocol mechanism. The protocol is transaction oriented, and delivery and duplicate protection are not guaranteed." — J. Postel, RFC 768: User Datagram Protocol, August 1980
Summary: TCP gives you a reliable, ordered byte stream and charges you a handshake, per-connection state, congestion control and head-of-line blocking; UDP gives you single datagrams with almost nothing added, and leaves loss, order, pacing and security to you. QUIC is the modern answer for when you want TCP's guarantees without its costs, built on UDP. Focus: The protocol-level mechanics a system designer must be able to reason about (handshake, sequence and acknowledgement numbers, retransmission and RTO, flow and congestion control including CUBIC and BBR, Nagle and delayed ACK, TIME_WAIT, keepalive, MSS/MTU, SYN floods and SYN cookies, TCP Fast Open), UDP and its uses (DNS, RTP, games, telemetry, multicast), QUIC (streams, 0-RTT, connection migration), how L4 load balancers and NAT interact with long-lived connections, and the Linux, Go, PHP and Laravel knobs that control all of it. Learning goal: For any connection in a design, say which transport it uses and why, how many round trips it costs before the first byte, what happens when a packet is lost, which timeouts and keepalives bound it, what a NAT or an L4 load balancer in the middle will do to it, and which error message you will see when it breaks.
This chapter sits in the Networking & Protocols group between Forward vs Reverse Proxies and HTTP/1.1, HTTP/2, HTTP/3, Keep-Alive & HTTPS. It owns the protocol-level comparison and the system-level decisions. The host view (sockets, ephemeral ports, ss, tcpdump, nc, conntrack) lives in Ports, Sockets & Connections; the layer model in Network Models: OSI vs TCP/IP; address translation in NAT, PAT & Port Forwarding; the TLS wire handshake in TLS in Practice; and failure diagnosis in the Network Troubleshooting Playbook. HTTP/3 as a protocol is taught in HTTP evolution, load-balancing algorithms in Load Balancing, DDoS defence in DDoS Protection, and pool sizing in Connection Pooling.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why two transports exist at all | Why it exists |
| RFC 768, RFC 793 to RFC 9293, Jacobson, CUBIC, BBR, QUIC | Where it comes from |
| TCP and UDP as service models | TCP, UDP |
| SYN, SYN-ACK, ACK, ISN | Three-way handshake |
| Sequence numbers, ACK, RTO, SACK | Retransmission |
| Receive window, window scaling, BDP | Flow control |
| Slow start, congestion avoidance, fast retransmit, CUBIC, BBR | Congestion control |
| Nagle, delayed ACK, TCP_NODELAY | Nagle and delayed ACK |
| Head-of-line blocking | Head-of-line blocking |
| FIN, RST, TIME_WAIT, connection churn | Teardown and TIME_WAIT |
| Keepalive, idle timeouts | Keepalive |
| MSS, MTU, path MTU discovery | MSS and MTU |
| SYN flood, backlog, somaxconn, SYN cookies | SYN floods |
| TCP Fast Open | TFO |
| Multicast and broadcast | Multicast |
| Reliability you build on UDP | Application-level reliability |
| QUIC, 0-RTT, connection migration | QUIC |
| Bufferbloat | Bufferbloat |
| L4 load balancers and NAT | L4 and NAT |
| Header fields, states, timers, sysctls, errors | Mechanics |
| Code | Go, Laravel |
| Classic production problems | Solving the classic problems |
| Which transport for which job | Choosing |
| Monolith to distributed system | In architecture |
| Measure it yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The two service models.
| Property | TCP | UDP | QUIC (over UDP) |
|---|---|---|---|
| Unit the app sees | Byte stream, no message boundaries | Datagram, boundaries kept | Streams of bytes, many per connection |
| Connection setup | Three-way handshake, 1 RTT | None | 1 RTT including TLS 1.3; 0-RTT on resumption |
| Reliability | Retransmits until ACKed or the connection dies | None: lost is lost | Retransmits per stream |
| Ordering | Total order over the whole connection | None; reordering and duplicates possible | Per stream |
| Flow control | Receive window | None | Per stream and per connection |
| Congestion control | Mandatory (Reno, CUBIC, BBR) | None; the app must behave (RFC 8085) | Mandatory (RFC 9002) |
| Header | 20 to 60 bytes | 8 bytes | Short header plus UDP's 8 |
| Encryption | None (TLS on top) | None (DTLS on top) | Always (TLS 1.3 built in) |
| Survives an IP change | No; the 4-tuple is the identity | No concept of connection | Yes, connection IDs and migration |
| Typical use | HTTP/1.1 and HTTP/2, databases, Redis, SSH, file transfer | DNS, RTP voice/video, games, StatsD, DHCP, WireGuard | HTTP/3, modern browsers and mobile apps |
The mechanisms you will meet in incidents.
| Mechanism | In plain words | Knob (Linux / Go / PHP) | What goes wrong when ignored |
|---|---|---|---|
| Dial timeout | How long to wait for the handshake | net.Dialer.Timeout, connectTimeout() | Callers hang ~131 s on a black-holed SYN |
| Read deadline | How long to wait for the next byte | SetReadDeadline, stream_set_timeout | A silent peer blocks a worker forever |
| Keepalive | Probe idle connections | tcp_keepalive_time, KeepAliveConfig | NAT or NLB drops the flow after 350 s idle; next write gets RST |
| TIME_WAIT | Closer remembers the 4-tuple for a while | tcp_tw_reuse, connection reuse | Ephemeral port exhaustion, EADDRNOTAVAIL |
| Backlog | Queue of finished handshakes waiting for accept() | listen(backlog), somaxconn | SYNs dropped during bursts, 1 s+ extra latency |
| Nagle + delayed ACK | Batch small writes / delay ACKs | TCP_NODELAY | 40 ms stalls on request/response protocols |
| Congestion control | Do not send faster than the path allows | tcp_congestion_control | Low throughput on long fat pipes, or bufferbloat |
| MSS / PMTUD | Segment size that fits the path | tcp_mtu_probing, MSS clamping | Small requests work, large ones hang (MTU black hole) |
Round trips before the first response byte (from the RFCs; the lab prints this table at several RTTs).
| Setup | RTTs | At 80 ms RTT |
|---|---|---|
| UDP request/response (DNS-style) | 1 | 80 ms |
| TCP, connection already open | 1 | 80 ms |
| New TCP connection + request | 2 | 160 ms |
| TCP Fast Open with cached cookie | 1 | 80 ms |
| New TCP + TLS 1.3 + request | 3 | 240 ms |
| QUIC new connection + request | 2 | 160 ms |
| QUIC 0-RTT resumption | 1 | 80 ms |
The picture shows one TCP connection's life: a one-round-trip handshake that agrees on sequence numbers and options, a data phase where every byte is numbered and acknowledged, and a four-segment teardown that leaves the side that closed first in TIME-WAIT. The right column is the same exchange over UDP: two datagrams, no state, and no help if one of them is lost.
Why it exists
IP moves packets between hosts on a best-effort basis: packets can be lost, duplicated, reordered or corrupted, and IP will not tell anyone. Applications need two very different things on top of that. Some need every byte, in order, and are willing to wait for it: a database result set, a file, a bank transfer request. Others need the newest data as fast as possible and would rather skip a lost packet than wait for it: a voice frame, a player position, a temperature sample. One transport cannot be optimal for both, so the Internet has two, and QUIC is a third built on the second.
| TCP: reliable stream | UDP: bare datagrams |
|---|---|
| Every byte arrives once, in order, or the connection fails | Each datagram arrives once, twice, late, out of order or never |
| One RTT handshake before data; state on both ends | No setup; the first packet carries data |
| Built-in congestion control protects the network | The application must pace itself (RFC 8085) |
| A lost segment delays everything behind it | A lost datagram delays nothing else |
| Byte stream: the app must frame messages | Message boundaries are preserved |
| Middleboxes (NAT, firewalls, LBs) understand it well | Middleboxes keep short timers; some block it |
| Kernel does the work; easy to use correctly | You design retries, ordering and security yourself |
The analogy we reuse on this page: the registered courier and the postcard. TCP is a registered courier service: before the first parcel goes out, the two offices phone each other and agree on a numbering scheme (the handshake); every parcel is numbered, the receiver signs for what arrived (ACKs), anything unsigned is sent again (retransmission), the receiver says how much shelf space is left (receive window), and the courier slows down when the roads are jammed (congestion control). If parcel 5 is lost, parcels 6 to 9 sit in the receiver's back office until 5 turns up (head-of-line blocking). When the business relationship ends, the office that hung up first keeps the file open for a while in case a late parcel arrives (TIME_WAIT). UDP is a postcard: you write the address and drop it in the box. It is cheap and quick, nobody signs for it, and if it matters that it arrived, you must ask for a reply yourself.
Three common misunderstandings, up front
- "TCP guarantees delivery." TCP guarantees that the bytes it delivers are complete and in order. It does not guarantee the peer's application processed them. If the connection breaks after your
write()returned, you cannot know whether the other side's database committed. Application-level acknowledgements and idempotency are still needed. - "UDP is faster." UDP does less, so it has less latency to add. A UDP application that needs reliability and reimplements it badly is slower than TCP. The real win of UDP is that a lost packet does not stall the packets after it, and that there is no handshake.
- "One
read()returns one message." TCP is a byte stream. A 10 KB response can arrive in seven reads, and two small responses can arrive in one. Every TCP protocol needs framing: a length prefix, a delimiter or a self-describing format (see the Go framing package).
Where it comes from
UDP, August 1980. RFC 768 is three pages long. It adds ports and an optional checksum to IP and nothing else, on purpose: "Applications requiring ordered reliable delivery of streams of data should use the Transmission Control Protocol (TCP)".
TCP, September 1981 to August 2022. RFC 793 defined TCP in 1981. Forty years of fixes were scattered across RFCs until RFC 9293 (August 2022, Internet Standard STD 7) collected them: "This document obsoletes RFC 793, as well as RFCs 879, 2873, 6093, 6429, 6528, and 6691 that updated parts of RFC 793."
Nagle, January 1984. RFC 896, Congestion Control in IP/TCP Internetworks, described small-packet congestion and the algorithm that now carries Nagle's name. RFC 9293 still says an endpoint "SHOULD implement the Nagle algorithm" and must let the application turn it off.
Congestion collapse and Jacobson, 1986 to 1988. After the Internet's throughput collapsed in 1986, Van Jacobson's 1988 work introduced slow start and congestion avoidance; RFC 5681 (September 2009) is the current standard text for slow start, congestion avoidance, fast retransmit and fast recovery.
Host requirements, October 1989. RFC 1122 set rules such as delayed ACKs and keepalive defaults; RFC 9293 now carries them: keepalives "MUST default to off" and the interval "MUST default to no less than two hours".
Path MTU discovery, November 1990; SACK, October 1996. RFC 1191 let hosts discover the largest packet a path accepts; RFC 2018 let receivers report non-contiguous blocks so senders retransmit only what is missing.
SYN floods, 1996 to 2007. SYN-flooding attacks became common in 1996; RFC 4987 (August 2007) surveyed the defences, including SYN cookies, which "allocate no state at all for connections in SYN-RECEIVED".
RTO, larger windows, TFO, 2011 to 2014. RFC 6298 (June 2011) lowered the initial RTO to 1 second; RFC 6928 (April 2013) proposed a 10-segment initial window; RFC 7323 (September 2014) defined window scaling and timestamps; RFC 7413 (December 2014) defined TCP Fast Open.
BBR, 2016. Cardwell, Cheng, Gunn, Hassas Yeganeh and Jacobson argued in ACM Queue (September-October 2016) that loss-based control "is the primary cause of these problems. When bottleneck buffers are large, loss-based congestion control keeps them full, causing bufferbloat."
UDP guidelines, March 2017; CUBIC, 2018 and 2023. RFC 8085 told UDP application designers how to behave without built-in congestion control. CUBIC, the Linux default for years, became RFC 8312 (February 2018) and then a Standards Track RFC 9438 (August 2023), which obsoletes RFC 8312.
QUIC, May 2021. RFC 9000 (transport) and RFC 9002 (loss detection and congestion control) standardised a UDP-based, always-encrypted, multiplexed transport; HTTP/3 runs on it.
Year Document What changed in practice
1 1980 RFC 768 UDP Ports + checksum over IP; nothing else
2 1981 RFC 793 TCP Reliable byte stream, three-way handshake
3 1984 RFC 896 Nagle Coalesce small segments
4 1988 Jacobson Slow start, congestion avoidance (now RFC 5681)
5 1989 RFC 1122 Delayed ACK, keepalive rules
6 1990 RFC 1191 PMTUD Find the path MTU with DF + ICMP
7 1996 RFC 2018 SACK Retransmit only the holes
8 2007 RFC 4987 SYN flood defences, SYN cookies
9 2011 RFC 6298 Initial RTO 1 s
10 2013 RFC 6928 Initial window 10 segments
11 2014 RFC 7323, RFC 7413 Window scaling; TCP Fast Open
12 2016 BBR (ACM Queue) Model-based congestion control
13 2017 RFC 8085 How to use UDP responsibly
14 2021 RFC 9000, RFC 9002 QUIC
15 2022 RFC 9293 TCP consolidated, STD 7
16 2023 RFC 9438 CUBIC on the Standards TrackThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a packet sequence, real scenarios, how products behave, and the fix.
TCP: a reliable, ordered byte stream Must-know
In plain words: TCP turns a lossy packet network into a pipe of bytes between two programs: what goes in one end comes out the other end, complete and in the same order, or the pipe breaks with an error.
Common misunderstanding: "TCP sends my messages." TCP sends bytes. It may split one write() into several segments and merge several writes into one segment. Your protocol needs its own message boundaries.
Definition: RFC 9293 defines TCP as a connection-oriented transport that numbers every byte with a 32-bit sequence number, acknowledges cumulatively, retransmits unacknowledged data, controls the sender's rate with a receive window (flow control) and a congestion window (congestion control), and identifies a connection by its 4-tuple (source IP, source port, destination IP, destination port).
App A (client) TCP A TCP B App B (server)
1 write("GET /a") seq 1..6 ->
2 write("GET /b") (Nagle may hold it until 1..6 is ACKed)
3 <- ack 7
4 seq 7..12 ->
5 read() returns "GET /aGET /b" (12 bytes, one read)
6 -- two writes became one read: the protocol must frame its messagesReal scenario: PostgreSQL, MySQL and Redis clients keep long-lived TCP connections and frame messages with length prefixes (PostgreSQL wire protocol) or delimiters (RESP); HTTP/1.1 frames with Content-Length or chunked encoding; a home-made "JSON over TCP" service that assumed one read per message corrupts data the first time a response exceeds one segment.
What each stack gives you:
| Stack | How you get a TCP stream | Default that matters |
|---|---|---|
| Linux kernel | socket(AF_INET, SOCK_STREAM, 0) | CUBIC congestion control on most distributions (kernel config) |
Go net | net.Dial("tcp", ...), net.Listen("tcp", ...) | TCP_NODELAY on; keepalive 15 s |
| PHP streams | stream_socket_client('tcp://...') | No read timeout unless stream_set_timeout or default_socket_timeout |
| Laravel HTTP client (Guzzle, libcurl) | Http::get() | 10 s connect, 30 s total; libcurl sets TCP_NODELAY by default |
| NGINX | listen 80; in http or stream | Proxies TCP at L4 with the stream module |
Fix / how to use it: frame every message (Go framing, PHP LineClient); keep connections open and reuse them; bound every phase with a deadline (Mechanics).
UDP: connectionless datagrams Must-know
In plain words: UDP sends one self-contained packet to an address and port. No setup, no delivery promise, no order, no pacing.
Common misunderstanding: "UDP packets can't be corrupted because there's a checksum." The UDP checksum is 16 bits, catches random bit errors, and in IPv4 is even optional; RFC 768 says "An all zero transmitted checksum value means that the transmitter generated no checksum". It does not protect against an attacker. Use DTLS, QUIC or an application MAC when integrity matters.
Definition: RFC 768 defines an 8-byte header: source port, destination port, length, checksum. Linux's udp(7) calls it "a connectionless, unreliable datagram packet service. Packets may be reordered or duplicated before they arrive." Each send is one datagram; each recv returns one datagram (truncated if your buffer is too small).
Client (port 53000) Resolver (port 53)
1 datagram: query A example.com id=0x1a2b ->
2 (lost on Wi-Fi)
3 timer 1 s expires; resend same query ->
4 <- datagram: answer id=0x1a2b
5 -- the application did the reliability: timer, resend, match by idReal scenario: DNS (stub resolvers retry after a timeout); RTP for voice and video in WebRTC, Zoom-style calls and SIP phones; game state updates at 20 to 60 per second; StatsD metrics; DHCP; NTP; syslog over UDP; WireGuard and many VPNs; QUIC itself.
What each stack gives you:
| Stack | UDP API | Notes |
|---|---|---|
| Linux | SOCK_DGRAM; connect() sets a default peer | A "connected" UDP socket receives ECONNREFUSED after an ICMP port unreachable |
Go net | net.ListenPacket("udp", ...), net.DialUDP | ReadFrom returns one datagram and the sender |
| PHP | stream_socket_client('udp://...'), stream_socket_server(..., STREAM_SERVER_BIND) | fwrite never waits for an answer |
| NGINX | listen 53 udp; in stream | The docs' example: listen 127.0.0.1:53 udp reuseport; |
| AWS NLB | UDP and TCP_UDP listeners | Flow tracked by 5-tuple; idle timers apply |
Fix / how to use it: keep datagrams under the path MTU (1200 bytes is safe for IPv6 and QUIC); add an ID to every message; design for loss, duplicates and reordering (Application-level reliability); pace your sending rate.
Three-way handshake and the initial sequence number Must-know
In plain words: before any data moves, the client says "I want to talk, my numbering starts at x" (SYN), the server says "fine, mine starts at y, and I got your x" (SYN-ACK), and the client says "got your y" (ACK).
Common misunderstanding: "The handshake is free on a fast network." It costs one full round trip on every new connection, before TLS adds its own. Across regions (80 ms RTT) a new HTTPS connection costs about 240 ms before the first response byte. Connection reuse is the cheapest latency fix in most systems.
Definition: the client sends a segment with the SYN flag and its initial sequence number (ISN) plus options (MSS, window scale, SACK permitted, timestamps); the server answers SYN+ACK with its own ISN and ack = ISN_client + 1; the client answers ACK with ack = ISN_server + 1. RFC 9293 section 3.4.1 requires ISNs to be unpredictable so off-path attackers cannot inject segments. The SYN and FIN flags each consume one sequence number.
t (ms) Client (SYN-SENT) Server (LISTEN)
1 0 SYN seq=1000 MSS=1460 WS=7 SACK ->
2 40 SYN-RECEIVED; SYN-ACK seq=5000 ack=1001
3 80 <- SYN-ACK; client is ESTABLISHED
4 80 ACK ack=5001 + first request bytes ->
5 120 ESTABLISHED; request read
6 160 <- first response byte (2 RTTs for a new connection, 1 RTT on a reused one)Real scenario: a PHP-FPM worker that opens a new connection to Redis on every request adds one RTT to every page; a Go service calling another region without keep-alive pays 2 RTTs per call; a mobile app on a 300 ms satellite link waits over a second for TCP + TLS + first byte.
What each product does:
| Product | Connection reuse | How to see the handshake cost |
|---|---|---|
Go net/http | Transport pools keep-alive connections by default | httptrace.ClientTrace ConnectStart/ConnectDone |
| Laravel HTTP client / Guzzle | Reuse is bounded by the PHP process lifetime; in PHP-FPM assume a new connection per web request | Guzzle on_stats request option (transfer statistics) |
| phpredis | persistent => true reuses the TCP connection across requests in a worker | CLIENT LIST age field |
| PgBouncer / RDS Proxy | Keeps server connections warm for many short clients | Connection Pooling |
| NGINX upstream | keepalive in an upstream block | $upstream_connect_time |
Fix / how to use it: reuse connections (pools, persistent connections, HTTP keep-alive); put TLS termination close to users (CDN); use TFO or QUIC 0-RTT for idempotent first requests where supported.
Sequence numbers, acknowledgements, retransmission and RTO Must-know
In plain words: every byte has a number; the receiver tells the sender the next number it expects; anything not acknowledged in time is sent again.
Common misunderstanding: "If a packet is lost, TCP resends it immediately." TCP only knows a segment is lost by waiting: either three duplicate ACKs arrive (fast retransmit, about one RTT) or the retransmission timer fires (RTO, at least 200 ms on Linux, 1 s initial per RFC 6298), and each further timeout doubles. A single lost SYN costs a full second.
Definition: ACKs are cumulative: ack = N means "I have every byte before N". The sender keeps a smoothed RTT (SRTT) and its variance (RTTVAR) and sets RTO <- SRTT + max(G, K*RTTVAR) with K = 4 (RFC 6298); before any measurement "set RTO <- 1 second". On each timeout the RTO doubles (exponential backoff). SACK (RFC 2018) lets the receiver list blocks it has beyond a hole, so the sender resends only the hole. Linux's tcp_retries2 (default 15) bounds an established connection to "a hypothetical timeout of 924.6 seconds" of unanswered retransmissions; tcp_syn_retries (default 6) gives up a connection attempt after about 131 seconds.
Sender Receiver
1 seg seq=1 (1448 B) -> ack 1449
2 seg seq=1449 (1448 B) -> lost
3 seg seq=2897 -> dup ack 1449, SACK 2897-4345
4 seg seq=4345 -> dup ack 1449, SACK 2897-5793
5 seg seq=5793 -> dup ack 1449 (third duplicate)
6 fast retransmit seq=1449 -> ack 7241 (everything up to 7241)
7 -- without SACK and enough later segments, the sender would wait for RTO insteadReal scenario: p99 latency spikes of exactly 200 ms or 1 s on an otherwise fast service are retransmission timeouts; a request/response protocol with tiny messages rarely has three later segments to trigger fast retransmit, so it waits for the RTO; a connect timeout of 1 s on a lossy link fails right when the first SYN retransmission would have succeeded.
What each stack does:
| Stack | Minimum RTO | Connect attempt gives up after | Established connection gives up after |
|---|---|---|---|
| RFC 6298 | 1 s (SHOULD round up) | n/a | n/a |
| Linux | tcp_rto_min_us default 200000 (200 ms) | tcp_syn_retries=6, about 131 s | tcp_retries2=15, at least 924.6 s; TCP_USER_TIMEOUT overrides |
| Go | Kernel's | Dialer.Timeout (none by default) | Read/write deadlines |
| PostgreSQL server | Kernel's | n/a | tcp_user_timeout setting |
| QUIC (RFC 9002) | Probe timeout computed per path | Handshake timeout of the stack | Idle timeout transport parameter |
Fix / how to use it: set a dial timeout of at least 1 to 3 s (so one SYN retransmission fits); use TCP_USER_TIMEOUT or application deadlines so a dead peer is detected in seconds, not 15 minutes; watch retransmission counters (nstat -az TcpRetransSegs, ss -ti retrans:).
Flow control: the receive window and window scaling Important
In plain words: the receiver tells the sender how much free buffer it has; the sender never has more unacknowledged bytes in flight than that.
Common misunderstanding: "Flow control and congestion control are the same thing." Flow control protects the receiver (its buffer, advertised as rwnd). Congestion control protects the network (estimated as cwnd). The sender uses the smaller of the two.
Definition: every segment carries a 16-bit window field, so without options a window is at most 65535 bytes. RFC 7323 window scaling, negotiated only in SYN and SYN-ACK, shifts it left by up to 14 bits (about 1 GiB). Throughput is bounded by window / RTT; to fill a path you need a window at least the bandwidth-delay product (BDP). Linux autotunes buffers between tcp_rmem min/default/max (default 4K / 131072 / up to 32 MB depending on RAM); setting SO_RCVBUF explicitly "disables automatic tuning".
Path: 1 Gbit/s, 80 ms RTT -> BDP = 125 MB/s x 0.08 s = 10 MB in flight
1 Window 64 KiB (no scaling): max 64 KiB / 0.08 s = 0.8 MB/s (6.5 Mbit/s)
2 Window 4 MiB: max 4 MiB / 0.08 s = 52 MB/s (420 Mbit/s)
3 Window 10 MB (autotuned): can fill the path
4 Receiver app stops reading: rwnd shrinks to 0 -> sender stops, sends zero-window probesReal scenario: cross-region backups that run at a few MB/s on a 10 Gbit/s link because a middlebox stripped the window-scale option; a slow consumer (a PHP worker blocked on the database) makes the producer's write() block once both buffers fill, which is TCP backpressure working as designed; Kafka and object-storage transfers across continents tuned with larger tcp_rmem max.
What each product does:
| Product | Knob | Default |
|---|---|---|
| Linux | net.ipv4.tcp_rmem, net.ipv4.tcp_wmem, tcp_window_scaling | Autotuning on; scaling on (1) |
| Go | TCPConn.SetReadBuffer/SetWriteBuffer | Unset: kernel autotuning (setting them disables it) |
| NGINX | listen ... rcvbuf= sndbuf= | Kernel defaults |
| AWS NLB / NAT | Pass the window through | Middleboxes that strip options break scaling |
Fix / how to use it: leave autotuning on and raise tcp_rmem/tcp_wmem max on long fat paths; do not hard-code SO_RCVBUF unless you measured; treat a blocking write as backpressure, with a write deadline.
Congestion control: slow start, congestion avoidance, fast retransmit, CUBIC and BBR Must-know
In plain words: the sender starts carefully, speeds up while ACKs come back, and slows down when it sees signs of a traffic jam (loss, or rising delay).
Common misunderstanding: "A new connection gets the full bandwidth immediately." It starts with an initial window of about 10 segments (around 14 KB) and doubles per RTT. A 1 MB response over a fresh connection at 80 ms RTT needs several round trips just to ramp up, which is one more reason to reuse connections. Also, Linux by default resets the window after an idle period (tcp_slow_start_after_idle=1), so an idle keep-alive connection starts slow again.
Definition (RFC 5681): the congestion window cwnd limits unacknowledged data. In slow start (cwnd < ssthresh) cwnd grows by up to one SMSS per ACK, roughly doubling per RTT; the initial window IW is 2 to 4 segments in RFC 5681 and 10 in RFC 6928. In congestion avoidance (cwnd > ssthresh) cwnd grows by about one SMSS per RTT. Fast retransmit "uses the arrival of 3 duplicate ACKs" as a loss signal and resends without waiting for the RTO; fast recovery (NewReno, RFC 6582) then halves cwnd instead of collapsing it. An RTO collapses cwnd to one segment. CUBIC (RFC 9438) grows cwnd as a cubic function of time since the last loss, flat near the previous maximum W_max and fast away from it, and reduces by beta_cubic = 0.7 instead of 0.5; RFC 9438 explains C = 0.4 "seems to provide a good balance". BBR ("Bottleneck Bandwidth and Round-trip propagation time", IETF draft-ietf-ccwg-bbr-07) builds "an explicit model of the network path" from delivery rate and minimum RTT and paces at the estimated bottleneck bandwidth instead of filling buffers until loss.
RTT cwnd (segments) phase event
1 0 10 slow start new connection, IW=10
2 1 20 slow start
3 2 40 slow start
4 3 64 reaches ssthresh=64 switch to avoidance
5 4 65 congestion avoidance +1 per RTT
6 25 86 fast retransmit 3 dup ACKs
7 25 60 fast recovery (CUBIC 0.7) W_max=86
8 31 85 CUBIC concave growth plateau near W_max
9 32 1 RTO fired slow start againReal scenario: large downloads from a CDN edge with BBR keep throughput on lossy mobile paths where CUBIC backs off; a bulk transfer next to latency-sensitive traffic fills a router buffer and adds hundreds of milliseconds (Bufferbloat); a service whose keep-alive connections sit idle for seconds sees the first response after idle slower than later ones because of slow start after idle.
What each product does:
| Product | Default | How to change |
|---|---|---|
| Linux | Set by kernel config; CUBIC on mainstream distributions; reno always available | sysctl net.ipv4.tcp_congestion_control=bbr (module tcp_bbr); per socket TCP_CONGESTION |
| Linux idle restart | tcp_slow_start_after_idle=1 | Set 0 on servers with long-lived keep-alive connections |
| QUIC stacks | NewReno-like per RFC 9002; many ship CUBIC or BBR | Library option (in user space, no kernel change) |
| Windows, macOS | Their own defaults (not covered here) | OS-specific |
| Cloud LBs (AWS NLB) | Pass-through: endpoints' algorithms apply | Change on the hosts |
Fix / how to use it: reuse connections so they stay warm; consider BBR (with fq qdisc for pacing) on servers sending bulk data over long or lossy paths, after measuring; set tcp_slow_start_after_idle=0 on API servers with long-lived connections; never "fix" throughput by opening dozens of parallel connections to the same host without understanding that each one competes for the same bottleneck.
Nagle's algorithm, delayed ACK and TCP_NODELAY Important
In plain words: Nagle holds back a small write while an earlier small write is still unacknowledged; delayed ACK holds back an ACK hoping to piggy-back it on data. Together they can make two polite parties wait for each other.
Common misunderstanding: "TCP_NODELAY makes TCP faster in general." It removes one source of delay for small, latency-sensitive writes. For bulk streams that write in tiny pieces it increases packet count; the right fix there is to buffer in the application and write once.
Definition: RFC 9293 section 3.7.4: an endpoint "SHOULD implement the Nagle algorithm to coalesce" small segments and must let the application disable it per connection. Delayed ACK (RFC 9293 section 3.8.6.3): "the delay MUST be less than 0.5 seconds", and an ACK "SHOULD be generated for at least every second full-sized segment". TCP_NODELAY disables Nagle. Linux also offers TCP_CORK (hold partial frames, 200 ms ceiling) and TCP_QUICKACK (temporary immediate ACKs).
Client (Nagle on) Server (delayed ACK on)
1 write(header, 40 B) -> sent
2 write(body, 200 B) -> held: 40 B still unACKed
3 waits for more data before ACKing ... (delayed-ACK timer)
4 timer fires (tens of ms) -> ACK
5 body sent now
6 -- write-write-read pattern: the request is complete only after the timer; fix = one write, or TCP_NODELAYReal scenario: an RPC client that writes a header and a body in two calls sees a steady extra ~40 ms per call on Linux; Redis pipelines and PostgreSQL drivers set TCP_NODELAY because they are request/response protocols; SSH interactive sessions disable Nagle for keystrokes.
What each product does:
| Product | Nagle default | Where to change |
|---|---|---|
Go net | Off: "The default is true (no delay)" for SetNoDelay | TCPConn.SetNoDelay(false) to re-enable |
| libcurl (Laravel HTTP client) | Off: CURLOPT_TCP_NODELAY "is set by default" since 7.50.2 | withOptions(['curl' => [CURLOPT_TCP_NODELAY => 0]]) |
| PHP streams | On (kernel default) | Context option socket.tcp_nodelay => true |
NGINX stream (L4 proxy) | Off: tcp_nodelay on is the default (since 1.9.4), for client and proxied connections | tcp_nodelay off; |
| Linux C sockets | On | setsockopt(TCP_NODELAY) |
Fix / how to use it: build the whole message and write it once (the Go framing code does one Write per frame); disable Nagle on request/response protocols; keep Nagle (or use TCP_CORK) for bulk writers that cannot batch.
Head-of-line blocking Must-know
In plain words: because TCP delivers bytes strictly in order, one lost segment holds back every byte behind it, even bytes that belong to a completely different request.
Common misunderstanding: "HTTP/2 solved head-of-line blocking." HTTP/2 removed it at the HTTP layer (many requests share one connection without waiting for each other's responses), but all of those streams still ride one TCP byte stream. One lost packet now stalls every stream on that connection. On lossy networks HTTP/2 over one connection can be worse than HTTP/1.1 over six.
Definition: head-of-line (HOL) blocking is the delay that an item at the front of an ordered queue imposes on items behind it. In TCP the kernel holds out-of-order segments in the receive buffer and makes them readable only once the gap is filled, after a fast retransmit (about one RTT) or an RTO. RFC 9000: "One of the benefits of QUIC is avoidance of head-of-line blocking across multiple streams. When a packet loss occurs, only streams with data in that packet are blocked".
t (ms) Packets on one TCP connection What the application can read
1 0 #1 stream A A part 1
2 1 #2 stream A (lost)
3 2 #3 stream B (complete response) nothing: waiting for #2
4 3 #4 stream C (complete response) nothing
5 80 #2 retransmitted (fast retransmit) A part 2, then B, then C, all at once
6 -- B and C were complete at t=3 but delivered at t=80; with an RTO it would be 200+ msReal scenario: a gRPC channel multiplexing hundreds of calls on one HTTP/2 connection shows correlated latency spikes across unrelated calls when the link drops packets; a WebSocket carrying both chat messages and a large file upload delays chat behind the file; a mobile app on a train sees every image on a page stall together.
What each option gives you:
| Transport | HOL scope | Notes |
|---|---|---|
| HTTP/1.1, several TCP connections | Per connection | Browsers open about six per origin to work around it |
| HTTP/2 over one TCP connection | Whole connection | HTTP-level HOL gone, TCP-level HOL remains |
| HTTP/3 over QUIC | Per stream | Lost packet blocks only streams with data in it |
| UDP with RTP | None at transport level | Jitter buffer decides to wait or skip |
| Kafka, PostgreSQL, Redis connections | Whole connection, and request order is part of the protocol | Pipelined requests also wait on each other by design |
Fix / how to use it: keep latency-sensitive and bulk traffic on separate connections; prefer HTTP/3 for browser and mobile traffic over lossy networks; for real-time media use UDP with a jitter buffer; ordering per key rather than global ordering is the same idea in messaging (Ordering & Partitioning).
Teardown, FIN, RST, TIME_WAIT and connection churn Must-know
In plain words: closing politely takes four segments, and the side that closes first must remember the connection for a while so a late packet from the old connection cannot be mistaken for a new one.
Common misunderstanding: "Thousands of TIME_WAIT sockets mean a leak, so enable tcp_tw_recycle." TIME_WAIT is normal and cheap per socket. The real problem is new connections per request: each one consumes an ephemeral port toward the same destination for the TIME_WAIT period. tcp_tw_recycle broke clients behind NAT and was removed after Linux 4.11 (tcp(7): "Linux 2.4 to Linux 4.11"). The fix is connection reuse.
Definition: FIN means "I have no more data"; each direction closes separately (half-close), so a peer in CLOSE-WAIT can still send. RST aborts immediately and discards unsent data; it is what you get when you talk to a port with no listener, when the peer's application crashed, or when a middlebox has forgotten your flow. RFC 9293 takes the MSL as 2 minutes and keeps TIME-WAIT for 2 MSL; Linux uses a fixed, shorter 60 seconds. tcp_fin_timeout (default 60 s) is about FIN-WAIT-2 for orphaned sockets, not TIME_WAIT. A 4-tuple in TIME_WAIT cannot be reused toward the same peer unless tcp_tw_reuse (default 2, "enable for loopback traffic only") allows it with timestamps.
Client (active closer) Server
1 close() -> FIN -> CLOSE-WAIT (app must call close)
2 FIN-WAIT-1 <- ACK
3 FIN-WAIT-2 app calls close() -> FIN
4 <- FIN; send ACK -> enter TIME-WAIT LAST-ACK -> CLOSED on ACK
5 ... 60 s on Linux ...
6 CLOSED; the 4-tuple (192.0.2.7:41234 -> 192.0.2.9:6379) may be reused
7 -- 1000 new connections/s to one Redis = about 60000 TIME_WAIT sockets > 28232 portsReal scenario: a PHP-FPM fleet opening a new connection per request to Redis or MySQL exhausts ephemeral ports (ip_local_port_range default 32768 to 60999, 28232 ports) and starts failing with EADDRNOTAVAIL / "Cannot assign requested address"; a server that never calls close() accumulates CLOSE_WAIT sockets until it runs out of file descriptors; an L7 proxy that closes upstream connections first collects the TIME_WAIT on the proxy host.
What each product does:
| Product | Behaviour | Knob |
|---|---|---|
| Linux | TIME_WAIT 60 s; tcp_max_tw_buckets caps the count | tcp_tw_reuse (0/1/2, default 2), ip_local_port_range |
Go net/http | Keep-alive pool reuses connections | Transport.MaxIdleConnsPerHost (default 2 is low for busy clients) |
Go net | SetLinger(0) sends RST on close (no TIME_WAIT, data may be lost) | Use only for abortive close |
| phpredis / PDO | persistent connections survive across requests in one worker | persistent => true, PDO::ATTR_PERSISTENT |
| HAProxy, NGINX, Envoy | Pool upstream connections | NGINX keepalive, HAProxy http-reuse |
Fix / how to use it: reuse connections (pools, keep-alive, persistent connections); let the server close idle connections so TIME_WAIT lands on the server side where the 4-tuples are spread over many clients; always close() what you accept (CLOSE_WAIT is your bug, not the kernel's); widen ip_local_port_range and spread across more destination IPs only as a second step.
Keepalive and idle timeouts Must-know
In plain words: TCP keepalive sends an empty probe on an idle connection to check that the other side (and everything in between) still remembers it.
Common misunderstanding: "HTTP keep-alive and TCP keepalive are the same." HTTP keep-alive (persistent connections) means "do not close after this response". TCP keepalive is a kernel probe on an idle socket. You usually need both: reuse the connection, and probe it often enough that NAT and load balancers do not forget it.
Definition: RFC 9293: keepalives "MUST default to off" and the idle interval "MUST default to no less than two hours". Linux defaults: tcp_keepalive_time 7200 s, tcp_keepalive_intvl 75 s, tcp_keepalive_probes 9 ("aborted after ~11 minutes of retries"). Applications override per socket (TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT). Go's net.Dialer and net.ListenConfig enable keepalive by default: "If zero, keep-alive probes are sent with a default value (currently 15 seconds)"; KeepAliveConfig sets idle, interval and count separately (defaults 15 s, 15 s, 9).
t (s) Client AWS NAT Gateway Server
1 0 last request/response flow entry refreshed
2 0-350 idle (no keepalive)
3 350 flow entry expires
4 400 write(next query) -> no entry: replies RST
5 400 ECONNRESET "connection reset by peer"
6 -- with keepalive idle=60 s the probe at t=60 refreshes the entry and nothing breaksReal scenario: the first database query after a quiet night fails with "server closed the connection unexpectedly"; a Laravel queue worker's Redis connection dies behind a NAT; a WebSocket from a browser silently stops receiving because a corporate proxy dropped it, and nobody notices until the user reloads.
Idle timers you must stay under:
| Middlebox or server | Idle timeout (documented) | What happens |
|---|---|---|
| AWS NAT Gateway | 350 s | Returns RST to the instance (not FIN) |
| AWS Network Load Balancer, TCP | 350 s default, configurable 60 to 6000 s | Connection closed |
| AWS NLB, TLS listener | 350 s, cannot be modified | Connection closed |
| HAProxy | timeout client / server / tunnel (no default; set them) | Session closed; option tcpka sends keepalives on both sides |
| NGINX stream | proxy_timeout default 10 min, "between two successive read or write operations" | Connection closed |
| PostgreSQL server | tcp_keepalives_idle 0 = OS default | Use 60 s to detect dead clients behind NAT |
| Laravel Redis config | read_timeout 60 in the docs example | Client gives up reading |
Fix / how to use it: set keepalive idle below the smallest idle timer on the path (60 s is a safe choice under 350 s); add application heartbeats on WebSockets (Reverb/Pusher protocol pings) because a TCP keepalive does not cross a proxy that terminates TCP; reconnect and retry idempotent operations on ECONNRESET.
MSS, MTU and path MTU discovery Important
In plain words: every link has a largest packet it can carry (MTU); TCP picks a segment size (MSS) that fits, and path MTU discovery finds the smallest MTU on the whole path.
Common misunderstanding: "If ping works, the network works." A small ping fits any MTU. When a tunnel or VPN lowers the path MTU and a firewall drops the ICMP "Fragmentation Needed" messages, small requests work and large ones hang forever: the MTU black hole.
Definition: Ethernet MTU is 1500 bytes; IPv4 + TCP headers without options take 40, so MSS is 1460 (1448 with the timestamp option). Each side advertises its MSS in the SYN. RFC 1191 PMTUD sends with the Don't Fragment bit and lowers the size when routers return ICMP; RFC 8899 (datagram PLPMTUD) and Linux tcp_mtu_probing (0 off, 1 "enabled when an ICMP black hole detected", 2 always) probe without relying on ICMP. IPv6 routers never fragment and the minimum IPv6 MTU is 1280. QUIC requires at least 1200-byte datagrams.
Client (MTU 1500) VPN tunnel (MTU 1420) Firewall Server
1 SYN MSS=1460 -> SYN-ACK MSS=1460
2 small GET (300 B) -> fits 200 OK small: works
3 POST 1460-byte segments, DF set -> too big: ICMP Frag Needed -> (dropped by firewall)
4 no ACK, RTO, retransmit same size, again ... connection hangs
5 -- fix: MSS clamping at the tunnel, allow ICMP type 3 code 4, or tcp_mtu_probing=1Real scenario: uploads over a site-to-site VPN hang while browsing works; Docker or Kubernetes overlay networks (VXLAN adds 50 bytes) with an MTU left at 1500 (Docker networking); UDP game packets above 1472 bytes fragmented and lost more often.
What each product does:
| Product | Behaviour | Knob |
|---|---|---|
| Linux TCP | PMTUD with DF; probing optional | tcp_mtu_probing, tcp_base_mss |
| Linux UDP | App decides; IP_MTU_DISCOVER controls DF | Keep datagrams small |
| QUIC (RFC 9000) | Datagrams at least 1200 bytes; PMTU probing in the stack | Library setting |
| Routers / VPN gateways | MSS clamping rewrites the SYN's MSS option | e.g. iptables ... TCPMSS --clamp-mss-to-pmtu |
| Kubernetes CNIs | Set pod MTU below the node MTU for overlays | CNI config |
Fix / how to use it: never block all ICMP; clamp MSS on tunnels; keep UDP datagrams at 1200 bytes or less (the Go udprel package enforces MaxPayload = 1200); test with large payloads, not ping.
SYN floods, the backlog, somaxconn and SYN cookies Important
In plain words: a listening server keeps a small record for every half-open handshake; an attacker sends a flood of SYNs from fake addresses to fill those records. SYN cookies let the server keep no record at all until the handshake completes.
Common misunderstanding: "The backlog argument is the number of clients my server can handle." It is the length of the queue of completed handshakes waiting for accept(). If your accept loop is slow, it fills and new connections are dropped, regardless of how many connections you can serve once accepted.
Definition: Linux keeps two queues per listener: the SYN queue (half-open, SYN-RECEIVED, bounded by tcp_max_syn_backlog) and the accept queue (completed, bounded by min(backlog, somaxconn); listen(2): "Since Linux 5.4, the default in this file is 4096; in earlier kernels, the default value is 128"). When the accept queue is full, Linux drops the final ACK or the SYN and the client retransmits after 1 s, 2 s, 4 s. RFC 4987: SYN cookies "encode most of the state ... into the sequence number transmitted on the SYN-ACK"; Linux tcp_syncookies=1 (default) sends them only when the SYN queue overflows, and the docs warn: "It MUST NOT be used to help highly loaded servers to stand against legal connection rate."
Attacker (spoofed sources) Server listener
1 SYN from 198.51.100.1 -> SYN queue +1, SYN-ACK to a host that never answers
2 SYN from 198.51.100.2 -> SYN queue +1
3 ... 100000 SYN/s ... SYN queue full
4 legit client SYN -> tcp_syncookies=1: SYN-ACK with cookie in seq, no state kept
5 legit client ACK (ack = cookie+1) -> cookie valid -> connection created, accept queue
6 -- without cookies step 4 is dropped and the client waits 1 s, 3 s, 7 s ... to retryReal scenario: a deploy restarts all Go pods at once and the reconnect storm overflows the accept queue of a database proxy; a volumetric SYN flood against an origin with no DDoS edge; an overloaded PHP-FPM socket where NGINX logs connect() to unix:/run/php/php-fpm.sock failed (11: Resource temporarily unavailable) because the backlog is full.
What each product does:
| Product | Backlog source | Notes |
|---|---|---|
| Linux | listen(fd, backlog) capped by net.core.somaxconn (4096 since 5.4) | nstat ListenOverflows, ListenDrops |
Go net.Listen | Go reads somaxconn and passes it as the backlog | Tune the sysctl, not Go |
PHP stream_socket_server | Context option socket.backlog | "Used to limit the number of outstanding connections in the socket's listen queue" |
| NGINX | listen ... backlog= (default 511 on Linux, -1 on FreeBSD and macOS) | Also reuseport to spread across workers |
| Cloudflare, AWS Shield, GCP Cloud Armor | Absorb SYN floods at the edge | DDoS Protection |
Fix / how to use it: keep tcp_syncookies=1; raise somaxconn and the application's backlog for bursty listeners; accept fast and hand work to goroutines or workers; stagger restarts and add jitter to reconnects (Timeouts, Retries & Jitter); terminate public traffic behind a DDoS-absorbing edge.
TCP Fast Open Good to know
In plain words: after a first normal connection, the server gives the client a cookie; next time the client can put data in the SYN itself and save one round trip.
Common misunderstanding: "TFO is a free 1-RTT win, turn it on everywhere." RFC 7413 warns that "the data in the SYN could be replayed to an application in some rare circumstances. Applications should not use TFO unless they can tolerate this issue". Many middleboxes also drop SYNs carrying data, so clients must fall back.
Definition: RFC 7413 (Experimental): the client requests a cookie in its first SYN; later SYNs carry the cookie plus data, which the server may pass to the application before the handshake completes. Linux: tcp_fastopen bit 0x1 client (on by default), 0x2 server (off by default); the client "must use sendmsg() or sendto() with the MSG_FASTOPEN flag".
Client Server
1 SYN + TFO cookie request -> (first visit)
2 <- SYN-ACK + cookie C
3 ... normal connection, later closed ...
4 SYN + cookie C + "GET /" -> cookie valid: deliver "GET /" to app now
5 <- SYN-ACK + response bytes (saved one RTT)
6 -- a duplicated SYN at step 4 could deliver "GET /" twice: only idempotent requestsReal scenario: DNS over TCP and HTTP GETs to a known server; mostly superseded in practice by TLS 1.3 resumption and QUIC 0-RTT, which solve the same problem with encryption included.
| Feature | Saves | Replay risk | Where |
|---|---|---|---|
| TCP Fast Open | 1 RTT (TCP) | Yes | Linux, macOS; often blocked by middleboxes |
| TLS 1.3 0-RTT | 1 RTT (TLS) | Yes | Servers must restrict to safe requests |
| QUIC 0-RTT | Transport + TLS to 1 RTT total | Yes (RFC 9000: "no protection against replay attacks") | HTTP/3 stacks |
Fix / how to use it: only for idempotent first requests, with fallback; prefer connection reuse, which saves the RTT with no replay risk at all.
Multicast and broadcast Good to know
In plain words: broadcast sends one datagram to every host on the local network; multicast sends one datagram to every host that joined a group address. Both exist only for UDP, because TCP is one-to-one.
Common misunderstanding: "We can use multicast to fan out events to our services in the cloud." The public Internet does not route multicast, and most cloud VPC networks do not carry it by default, so cloud designs use a broker or a pub/sub service instead (Messaging Fundamentals).
Definition: IPv4 broadcast (255.255.255.255 or the subnet broadcast) needs SO_BROADCAST and does not cross routers. Multicast uses group addresses (IPv4 224.0.0.0/4, IPv6 ff00::/8); receivers join with IP_ADD_MEMBERSHIP and IGMP/MLD tells switches and routers who listens. RFC 8085 adds guidelines for multicast senders, which also need congestion control.
Sender Switch (IGMP snooping) Receivers
1 join? no R1, R2 join 239.1.2.3
2 send to 239.1.2.3:5000 -> copies to ports of R1 and R2 R1, R2 receive; R3 does not
3 -- one send, N deliveries, no ACKs, no retransmission: a lost copy is lost for that receiverReal scenario: DHCP discovery (broadcast); mDNS/Bonjour (multicast 224.0.0.251); market-data feeds in exchanges and trading firms; IPTV inside carrier networks; cluster discovery on bare metal.
| Mechanism | Scope | Needs | Typical use |
|---|---|---|---|
| Broadcast | Local subnet | SO_BROADCAST | DHCP, ARP (L2) |
| Multicast | Group members, routed if enabled | IGMP/MLD, multicast routing | mDNS, market data, IPTV |
| Anycast | Nearest of many hosts sharing an IP | BGP | DNS resolvers, CDN edges (IP, DNS, GeoDNS) |
| Broker pub/sub | Anywhere | Kafka, RabbitMQ, Redis, SNS | Cloud event fan-out |
Fix / how to use it: use broadcast and multicast inside networks you control; use a broker in the cloud.
Application-level reliability over UDP Important
In plain words: when you choose UDP but some messages must arrive, you rebuild the parts of TCP you need: an ID per message, an acknowledgement, a timer and a resend, and duplicate detection on the receiver.
Common misunderstanding: "I'll add ACKs and retries and I'm done." Then you also need congestion control (RFC 8085: UDP "has no inherent congestion control mechanisms" and applications must provide it), a bound on retries, deduplication with expiry, and a decision on ordering. Most teams that need all of that should use QUIC or TCP.
Definition: a minimal reliable-datagram protocol: sender assigns a unique message ID, sends, starts a timer; receiver acks every datagram it receives (including duplicates, because the duplicate means the previous ack was lost) and processes each ID once; sender retransmits on timeout with exponential backoff and gives up after N attempts, reporting "unknown outcome" rather than "failed".
Sender Receiver
1 D id=7 "cpu=0.71" -> (lost)
2 timer 50 ms fires; D id=7 -> handle(7); A id=7 -> (ack lost)
3 timer 100 ms fires; D id=7 -> seen 7: skip handle; A id=7 ->
4 <- A id=7; done
5 -- handled once, acked twice; after 5 tries without ack: ErrNoAck = "maybe delivered"Real scenario: game servers send state unreliably and inputs reliably on the same UDP socket; IoT devices send telemetry with acks over CoAP or a custom protocol; DNS resolvers retry and match by ID; RTP leaves reliability out entirely and uses sequence numbers only to reorder and detect loss (RFC 3550: "RTP itself does not provide any mechanism to ensure timely delivery").
| Need | TCP gives it | UDP app must add | QUIC gives it |
|---|---|---|---|
| Detect loss | ACKs, SACK | IDs + acks or sequence gaps | Yes |
| Recover loss | Retransmission | Resend or forward error correction | Yes (per stream) |
| Order | Whole stream | Sequence numbers + buffer | Per stream |
| Deduplicate | Yes | Seen-ID set with TTL | Yes |
| Pace | Congestion control | Your own (RFC 8085) | Yes |
| Encrypt | TLS on top | DTLS or app crypto | Built in |
Fix / how to use it: see the Go udprel package (acks, backoff, dedup, ErrNoAck); keep it for small, independent messages; reach for QUIC when you need streams.
QUIC: a reliable, encrypted, multiplexed transport over UDP Must-know
In plain words: QUIC moves TCP's job (reliability, ordering, congestion control) plus TLS into a user-space library on top of UDP, with many independent streams per connection and a connection identity that survives an IP change.
Common misunderstanding: "QUIC is UDP, so it is unreliable." The wire is UDP; the service is reliable, ordered streams with mandatory congestion control and TLS 1.3. RFC 9000: "QUIC is a connection-oriented protocol that creates a stateful interaction between a client and server."
Definition: RFC 9000 (May 2021). Streams are independent ordered byte streams, so loss blocks only the affected stream. The handshake integrates TLS 1.3, so a new connection reaches application data after 1 RTT, and resumption can send 0-RTT data ("0-RTT provides no protection against replay attacks"). Packets carry connection IDs; "The use of a connection ID allows connections to survive changes to endpoint addresses (IP address and port), such as those caused by an endpoint migrating to a new network", after path validation. Loss detection and congestion control are in RFC 9002. HTTP/3 maps HTTP onto QUIC (HTTP evolution).
Phone (Wi-Fi 192.0.2.10) Server
1 Initial (ClientHello, conn ID S1) ->
2 <- Initial + Handshake (ServerHello, cert, conn ID C1)
3 Handshake Finished + 1-RTT stream 0 "GET /feed" -> (1 RTT to first request)
4 <- stream 0 response; stream 4 image; stream 8 image
5 walks outside: new IP 198.51.100.20 (5G), same conn ID S1 ->
6 <- PATH_CHALLENGE; PATH_RESPONSE -> connection continues, no new handshake
7 -- with TCP, step 5 kills the 4-tuple: reconnect, TCP + TLS handshakes againReal scenario: browsers and CDNs (Cloudflare, Google, Fastly) serve HTTP/3 to users on lossy mobile links; mobile apps keep a session alive across Wi-Fi to cellular handover; DNS over QUIC; internal service traffic usually stays on TCP, where loss is rare and tooling is mature.
| Aspect | TCP + TLS 1.3 | QUIC |
|---|---|---|
| Where implemented | Kernel (TCP) + library (TLS) | User space library over UDP |
| New connection to first request | 2 RTT (TCP 1 + TLS 1) | 1 RTT |
| Resumption | 1 RTT with TLS 0-RTT data after TCP handshake | 0-RTT |
| Head-of-line blocking | Whole connection | Per stream |
| IP or port change | Connection breaks | Connection migration |
| Middlebox visibility | Headers visible, often manipulated | Encrypted; only UDP and a few bits visible |
| Cost | Kernel offloads (TSO, GRO) mature | More CPU per byte; UDP GSO/GRO help |
| Blocked by | Rarely | Some enterprise networks block UDP 443; clients fall back to TCP |
Fix / how to use it: enable HTTP/3 at the edge (CDN or NGINX/Envoy with QUIC support) and keep TCP fallback; do not hand-roll QUIC; at an L4 load balancer, route QUIC by connection ID or accept that migrated connections may land elsewhere.
Bufferbloat Good to know
In plain words: oversized buffers in routers and modems let a single bulk upload queue seconds of data, and every other packet, including your game, call or DNS query, waits behind it.
Common misunderstanding: "Bigger buffers prevent loss, so they are good." Loss-based congestion control keeps increasing its window until a buffer overflows; a bigger buffer only means a longer queue before that happens. The BBR paper: "When bottleneck buffers are large, loss-based congestion control keeps them full, causing bufferbloat."
Definition: bufferbloat is excess latency caused by persistently full queues at the bottleneck. Fixes are on two sides: active queue management at the bottleneck (CoDel, RFC 8289; fq_codel in Linux) and senders that do not fill queues (BBR, pacing).
t (s) Home uplink 10 Mbit/s, modem buffer 2 MB
1 0 ping 20 ms
2 1 cloud backup starts (CUBIC grows cwnd until the buffer overflows)
3 3 buffer full: 2 MB / 1.25 MB/s = 1.6 s of queue; ping 1600 ms; video call freezes
4 4 fq_codel on the router: queue held near 5 ms target; ping 25 ms againReal scenario: video calls that freeze whenever someone uploads; latency SLOs violated only at peak because queues build; cloud VMs with large NIC queues adding tail latency.
| Fix | Where | Effect |
|---|---|---|
fq_codel / CoDel (RFC 8289) | Bottleneck router, Linux qdisc | Keeps queue delay near a target |
BBR + fq pacing | Sender | Sends near bottleneck rate, small queue |
| Separate traffic classes | Network QoS | Real-time traffic skips the bulk queue |
| Limit in-flight data | App (TCP_NOTSENT_LOWAT) | Less data stuck in socket buffers |
Fix / how to use it: measure latency under load, not idle latency; enable fq_codel where you control the bottleneck; consider BBR on bulk senders.
L4 load balancers and NAT Important
In plain words: an L4 load balancer or a NAT keeps a table entry per flow (the 5-tuple) and forwards packets without understanding the application; when the entry expires or the table fills, the flow is gone.
Common misunderstanding: "An L4 load balancer balances requests." It balances connections (or UDP flows). One long-lived HTTP/2 or gRPC connection pins all its requests to one backend, so a few clients with long connections can overload one pod while others idle (Load Balancing).
Definition: an L4 load balancer (AWS NLB, GCP Network LB, HAProxy mode tcp, NGINX stream, Envoy tcp_proxy, Kubernetes Services via kube-proxy) chooses a backend per new flow and then forwards every packet of that flow; it may proxy (two TCP connections) or pass packets through (one connection, client IP preserved). NAT (NAT, PAT & Port Forwarding) rewrites addresses and ports and keeps a mapping per flow with an idle timer; UDP mappings usually expire far sooner than TCP ones because UDP has no FIN. The PROXY protocol carries the original client address through proxies: it "provides a convenient way to safely transport connection information such as a client's address across multiple layers of NAT or TCP proxies".
Client NLB (L4, flow table) Pod A Pod B
1 SYN 203.0.113.5:50001 -> new flow -> hash -> Pod A
2 1000 gRPC calls on that one connection -> all on Pod A idle
3 Pod A drains for deploy: connection stays until client reconnects
4 350 s idle -> NLB forgets flow; next packet -> RST to client
5 -- fixes: max connection age on the server, client-side balancing, keepalive < 350 sReal scenario: gRPC clients behind an NLB that never rebalance after a scale-out; UDP game sessions that drop when the NAT mapping expires between packets; source NAT on a Kubernetes node running out of ports to one external API; client IPs lost behind a TCP proxy without the PROXY protocol.
| Product | Layer and mode | Idle / keepalive knob | Client IP |
|---|---|---|---|
| AWS NLB | L4 pass-through, TCP/UDP/TLS | TCP idle 350 s default (60 to 6000) | Preserved (or PROXY protocol v2) |
| AWS NAT Gateway | Source NAT | 350 s idle, then RST | Replaced by NAT IP |
| HAProxy | mode tcp proxy | timeout client/server/tunnel, option tcpka | send-proxy PROXY protocol |
| NGINX | stream module proxy | proxy_timeout, so_keepalive on listen | proxy_protocol on |
| Envoy | tcp_proxy filter | idle_timeout (counted in stats as idle_timeout) | PROXY protocol listener filter |
| Kubernetes Service | kube-proxy iptables/IPVS, or eBPF CNI | conntrack timeouts | SNAT unless externalTrafficPolicy: Local |
Fix / how to use it: keepalive below every idle timer on the path; set a maximum connection age on servers (for example grpc-go's keepalive.ServerParameters.MaxConnectionAge) so long-lived connections rebalance; use the PROXY protocol when backends need the client IP; send UDP keepalives (for example every 15 to 25 s) to keep NAT mappings open.
Mechanics
Headers
| TCP header field | Bits | Meaning |
|---|---|---|
| Source / destination port | 16 + 16 | With the IPs, the 4-tuple that identifies the connection |
| Sequence number | 32 | Number of the first data byte in this segment (ISN on SYN) |
| Acknowledgement number | 32 | Next byte expected from the peer (valid when ACK is set) |
| Data offset | 4 | Header length in 32-bit words (20 to 60 bytes) |
| Flags | 8 | CWR, ECE, URG, ACK, PSH, RST, SYN, FIN |
| Window | 16 | Receive window, scaled by the negotiated shift |
| Checksum | 16 | Over header, data and a pseudo-header (mandatory) |
| Options | variable | MSS, window scale, SACK-permitted, SACK, timestamps, TFO cookie |
| UDP header field | Bits | Meaning |
|---|---|---|
| Source port | 16 | Optional in IPv4 (0 if unused) |
| Destination port | 16 | Demultiplexes to the receiving socket |
| Length | 16 | Header plus data, in bytes |
| Checksum | 16 | Optional in IPv4 (all zero = none), mandatory in IPv6 |
Timers and their defaults
| Timer | Standard | Linux default | Override |
|---|---|---|---|
| Initial RTO | RFC 6298: 1 s | 1 s | n/a |
| Minimum RTO | RFC 6298: 1 s | 200 ms (tcp_rto_min_us) | Route rto_min, TCP_RTO_MIN_US |
| SYN retries | n/a | 6, about 131 s total | tcp_syn_retries, app dial timeout |
| Established retries | RFC 1122 at least 100 s | tcp_retries2=15, at least 924.6 s | TCP_USER_TIMEOUT |
| Delayed ACK | RFC 9293: under 0.5 s | Tens of ms (minimum 40 ms) | TCP_QUICKACK |
| TIME_WAIT | 2 MSL = 4 min | 60 s fixed | Reuse connections; tcp_tw_reuse |
| FIN_WAIT_2 (orphaned) | n/a | tcp_fin_timeout=60 | sysctl |
| Keepalive idle / interval / probes | Off; at least 2 h | 7200 s / 75 s / 9 | Socket options, Go KeepAliveConfig |
| Go dialer keepalive | n/a | 15 s idle, 15 s interval, 9 probes | KeepAliveConfig |
Linux sysctls that matter
| sysctl | Default | Change when |
|---|---|---|
net.core.somaxconn | 4096 (since 5.4) | Bursty listeners; raise with the app's backlog |
net.ipv4.tcp_max_syn_backlog | 128+ scaled with memory | SYN queue overflows under load |
net.ipv4.tcp_syncookies | 1 | Keep 1 |
net.ipv4.ip_local_port_range | 32768 60999 | Many outbound connections to one destination |
net.ipv4.tcp_tw_reuse | 2 (loopback only) | Set 1 on clients that must open many outbound connections, after fixing reuse |
net.ipv4.tcp_fin_timeout | 60 | Many orphaned FIN_WAIT_2 sockets |
net.ipv4.tcp_keepalive_time / _intvl / _probes | 7200 / 75 / 9 | Prefer per-socket settings |
net.ipv4.tcp_rmem / tcp_wmem | 4K, 131072, 131072 to 32MB by RAM / 4K, 16K, 64K to 4MB by RAM | Long fat pipes: raise max |
net.ipv4.tcp_congestion_control | Kernel config (often cubic) | bbr for bulk senders after measuring |
net.ipv4.tcp_slow_start_after_idle | 1 | 0 for long-lived API connections |
net.ipv4.tcp_mtu_probing | 0 | 1 where ICMP black holes exist |
net.ipv4.tcp_fastopen | 1 (client only) | 3 to enable server side too |
Bandwidth-delay product arithmetic
BDP (bytes) = bandwidth (bytes/s) x RTT (s). Maximum throughput of one connection is min(rwnd, cwnd) / RTT. Examples: 100 Mbit/s and 30 ms gives 375 KB; 10 Gbit/s and 100 ms gives 125 MB, beyond the default tcp_rmem max, so one connection cannot fill that path without tuning. Ephemeral ports: (60999 - 32768 + 1) / 60 s = about 470 new connections per second to one destination IP and port before TIME_WAIT blocks reuse (without tcp_tw_reuse).
Error messages you will actually see
| errno / message | Meaning | Typical cause | Retry? |
|---|---|---|---|
ECONNREFUSED "connection refused" | Peer answered SYN with RST | Nothing listens on the port; backend down | Yes, after backoff; the request never ran |
ETIMEDOUT "connection timed out" / Go "i/o timeout" on dial | No SYN-ACK in time | Firewall drop, black hole, overloaded accept queue | Yes, the request never ran |
ECONNRESET "connection reset by peer" | RST on an established connection | Peer crashed, NAT/LB forgot the flow, SO_LINGER 0 | Only idempotent requests; outcome unknown |
EPIPE "broken pipe" | Write after the peer closed | Server closed an idle connection | Reconnect; outcome of previous call known |
Go os.ErrDeadlineExceeded "i/o timeout" on read | Your deadline passed | Slow peer or lost packets | Outcome unknown; idempotent only |
EADDRNOTAVAIL "cannot assign requested address" | No free local port for that 4-tuple | Ephemeral port exhaustion, TIME_WAIT | Fix reuse; retrying makes it worse |
EMFILE "too many open files" | Out of file descriptors | Leak, CLOSE_WAIT pile-up, ulimit -n low | No; fix the limit or the leak |
EHOSTUNREACH / ENETUNREACH | ICMP unreachable or no route | Routing, security group | After the fix |
UDP ECONNREFUSED on a connected socket | ICMP port unreachable for an earlier datagram | Collector not listening | Optional; UDP stays connectionless |
| PostgreSQL "server closed the connection unexpectedly" | TCP closed or reset under the driver | Idle timeout, failover, idle_session_timeout | Reconnect; retry idempotent work |
PHP stream_socket_client(): Unable to connect ... (Connection refused) | Same as ECONNREFUSED | Same | Same |
Go
The Go module (academy/tcp-udp, go 1.24) uses only the standard library. go vet ./... and go test -race ./... pass.
Before
A client that works on a laptop: no dial timeout, no deadlines, a new connection per call, and one Read treated as one message.
// Package before shows a TCP client that works on a laptop and hurts in
// production: no dial timeout, no deadlines, one new connection per call,
// and a "protocol" that assumes one Read returns one whole message.
package before
import (
"net"
)
// Fetch opens a new TCP connection for every request.
//
// Problems (on purpose):
// - net.Dial has no timeout: a SYN to a black-holed address waits for the
// kernel's SYN retries (Linux tcp_syn_retries=6, about 131 s).
// - No read deadline: a peer that accepts and never answers blocks forever.
// - One connection per call: three-way handshake every time, and the
// active closer (this client) keeps a TIME_WAIT entry for 2*MSL.
// - A single Read is treated as a whole message; TCP is a byte stream, so
// a reply can arrive split across reads or merged with the next one.
func Fetch(addr string, request []byte) ([]byte, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
defer conn.Close()
if _, err := conn.Write(request); err != nil {
return nil, err
}
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
return nil, err
}
return buf[:n], nil
}After
Framing. A 4-byte length prefix restores message boundaries on a byte stream, caps the frame size, and writes header and body in one Write. The test feeds two frames through a reader that returns one byte at a time.
// Package framing adds message boundaries to a TCP byte stream with a
// 4-byte big-endian length prefix.
package framing
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
// MaxFrame bounds memory use per message; a peer cannot make us allocate
// gigabytes by sending a huge length.
const MaxFrame = 1 << 20
// ErrFrameTooLarge is returned when a length prefix exceeds MaxFrame.
var ErrFrameTooLarge = errors.New("framing: frame too large")
// Write sends one frame. It uses a single Write call for header and body so
// that, with TCP_NODELAY on, the frame leaves as one segment when it fits.
func Write(w io.Writer, payload []byte) error {
if len(payload) > MaxFrame {
return ErrFrameTooLarge
}
buf := make([]byte, 4+len(payload))
binary.BigEndian.PutUint32(buf, uint32(len(payload)))
copy(buf[4:], payload)
_, err := w.Write(buf)
return err
}
// Read returns exactly one frame, however the bytes were split by TCP.
func Read(r io.Reader) ([]byte, error) {
var hdr [4]byte
if _, err := io.ReadFull(r, hdr[:]); err != nil {
return nil, err
}
n := binary.BigEndian.Uint32(hdr[:])
if n > MaxFrame {
return nil, fmt.Errorf("%w: %d bytes", ErrFrameTooLarge, n)
}
payload := make([]byte, n)
if _, err := io.ReadFull(r, payload); err != nil {
return nil, err
}
return payload, nil
}package framing
import (
"bytes"
"errors"
"io"
"testing"
)
// oneByteReader returns at most one byte per Read, like a slow network that
// splits a message into many segments.
type oneByteReader struct{ r io.Reader }
func (o oneByteReader) Read(p []byte) (int, error) {
if len(p) > 1 {
p = p[:1]
}
return o.r.Read(p)
}
func TestFramesSurviveSplitAndMergedReads(t *testing.T) {
var stream bytes.Buffer
for _, m := range []string{"hello", "", "world"} {
if err := Write(&stream, []byte(m)); err != nil {
t.Fatal(err)
}
}
// Both messages sit in one buffer (merged) and are read one byte at a
// time (split). Framing recovers the original boundaries.
r := oneByteReader{&stream}
for _, want := range []string{"hello", "", "world"} {
got, err := Read(r)
if err != nil {
t.Fatal(err)
}
if string(got) != want {
t.Fatalf("got %q, want %q", got, want)
}
}
if _, err := Read(r); !errors.Is(err, io.EOF) {
t.Fatalf("want io.EOF at end of stream, got %v", err)
}
}
func TestRejectsHugeLength(t *testing.T) {
stream := bytes.NewReader([]byte{0xff, 0xff, 0xff, 0xff})
if _, err := Read(stream); !errors.Is(err, ErrFrameTooLarge) {
t.Fatalf("want ErrFrameTooLarge, got %v", err)
}
}Server. net.ListenConfig with KeepAliveConfig (60 s idle, below the 350 s AWS NAT/NLB timers), the read deadline as an idle timeout, a write deadline, and graceful shutdown that wakes blocked reads with context.AfterFunc.
// Package tcpserver is a small framed TCP server with keepalive, an idle
// timeout per connection and graceful shutdown.
package tcpserver
import (
"context"
"errors"
"net"
"sync"
"sync/atomic"
"time"
"academy/tcp-udp/framing"
)
// Handler turns one request frame into one response frame.
type Handler func(ctx context.Context, req []byte) []byte
// Server serves framed requests. Zero values are replaced by safe defaults.
type Server struct {
Handler Handler
IdleTimeout time.Duration // close a connection with no request for this long
KeepAlive net.KeepAliveConfig
accepted atomic.Int64
wg sync.WaitGroup
}
// Accepted reports how many TCP connections were accepted (for tests and labs).
func (s *Server) Accepted() int64 { return s.accepted.Load() }
// Listen opens a TCP listener whose accepted sockets get the keepalive config.
// The accept queue length comes from the kernel (Linux: min(backlog, somaxconn)).
func (s *Server) Listen(ctx context.Context, addr string) (net.Listener, error) {
ka := s.KeepAlive
if !ka.Enable {
// Probe well below the 350 s idle timeout of AWS NLB and NAT Gateway.
ka = net.KeepAliveConfig{Enable: true, Idle: 60 * time.Second, Interval: 15 * time.Second, Count: 4}
}
lc := net.ListenConfig{KeepAliveConfig: ka}
return lc.Listen(ctx, "tcp", addr)
}
// Serve accepts until ctx is cancelled, then waits for open connections.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
idle := s.IdleTimeout
if idle <= 0 {
idle = 2 * time.Minute
}
go func() {
<-ctx.Done()
ln.Close() // unblocks Accept
}()
for {
conn, err := ln.Accept()
if err != nil {
if ctx.Err() != nil {
s.wg.Wait()
return nil
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
continue
}
return err
}
s.accepted.Add(1)
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.serveConn(ctx, conn, idle)
}()
}
}
func (s *Server) serveConn(ctx context.Context, conn net.Conn, idle time.Duration) {
defer conn.Close()
stop := context.AfterFunc(ctx, func() {
// Shutdown: wake a blocked Read now instead of waiting for idle.
conn.SetReadDeadline(time.Now())
})
defer stop()
for {
// The read deadline is the idle timeout: no request in time -> close.
if err := conn.SetReadDeadline(time.Now().Add(idle)); err != nil {
return
}
req, err := framing.Read(conn)
if err != nil {
return // io.EOF (peer closed), os.ErrDeadlineExceeded (idle), reset...
}
resp := s.Handler(ctx, req)
if err := conn.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
return
}
if err := framing.Write(conn, resp); err != nil {
return
}
}
}Client. A net.Dialer with a dial timeout and keepalive, explicit SetNoDelay(true), one reused connection, the context deadline applied as the socket deadline, and no automatic retry, because after an I/O error the request may or may not have run.
// Package tcpclient is a framed TCP client that keeps one connection open,
// bounds every step with a deadline, and tells the caller what failed.
package tcpclient
import (
"context"
"errors"
"net"
"sync"
"time"
"academy/tcp-udp/framing"
)
// Client is safe for concurrent use; calls are serialised on one connection.
type Client struct {
Addr string
DialTimeout time.Duration
mu sync.Mutex
conn net.Conn
dial net.Dialer
}
// New returns a client with a dial timeout and keepalive probes.
func New(addr string) *Client {
return &Client{
Addr: addr,
DialTimeout: 2 * time.Second,
dial: net.Dialer{
Timeout: 2 * time.Second, // dial timeout: SYN, SYN-ACK, ACK must finish in time
KeepAliveConfig: net.KeepAliveConfig{
Enable: true,
Idle: 30 * time.Second,
Interval: 10 * time.Second,
Count: 3,
},
},
}
}
// Call sends one request frame and waits for one response frame. The context
// deadline becomes the socket deadline for both the write and the read.
// On any I/O error the connection is discarded; whether to retry is the
// caller's decision, because the server may have processed the request.
func (c *Client) Call(ctx context.Context, req []byte) ([]byte, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
conn, err := c.dial.DialContext(ctx, "tcp", c.Addr)
if err != nil {
return nil, err // ECONNREFUSED, i/o timeout, no route to host
}
if tc, ok := conn.(*net.TCPConn); ok {
// Go already defaults to true; we set it to make the intent explicit.
_ = tc.SetNoDelay(true)
}
c.conn = conn
}
deadline, ok := ctx.Deadline()
if !ok {
deadline = time.Now().Add(5 * time.Second) // never wait forever
}
conn := c.conn
if err := conn.SetDeadline(deadline); err != nil {
c.closeLocked()
return nil, err
}
// Cancelling ctx before the deadline also interrupts blocked I/O.
stop := context.AfterFunc(ctx, func() { conn.SetDeadline(time.Now()) })
defer stop()
if err := framing.Write(conn, req); err != nil {
c.closeLocked()
return nil, err
}
resp, err := framing.Read(conn)
if err != nil {
c.closeLocked()
if ctx.Err() != nil {
return nil, errors.Join(ctx.Err(), err)
}
return nil, err
}
return resp, nil
}
// Close closes the pooled connection, if any.
func (c *Client) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.closeLocked()
}
func (c *Client) closeLocked() error {
if c.conn == nil {
return nil
}
err := c.conn.Close()
c.conn = nil
return err
}The tests prove four behaviours: 50 calls use one connection (Accepted() == 1); a slow server is cut off by the read deadline with os.ErrDeadlineExceeded; a server-side idle timeout closes the connection and the client reconnects; dialing a closed port fails with a dial *net.OpError (connection refused).
package tcpclient
import (
"context"
"errors"
"net"
"os"
"testing"
"time"
"academy/tcp-udp/tcpserver"
)
func startServer(t *testing.T, idle time.Duration, h tcpserver.Handler) (*tcpserver.Server, string) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
srv := &tcpserver.Server{Handler: h, IdleTimeout: idle}
ln, err := srv.Listen(ctx, "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() { srv.Serve(ctx, ln); close(done) }()
t.Cleanup(func() { cancel(); <-done })
return srv, ln.Addr().String()
}
func echo(_ context.Context, req []byte) []byte { return append([]byte("echo:"), req...) }
func TestCallsReuseOneConnection(t *testing.T) {
srv, addr := startServer(t, time.Minute, echo)
c := New(addr)
defer c.Close()
for i := 0; i < 50; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
resp, err := c.Call(ctx, []byte("ping"))
cancel()
if err != nil {
t.Fatal(err)
}
if string(resp) != "echo:ping" {
t.Fatalf("got %q", resp)
}
}
if got := srv.Accepted(); got != 1 {
t.Fatalf("50 calls used %d connections, want 1 (no handshake per call)", got)
}
}
func TestReadDeadlineStopsASlowServer(t *testing.T) {
slow := func(ctx context.Context, req []byte) []byte {
select {
case <-time.After(500 * time.Millisecond):
case <-ctx.Done():
}
return req
}
_, addr := startServer(t, time.Minute, slow)
c := New(addr)
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
_, err := c.Call(ctx, []byte("x"))
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Fatalf("want os.ErrDeadlineExceeded, got %v", err)
}
if time.Since(start) > 300*time.Millisecond {
t.Fatalf("deadline not enforced: waited %v", time.Since(start))
}
}
func TestIdleTimeoutThenReconnect(t *testing.T) {
srv, addr := startServer(t, 100*time.Millisecond, echo)
c := New(addr)
defer c.Close()
ctx := context.Background()
if _, err := c.Call(ctx, []byte("a")); err != nil {
t.Fatal(err)
}
time.Sleep(250 * time.Millisecond) // server closes the idle connection (FIN)
// The first call on the dead connection fails (EOF or reset); the client
// does not retry by itself because it cannot know if the request ran.
if _, err := c.Call(ctx, []byte("b")); err == nil {
t.Fatal("expected an error on a connection the server closed")
}
resp, err := c.Call(ctx, []byte("c"))
if err != nil || string(resp) != "echo:c" {
t.Fatalf("reconnect failed: %q %v", resp, err)
}
if got := srv.Accepted(); got != 2 {
t.Fatalf("accepted %d connections, want 2", got)
}
}
func TestDialRefused(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
ln.Close() // nothing listens: the kernel answers SYN with RST
c := New(addr)
_, err = c.Call(context.Background(), []byte("x"))
var op *net.OpError
if !errors.As(err, &op) || op.Op != "dial" {
t.Fatalf("want a dial *net.OpError (connection refused), got %v", err)
}
}UDP with application-level acks. Message IDs, acks for every datagram (including duplicates), retransmission with exponential backoff, receiver-side deduplication, a 1200-byte payload limit and ErrNoAck meaning "maybe delivered".
// Package udprel adds the smallest useful reliability layer on top of UDP:
// message IDs, acknowledgements, retransmission with backoff, and duplicate
// suppression at the receiver. It deliberately has no ordering, no
// congestion control and no flow control; see RFC 8085 before you ship it.
package udprel
import (
"context"
"encoding/binary"
"errors"
"net"
"sync"
"time"
)
const (
kindData byte = 'D'
kindAck byte = 'A'
header = 9 // 1 byte kind + 8 bytes message ID
// MaxPayload keeps a datagram under a 1280-byte IPv6 minimum MTU after
// IP (40) and UDP (8) headers, so it is never fragmented.
MaxPayload = 1200
)
// ErrNoAck means every attempt went unanswered. The message may or may not
// have been delivered: the data or only the ack may have been lost.
var ErrNoAck = errors.New("udprel: no ack after all attempts")
// ErrTooLarge is returned for payloads above MaxPayload.
var ErrTooLarge = errors.New("udprel: payload exceeds MaxPayload")
// Receiver acks every data datagram and hands each message ID to Handle once.
type Receiver struct {
Conn net.PacketConn
Handle func(id uint64, payload []byte)
// Drop, if set, lets tests simulate loss of incoming datagrams.
Drop func(id uint64) bool
mu sync.Mutex
seen map[uint64]time.Time
}
// Serve reads until the connection is closed.
func (r *Receiver) Serve() error {
r.seen = make(map[uint64]time.Time)
buf := make([]byte, 64*1024)
for {
n, from, err := r.Conn.ReadFrom(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
if n < header || buf[0] != kindData {
continue // not ours; UDP gives no guarantee about who sends what
}
id := binary.BigEndian.Uint64(buf[1:header])
if r.Drop != nil && r.Drop(id) {
continue
}
r.mu.Lock()
_, dup := r.seen[id]
if !dup {
r.seen[id] = time.Now() // a real system expires entries (TTL)
}
r.mu.Unlock()
if !dup {
payload := append([]byte(nil), buf[header:n]...)
r.Handle(id, payload)
}
// Ack duplicates too: the sender retransmitted because our ack was lost.
var ack [header]byte
ack[0] = kindAck
binary.BigEndian.PutUint64(ack[1:], id)
if _, err := r.Conn.WriteTo(ack[:], from); err != nil {
return err
}
}
}
// Sender sends one message at a time and waits for its ack.
type Sender struct {
Conn net.Conn // a "connected" UDP socket from net.Dial("udp", ...)
Attempts int // total tries, default 5
Initial time.Duration // first ack timeout, default 50 ms; doubles per try
}
// Send returns nil once the receiver acked id, or ErrNoAck.
func (s *Sender) Send(ctx context.Context, id uint64, payload []byte) error {
if len(payload) > MaxPayload {
return ErrTooLarge
}
attempts, wait := s.Attempts, s.Initial
if attempts <= 0 {
attempts = 5
}
if wait <= 0 {
wait = 50 * time.Millisecond
}
msg := make([]byte, header+len(payload))
msg[0] = kindData
binary.BigEndian.PutUint64(msg[1:header], id)
copy(msg[header:], payload)
buf := make([]byte, 64)
for try := 0; try < attempts; try++ {
if err := ctx.Err(); err != nil {
return err
}
if _, err := s.Conn.Write(msg); err != nil {
return err
}
deadline := time.Now().Add(wait)
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
deadline = d
}
if err := s.Conn.SetReadDeadline(deadline); err != nil {
return err
}
for {
n, err := s.Conn.Read(buf)
if err != nil {
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
break // retransmit
}
return err // e.g. ECONNREFUSED from an ICMP port unreachable
}
if n == header && buf[0] == kindAck && binary.BigEndian.Uint64(buf[1:]) == id {
return nil
}
// A late ack for an older message: ignore and keep waiting.
}
wait *= 2 // exponential backoff, like TCP's RTO backoff
}
return ErrNoAck
}package udprel
import (
"context"
"errors"
"net"
"sync"
"sync/atomic"
"testing"
"time"
)
func start(t *testing.T, drop func(uint64) bool) (*Receiver, *sync.Map, *sync.Map, string) {
t.Helper()
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
var got, count sync.Map
r := &Receiver{Conn: pc, Drop: drop, Handle: func(id uint64, p []byte) {
got.Store(id, string(p))
v, _ := count.LoadOrStore(id, new(atomic.Int64))
v.(*atomic.Int64).Add(1)
}}
done := make(chan struct{})
go func() { r.Serve(); close(done) }()
t.Cleanup(func() { pc.Close(); <-done })
return r, &got, &count, pc.LocalAddr().String()
}
func dial(t *testing.T, addr string) net.Conn {
t.Helper()
c, err := net.Dial("udp", addr)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { c.Close() })
return c
}
func TestRetransmitsUntilAcked(t *testing.T) {
var mu sync.Mutex
seen := map[uint64]int{}
// Lose the first two copies of every message.
drop := func(id uint64) bool {
mu.Lock()
defer mu.Unlock()
seen[id]++
return seen[id] <= 2
}
_, got, count, addr := start(t, drop)
s := &Sender{Conn: dial(t, addr), Initial: 10 * time.Millisecond}
for id := uint64(1); id <= 3; id++ {
if err := s.Send(context.Background(), id, []byte("metric")); err != nil {
t.Fatalf("id %d: %v", id, err)
}
}
for id := uint64(1); id <= 3; id++ {
if v, ok := got.Load(id); !ok || v != "metric" {
t.Fatalf("id %d not delivered", id)
}
if n, _ := count.Load(id); n.(*atomic.Int64).Load() != 1 {
t.Fatalf("id %d handled %d times, want 1", id, n.(*atomic.Int64).Load())
}
}
}
func TestDuplicateIsAckedButHandledOnce(t *testing.T) {
_, _, count, addr := start(t, nil)
s := &Sender{Conn: dial(t, addr), Initial: 20 * time.Millisecond}
// Same ID twice, as if the first ack had been lost on the way back.
for i := 0; i < 2; i++ {
if err := s.Send(context.Background(), 42, []byte("x")); err != nil {
t.Fatal(err)
}
}
if n, _ := count.Load(uint64(42)); n.(*atomic.Int64).Load() != 1 {
t.Fatalf("handled %d times, want 1", n.(*atomic.Int64).Load())
}
}
func TestGivesUpWithErrNoAck(t *testing.T) {
_, _, _, addr := start(t, func(uint64) bool { return true }) // 100% loss
s := &Sender{Conn: dial(t, addr), Attempts: 3, Initial: 5 * time.Millisecond}
start := time.Now()
err := s.Send(context.Background(), 7, []byte("x"))
if !errors.Is(err, ErrNoAck) {
t.Fatalf("want ErrNoAck, got %v", err)
}
// 5 + 10 + 20 ms of waiting.
if el := time.Since(start); el < 30*time.Millisecond {
t.Fatalf("backoff not applied, took %v", el)
}
}
func TestRejectsOversizedPayload(t *testing.T) {
_, _, _, addr := start(t, nil)
s := &Sender{Conn: dial(t, addr)}
if err := s.Send(context.Background(), 1, make([]byte, MaxPayload+1)); !errors.Is(err, ErrTooLarge) {
t.Fatalf("want ErrTooLarge, got %v", err)
}
}The Go angle
| Go API | What it controls | Note |
|---|---|---|
net.Dialer.Timeout / DialContext | Dial timeout for the whole connect (DNS + handshake) | Zero means no timeout beyond the OS's |
net.Dialer.KeepAlive, KeepAliveConfig | TCP keepalive on dialed connections | "If zero, keep-alive probes are sent with a default value (currently 15 seconds)" |
net.ListenConfig.KeepAliveConfig | Keepalive on accepted connections | Same defaults |
SetDeadline / SetReadDeadline / SetWriteDeadline | Absolute time limit for I/O | Error wraps os.ErrDeadlineExceeded; test with errors.Is |
TCPConn.SetNoDelay | Nagle | "The default is true (no delay)" |
TCPConn.SetLinger(0) | Abortive close with RST, no TIME_WAIT | Loses unsent data; rarely right |
TCPConn.SetReadBuffer / SetWriteBuffer | SO_RCVBUF / SO_SNDBUF | Disables kernel autotuning |
net.ListenPacket("udp", ...), ReadFrom, WriteTo | UDP server | One datagram per call |
net.Dial("udp", ...) | Connected UDP socket | Receives ECONNREFUSED from ICMP |
net/http.Transport | HTTP connection pool | MaxIdleConnsPerHost default 2; IdleConnTimeout |
context.AfterFunc | Interrupt blocked I/O on cancellation | Set a past deadline in the callback |
quic-go (third party) | QUIC and HTTP/3 in Go | Not in the standard library |
Laravel
Laravel code runs on top of PHP streams and libcurl. The TCP decisions are the same; the knobs have different names.
Before
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
// Before: works in development, hurts in production.
// - No connectTimeout(): the 10 s default applies to every SYN that is lost.
// - No timeout(): the 30 s default holds a PHP-FPM worker for 30 s per slow call.
// - retry() on a POST without an idempotency key: a timeout after the server
// committed turns into a second reservation.
class InventoryClientBefore
{
public function reserve(int $sku, int $qty): array
{
return Http::retry(3)
->post('https://inventory.internal.example/reservations', [
'sku' => $sku,
'qty' => $qty,
])
->json();
}
}After
HTTP client with explicit TCP behaviour. connectTimeout() bounds the handshake (the default is 10 seconds), timeout() the whole exchange (default 30 seconds; exceeding it throws Illuminate\Http\Client\ConnectionException), and Guzzle's curl request option ("passing an associative array of cURL settings in the curl key of a request") turns on keepalive. retry() retries only connection failures and only with an Idempotency-Key.
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
// After: every TCP-level knob is explicit.
// connectTimeout bounds the three-way handshake (plus TLS on https),
// timeout bounds the whole exchange, and the curl options turn on TCP
// keepalive so an idle pooled connection is probed before a NAT or an
// L4 load balancer (AWS NLB / NAT Gateway: 350 s idle) silently drops it.
class InventoryClient
{
private function client(): PendingRequest
{
return Http::baseUrl('https://inventory.internal.example')
->connectTimeout(1) // seconds; SYN retransmit is ~1 s, so 1-2 s is realistic
->timeout(3) // seconds for the whole response
->withOptions([
'curl' => [
CURLOPT_TCP_KEEPALIVE => 1,
CURLOPT_TCP_KEEPIDLE => 60, // first probe after 60 s idle
CURLOPT_TCP_KEEPINTVL => 15, // then every 15 s
CURLOPT_TCP_NODELAY => 1, // libcurl default since 7.50.2; explicit here
],
]);
}
public function reserve(int $sku, int $qty, ?string $key = null): array
{
$key ??= (string) Str::uuid();
// Retry only failures where the request may not have reached the
// server, and only with an idempotency key so a retry is safe anyway.
return $this->client()
->withHeaders(['Idempotency-Key' => $key])
->retry([100, 300], when: fn (\Throwable $e) => $e instanceof ConnectionException)
->post('/reservations', ['sku' => $sku, 'qty' => $qty])
->throw()
->json();
}
}A raw TCP client with PHP streams. stream_socket_client with a connect timeout, the socket.tcp_nodelay context option ("Setting this option to true will set SOL_TCP,NO_DELAY=1 appropriately, thus disabling the TCP Nagle algorithm"), stream_set_timeout for reads, and a length-prefixed frame like the Go one.
<?php
namespace App\Support;
use RuntimeException;
// A raw TCP client with PHP streams: connect timeout, Nagle off, a read
// timeout per call, and length-prefixed frames (TCP has no message boundaries).
final class LineClient
{
/** @var resource|null */
private $stream = null;
public function __construct(
private readonly string $address = 'tcp://192.0.2.10:7000', // RFC 5737 documentation address
private readonly float $connectTimeout = 1.0,
private readonly int $readTimeoutSeconds = 2,
) {
}
public function call(string $payload): string
{
$stream = $this->connect();
fwrite($stream, pack('N', strlen($payload)).$payload);
$header = $this->readExactly($stream, 4);
$length = unpack('Nlen', $header)['len'];
if ($length > 1048576) {
$this->close();
throw new RuntimeException('frame too large');
}
return $this->readExactly($stream, $length);
}
public function close(): void
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->stream = null;
}
/** @return resource */
private function connect()
{
if (is_resource($this->stream)) {
return $this->stream;
}
$context = stream_context_create([
'socket' => ['tcp_nodelay' => true], // sets TCP_NODELAY, disabling Nagle
]);
$stream = @stream_socket_client(
$this->address,
$errno,
$errstr,
$this->connectTimeout,
STREAM_CLIENT_CONNECT,
$context,
);
if ($stream === false) {
// e.g. errno 111 "Connection refused" (RST) or 110 "Connection timed out"
throw new RuntimeException("connect failed: [$errno] $errstr");
}
stream_set_timeout($stream, $this->readTimeoutSeconds);
return $this->stream = $stream;
}
/** @param resource $stream */
private function readExactly($stream, int $length): string
{
$buffer = '';
while (strlen($buffer) < $length) {
$chunk = fread($stream, $length - strlen($buffer));
$meta = stream_get_meta_data($stream);
if ($meta['timed_out']) {
$this->close();
throw new RuntimeException('read timed out');
}
if ($chunk === false || ($chunk === '' && feof($stream))) {
$this->close();
throw new RuntimeException('connection closed by peer');
}
$buffer .= $chunk;
}
return $buffer;
}
}UDP metrics. A StatsD emitter: one small datagram per sample, sampling, a size cap, and failures that never reach the request path.
<?php
namespace App\Support;
// Fire-and-forget metrics over UDP (StatsD line format). A lost datagram
// costs one sample; a down collector never blocks the request, because a
// UDP "connect" sends nothing and a send does not wait for any answer.
final class StatsdEmitter
{
/** @var resource|false|null */
private $socket = null;
public function __construct(private readonly string $address = 'udp://127.0.0.1:8125')
{
}
public function increment(string $metric, int $by = 1, float $sampleRate = 1.0): void
{
if ($sampleRate < 1.0 && mt_rand() / mt_getrandmax() > $sampleRate) {
return;
}
$line = sprintf('%s:%d|c%s', $metric, $by, $sampleRate < 1.0 ? '|@'.$sampleRate : '');
$this->send($line);
}
public function timing(string $metric, float $milliseconds): void
{
$this->send(sprintf('%s:%.3f|ms', $metric, $milliseconds));
}
private function send(string $line): void
{
// Keep each datagram well under 1200 bytes so it is never fragmented.
if (strlen($line) > 1200) {
return;
}
if ($this->socket === null) {
$this->socket = @stream_socket_client($this->address, $errno, $errstr, 0.1);
}
if ($this->socket === false) {
return; // metrics must never break the request path
}
@fwrite($this->socket, $line);
}
}Connection settings for long-lived TCP connections to Redis (the phpredis options Laravel documents: timeout, read_timeout, persistent, retry_interval, max_retries) and PostgreSQL (PDO::ATTR_TIMEOUT becomes libpq's connect_timeout in pdo_pgsql, default 30 s).
<?php
// Fragment of config/database.php: connection-level timeouts for the
// long-lived TCP connections a Laravel worker keeps to Redis and PostgreSQL.
return [
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'timeout' => 1.0, // connect timeout (seconds)
'read_timeout' => 3.0, // a blocked read fails after 3 s instead of hanging
'persistent' => true, // reuse the TCP connection across requests in a PHP-FPM worker
'retry_interval' => 100, // ms between reconnect attempts
'max_retries' => 2,
],
],
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'laravel'),
'password' => env('DB_PASSWORD', ''),
// Server-side keepalive is set in PostgreSQL itself
// (tcp_keepalives_idle / tcp_keepalives_interval / tcp_user_timeout).
'options' => [
PDO::ATTR_TIMEOUT => 2, // connect timeout in seconds for pdo_pgsql
],
],
],
];Reverb: WebSockets over TCP. Reverb holds one TCP connection per browser tab. The Laravel docs list the operational limits: "each connection is represented by a file", the default stream_select loop "is typically limited to 1,024 open files" (install ext-uv above 1,000 connections), NGINX must forward Upgrade and Connection "Upgrade", and the ephemeral port range matters.
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
// Broadcast through Laravel Reverb: one long-lived WebSocket (over TCP) per
// browser tab. Position updates are small and frequent; the newest one wins,
// so we keep the payload tiny and let a lost connection resync on reconnect.
class ParcelLocationUpdated implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets;
public function __construct(
public int $parcelId,
public float $lat,
public float $lng,
public int $sequence, // client drops anything older than what it has
) {
}
/** @return array<int, PrivateChannel> */
public function broadcastOn(): array
{
return [new PrivateChannel('parcels.'.$this->parcelId)];
}
public function broadcastAs(): string
{
return 'parcel.location';
}
}# .env: where Reverb listens vs where Laravel sends broadcasts
REVERB_SERVER_HOST=0.0.0.0
REVERB_SERVER_PORT=8080
REVERB_HOST=ws.example.com
REVERB_PORT=443# Expected, not run: the limits the Reverb docs tell you to check
ulimit -n # open files per process
cat /proc/sys/net/ipv4/ip_local_port_range # 32768 60999
php artisan reverb:start --host=0.0.0.0 --port=8080The Laravel angle
| Laravel / PHP feature | TCP or UDP behaviour | Default |
|---|---|---|
Http::connectTimeout() | Handshake (and TLS) limit | 10 s |
Http::timeout() | Whole request limit | 30 s |
Http::retry($times, $sleep, $when) | Retries; pass when to limit to connection errors | Off |
Http::withOptions(['curl' => [...]]) | Raw libcurl options (CURLOPT_TCP_KEEPALIVE, CURLOPT_TCP_NODELAY) | libcurl TCP_NODELAY on |
Redis read_timeout, timeout, persistent | Read limit, connect limit, reuse across requests | Docs example read_write_timeout 60 (Predis), read_timeout 60 (phpredis) |
PDO ATTR_TIMEOUT (pgsql) | libpq connect_timeout | 30 s |
stream_socket_client timeout argument | Connect timeout | default_socket_timeout (60 s) |
stream_set_timeout | Read timeout on a stream | None set |
Context socket.tcp_nodelay, socket.backlog, socket.so_reuseport | Nagle off; listen queue; multiple listeners on one port | Kernel defaults |
Reverb + ext-uv | Event loop above 1,024 descriptors | stream_select |
| Octane (Swoole, RoadRunner, FrankenPHP) | Long-lived workers keep connections across requests | n/a |
Solving the classic problems
Ephemeral port exhaustion and TIME_WAIT
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Reuse connections | Pools, HTTP keep-alive, persistent | Removes the cause | Pool sizing and health checks |
| Server closes idle connections | Server-side idle timeout | TIME_WAIT lands on the server, spread over client ports | Clients must handle reconnects |
tcp_tw_reuse=1 on the client | sysctl | Reuses TIME_WAIT 4-tuples safely with timestamps | Only outbound; treats symptoms |
Widen ip_local_port_range | sysctl | More ports | About 2x at best |
| More destination IPs | Several backends or VIPs | Each IP has its own port space | More infrastructure |
Idle connections killed by NAT or an L4 load balancer
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| TCP keepalive under the idle timer | KeepAliveConfig{Idle: 60s}, CURLOPT_TCP_KEEPIDLE, PostgreSQL tcp_keepalives_idle | Kernel does it, no app changes | Does not cross L7 proxies |
| Application heartbeat | WebSocket ping, Redis PING from the pool | Works through proxies | Code and traffic |
| Client-side idle timeout shorter than the middlebox's | Pool IdleConnTimeout 90 s and LB 350 s | Never uses a dead connection | More reconnects |
Retry idempotent work on ECONNRESET | Retry once after reconnect | Hides the rare case | Only idempotent operations |
PostgreSQL server-side keepalives and a query that finds connections idle long enough to be at risk:
-- PostgreSQL: probe idle clients after 60 s, every 15 s, give up after 4 probes;
-- abort a connection whose sent data stays unacknowledged for 30 s.
ALTER SYSTEM SET tcp_keepalives_idle = 60;
ALTER SYSTEM SET tcp_keepalives_interval = 15;
ALTER SYSTEM SET tcp_keepalives_count = 4;
ALTER SYSTEM SET tcp_user_timeout = 30000; -- milliseconds
SELECT pg_reload_conf();
SHOW tcp_keepalives_idle;
-- Client connections idle longer than the 350 s AWS NAT/NLB timer
SELECT pid, usename, client_addr, state, now() - state_change AS idle_for
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND state = 'idle'
AND now() - state_change > interval '350 seconds'
ORDER BY idle_for DESC;40 ms stalls on small requests
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| One write per message | Build the frame, then Write once | Fewest packets and no stall | Needs a buffer |
TCP_NODELAY | Go default; socket.tcp_nodelay in PHP | Small writes leave immediately | More small packets for chatty bulk writers |
TCP_QUICKACK on the receiver | Linux socket option | Removes delayed ACK temporarily | Not sticky; Linux only |
SYN backlog overflow during bursts and deploys
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
Raise somaxconn and the backlog | sysctl plus listen backlog | Absorbs bursts | Queued clients still wait |
| Accept fast | Accept loop does no work | Queue drains quickly | Need bounded workers behind it |
SO_REUSEPORT | Several listeners on one port (NGINX reuseport, PHP so_reuseport) | Spreads accepts across cores | Uneven with long connections |
| Jittered reconnects | Clients add random delay | Avoids thundering herds | Slower recovery |
| SYN cookies + DDoS edge | tcp_syncookies=1; Cloudflare / AWS Shield | Survives spoofed floods | Cookies lose some TCP options |
Throughput far below the link speed
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Check window scaling | ss -ti shows wscale; remove the middlebox that strips it | Fixes the 64 KiB cap | Requires network access |
| Raise buffer maximums | tcp_rmem/tcp_wmem max at least BDP | One connection fills the path | Memory per connection |
BBR + fq | tcp_congestion_control=bbr | Robust on lossy long paths | Fairness with CUBIC flows to evaluate |
| Parallel streams | Several connections (S3 multipart, aria2) | Works with untuned hosts | More state; can be unfair to others |
Silent loss on UDP
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Accept and measure | Sequence numbers to count gaps | Simple | Loss stays |
| Acks and retransmit | udprel | Delivery for important messages | Latency, state, congestion control needed |
| Bigger socket buffers | SO_RCVBUF, net.core.rmem_max | Fewer drops at the receiver under bursts | Memory |
| Move to TCP or a queue | Logs that must not be lost | Reliability solved | Connection management |
Choosing
| Workload | Transport | Extra technique | Reason |
|---|---|---|---|
| Video and voice calls | UDP (RTP/SRTP via WebRTC) | Jitter buffer, FEC, congestion control (in WebRTC), TURN over TCP as fallback | Late audio is useless; retransmission would add delay |
| Real-time multiplayer games | UDP with a custom protocol, or QUIC | Unreliable state, reliable inputs, sequence numbers | Newest position matters; HOL blocking would freeze everyone |
| DNS lookups | UDP | Timeout, retry, TCP fallback on truncation (RFC 7766) | One small question and answer; no handshake |
| Metrics (StatsD) | UDP | Sampling, small datagrams | Losing a sample is fine; never block the request |
| Logs and audit events | TCP (or a queue: Kafka, a log shipper) | Batching, backpressure, TLS | Loss is not acceptable |
| File transfer, backups | TCP (or QUIC) | Large buffers, BBR, resumable chunks | Every byte must arrive |
| Database connections | TCP | Pool, keepalive under NAT timers, TCP_NODELAY | Ordered request/response protocol; protocol state per connection |
| Internal RPC (gRPC, HTTP) | TCP (HTTP/2) | Keep-alive, max connection age, deadlines | Low loss inside a data centre; mature tooling |
| Browser and mobile APIs | QUIC (HTTP/3) with TCP fallback | 0-RTT for safe requests | Lossy last mile, network changes |
| WebSockets (Reverb) | TCP | App-level pings, sticky sessions at the LB | Ordered messages; browser API |
| IoT telemetry on batteries | UDP (CoAP) or MQTT over TCP | Acks for commands only | Small packets, sleeping devices, NAT timers |
| VPN tunnels | UDP (WireGuard, IPsec NAT-T) | Keepalive for NAT | Tunnelling TCP in TCP causes retransmission meltdown |
| Service discovery on a LAN | UDP multicast (mDNS) | TTLs | One-to-many on a local link |
In architecture: from a single process to a distributed system
Transport choices look like plumbing, but they set latency floors, failure modes and capacity limits at every step of a system's growth.
Monolith: one process, one database
A Laravel monolith behind NGINX has three TCP relationships: browser to NGINX (HTTP/1.1 or HTTP/2, maybe HTTP/3 at a CDN), NGINX to PHP-FPM (a Unix socket or TCP with a listen backlog), and PHP to PostgreSQL and Redis. The simplest correct setup: persistent Redis connections, a connect timeout and read timeout on every client, PostgreSQL tcp_keepalives_idle = 60, and HTTP keep-alive enabled at NGINX. The first real incident is usually port exhaustion from per-request connections, or a 30-second default timeout holding every PHP-FPM worker during a dependency outage.
Modular monolith: boundaries without the network
Modules talk by function call, so no transport is involved, and that is the point: no handshake, no partial failure. The transport decision appears only at the edges you choose to externalise: a module that calls a payment provider owns its HTTP client configuration (timeouts, keepalive, idempotency key), and one shared HTTP client factory keeps those settings consistent. Background jobs that fan out to many external APIs need a connection pool per destination, not per job.
Microservices: every arrow is a connection
Each service-to-service arrow is now a long-lived TCP connection pool (HTTP/2 or gRPC), usually through an L4 or L7 load balancer or a sidecar. The concrete flow for "place order" in Go: orders keeps one HTTP/2 connection to inventory through an AWS NLB; a deploy scales inventory from 3 to 6 pods, but the existing connection stays pinned to the old pods until MaxConnectionAge forces a reconnect; keepalive at 60 s keeps the NLB's 350 s flow timer from firing at night; a deadline on every call stops a slow pod from holding goroutines. Internal metrics go over UDP to a local agent so a slow collector cannot slow requests. Service meshes (Service Mesh) change who holds the connections (the sidecar) but not the rules.
Distributed data: replicas, caches, regions
Across regions, RTT dominates: 80 ms RTT makes a new TCP + TLS connection about 240 ms before the first byte, and every synchronous replication round trip costs at least one RTT. Database replication streams (PostgreSQL streaming replication, Kafka replica fetchers, Redis replication) are single long-lived TCP connections whose throughput is limited by window size and congestion control, so cross-region links need larger buffers and sometimes BBR. Cache clusters see connection-count limits before CPU limits (each Redis client is a socket and a file descriptor). Failover changes IPs: TCP connections to the old primary break and must be re-established; QUIC's connection migration helps clients, not database drivers.
Scaling path: 1x, 10x, 100x
At 1x, defaults hurt only through missing timeouts. At 10x, connection churn appears: TIME_WAIT and ephemeral ports, accept-queue overflows during deploys, ulimit -n on Reverb or a proxy, and NAT gateway port limits for egress to one external API; fixes are pooling, somaxconn, ext-uv, more NAT IPs. At 100x, the transport itself shapes the architecture: L4 load balancers with long-lived connections need connection-age limits or client-side balancing, edges terminate TCP and TLS close to users and speak HTTP/3 to mobile clients, bulk transfer moves to tuned paths (BBR, large buffers), and UDP-based protocols (QUIC, WebRTC) carry the latency-critical traffic.
Lab
Runs offline on loopback. Steps 1 to 3 were run on macOS (Apple silicon, Go 1.27); steps 4 to 7 are Linux commands with expected output, not run.
Step 1: tests.
cd docs/snippets/system-design/tcp-udp/go
go vet ./... && go test -race ./...
# ok academy/tcp-udp/framing
# ok academy/tcp-udp/tcpclient
# ok academy/tcp-udp/udprelStep 2: handshake cost on loopback. The program sends 2000 requests with a new connection each, then 2000 over one reused connection.
// Command dialcost compares a new TCP connection per request with one reused
// connection, on loopback, and counts the accepted connections.
//
// go run ./lab/dialcost -n 2000
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"academy/tcp-udp/tcpclient"
"academy/tcp-udp/tcpserver"
)
func main() {
n := flag.Int("n", 2000, "requests per mode")
flag.Parse()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
srv := &tcpserver.Server{Handler: func(_ context.Context, b []byte) []byte { return b }}
ln, err := srv.Listen(ctx, "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
go srv.Serve(ctx, ln)
addr := ln.Addr().String()
run := func(name string, fresh bool) {
before := srv.Accepted()
c := tcpclient.New(addr)
start := time.Now()
for i := 0; i < *n; i++ {
if _, err := c.Call(ctx, []byte("ping")); err != nil {
log.Fatal(err)
}
if fresh {
c.Close() // client closes first -> client socket enters TIME_WAIT
}
}
el := time.Since(start)
c.Close()
fmt.Printf("%-18s requests=%d connections=%d total=%v per_request=%v\n",
name, *n, srv.Accepted()-before, el.Round(time.Millisecond), (el / time.Duration(*n)).Round(time.Microsecond))
}
run("new-conn-per-call", true)
run("reused-conn", false)
} $ go run ./lab/dialcost -n 2000 (measured, macOS loopback)
1 new-conn-per-call requests=2000 connections=2000 total=152ms per_request=76µs
2 reused-conn requests=2000 connections=1 total=32ms per_request=16µs
3 -- loopback RTT is microseconds; across a region multiply the extra handshake by the real RTTStep 3: round trips before the first byte.
// Command rttcost prints how many round trips each transport setup costs
// before the first response byte, and what that means at several RTTs.
// The RTT counts follow RFC 9293 (TCP), RFC 8446 (TLS 1.3), RFC 7413 (TFO)
// and RFC 9000 (QUIC); queueing, DNS and server time are left out.
package main
import (
"fmt"
"time"
)
type setup struct {
name string
rtts float64 // round trips before the first response byte arrives
}
func main() {
setups := []setup{
{"UDP request/response (DNS-style)", 1},
{"TCP, reused connection", 1},
{"TCP new + request", 2},
{"TCP Fast Open (cookie cached)", 1},
{"TCP + TLS 1.3 new", 3},
{"TCP + TLS 1.3 resumed with 0-RTT data", 2},
{"QUIC new (TLS 1.3 inside)", 2},
{"QUIC 0-RTT resumption", 1},
}
rtts := []time.Duration{1 * time.Millisecond, 20 * time.Millisecond, 80 * time.Millisecond, 250 * time.Millisecond}
fmt.Printf("%-40s %5s", "setup", "RTTs")
for _, r := range rtts {
fmt.Printf(" %9s", "@"+r.String())
}
fmt.Println()
for _, s := range setups {
fmt.Printf("%-40s %5.0f", s.name, s.rtts)
for _, r := range rtts {
fmt.Printf(" %9s", time.Duration(s.rtts*float64(r)).String())
}
fmt.Println()
}
} $ go run ./lab/rttcost (measured)
1 setup RTTs @1ms @20ms @80ms @250ms
2 TCP, reused connection 1 1ms 20ms 80ms 250ms
3 TCP new + request 2 2ms 40ms 160ms 500ms
4 TCP + TLS 1.3 new 3 3ms 60ms 240ms 750ms
5 QUIC new (TLS 1.3 inside) 2 2ms 40ms 160ms 500ms
6 QUIC 0-RTT resumption 1 1ms 20ms 80ms 250msStep 4: watch the handshake and teardown (Linux, expected, not run).
sudo tcpdump -ni lo 'tcp and host 127.0.0.1' & # the lab listens on a random loopback port
go run ./lab/dialcost -n 1
# Flags [S], seq 1234567890, win 65495, options [mss 65495,sackOK,TS ...,wscale 7]
# Flags [S.], seq 987654321, ack 1234567891, ...
# Flags [.], ack 1, ...
# ... Flags [F.] ... Flags [.] ... Flags [F.] ... Flags [.]Step 5: count TIME_WAIT after churn (expected, not run).
go run ./lab/dialcost -n 20000 && ss -tan state time-wait | wc -l
# about 20000 right after the run, falling to 0 within 60 s
sysctl net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse net.core.somaxconn
# net.ipv4.ip_local_port_range = 32768 60999
# net.ipv4.tcp_tw_reuse = 2
# net.core.somaxconn = 4096Step 6: UDP loss and app-level acks (expected, not run). Add 30% loss on loopback and run the udprel tests verbosely; every message is still delivered once, with retransmissions visible in the timing.
sudo tc qdisc add dev lo root netem loss 30%
go test -v -run TestRetransmitsUntilAcked ./udprel
# --- PASS: TestRetransmitsUntilAcked (0.2s)
sudo tc qdisc del dev lo rootStep 7: keepalive and retransmission state (expected, not run).
ss -tion state established '( dport = :5432 )'
# ... timer:(keepalive,58sec,0) ... cubic wscale:7,7 rto:204 rtt:1.2/0.6 ... retrans:0/0Common misconceptions
| Belief | Reality |
|---|---|
| TCP guarantees the server processed my request | It guarantees ordered bytes while the connection lives; after a reset the outcome is unknown, so use idempotency |
| UDP is always faster than TCP | UDP adds no handshake and no HOL blocking; a UDP app that rebuilds reliability badly is slower |
One read() returns one message | TCP is a byte stream; frame your messages |
| HTTP/2 removed head-of-line blocking | Only at the HTTP layer; TCP still blocks all streams on loss; HTTP/3 fixes it |
| Many TIME_WAIT sockets are a leak | They are normal; per-request connections are the problem; CLOSE_WAIT is the leak |
tcp_tw_recycle fixes TIME_WAIT | It broke clients behind NAT and is gone since Linux 4.12 |
| TCP keepalive keeps HTTP connections open | It probes idle sockets; HTTP keep-alive is connection reuse; you usually need both |
| The default keepalive protects me from NAT timeouts | Linux waits 2 hours before the first probe; NAT and NLB forget flows after 350 s |
backlog is the maximum number of clients | It is the queue of completed handshakes waiting for accept() |
| SYN cookies are a performance feature | They are a fallback for floods; the kernel docs say they must not be used for legitimate load |
| An L4 load balancer spreads requests evenly | It spreads connections; long-lived connections pin their requests |
| QUIC is unreliable because it uses UDP | QUIC provides reliable, ordered, encrypted streams with congestion control |
| Bigger router buffers are better | They create bufferbloat: seconds of queueing delay under load |
| If ping works, MTU is fine | Small pings fit; large segments hit MTU black holes |
TCP_NODELAY should be on for everything | It helps request/response; batching in the app is the real fix for chatty writers |
Cheat sheet
| Topic | Remember |
|---|---|
| Handshake | SYN, SYN-ACK, ACK: 1 RTT; with TLS 1.3, 2 RTT before the request; reuse connections |
| UDP | 8-byte header, datagrams, no order, no reliability, no congestion control |
| Retransmission | Fast retransmit after 3 dup ACKs; RTO initial 1 s, Linux min 200 ms, doubles on each timeout |
| Flow control | rwnd; window scaling to about 1 GiB; throughput at most window / RTT |
| Congestion control | Slow start doubles, avoidance +1 MSS per RTT; CUBIC 0.7 backoff; BBR models BtlBw and min RTT |
| Nagle + delayed ACK | Write once per message; TCP_NODELAY (Go default on) |
| HOL blocking | TCP blocks all streams on loss; QUIC per stream |
| TIME_WAIT | On the active closer, 60 s on Linux; fix churn with reuse |
| Keepalive | Linux 7200/75/9; Go 15 s; set idle under 350 s for AWS NAT/NLB |
| MSS / MTU | 1460 on Ethernet; clamp on tunnels; UDP payloads at most 1200 |
| Backlog | min(backlog, somaxconn), somaxconn 4096 since Linux 5.4 |
| SYN cookies | tcp_syncookies=1; flood fallback, not capacity |
| TFO / 0-RTT | Save 1 RTT; replayable: idempotent requests only |
| QUIC | UDP + TLS 1.3 + streams; 1 RTT new, 0-RTT resume, migration via connection IDs |
| Errors | Refused = nothing listening (safe to retry); reset/timeout after send = outcome unknown |
| Timeouts in code | Dial timeout, read/write deadlines, overall request deadline, always |
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 in Frankfurt opens a new HTTPS (TLS 1.3 over TCP) connection to a server in Virginia (RTT 90 ms) for every request. How long before the first response byte, ignoring server time, and what is the cheapest fix? Must-know
Answer
Answer: Three round trips: TCP handshake, TLS 1.3 handshake, request/response, so about 270 ms. Reusing the connection brings it to one RTT (90 ms). See Handshake and the lab.
2 — Your Go service reports read: connection reset by peer on the first database query each morning. What is the likely cause and two fixes? Important
Answer
Answer: A NAT or L4 load balancer (for example AWS NAT Gateway or NLB, 350 s idle) forgot the idle flow and answered with RST. Fix with TCP keepalive below the idle timer (Go KeepAliveConfig, PostgreSQL tcp_keepalives_idle = 60) and a pool idle timeout shorter than the middlebox's; retry idempotent queries once after reconnect. See Keepalive.
3 — Why does a gRPC service behind an NLB stay unbalanced after a scale-out? Important
Answer
Answer: An L4 load balancer chooses a backend per connection, and gRPC multiplexes all calls over long-lived HTTP/2 connections, so existing connections stay on the old pods. Set a maximum connection age on the server or use client-side load balancing. See L4 and NAT.
4 — A PHP-FPM fleet begins failing with "Cannot assign requested address" when talking to Redis. Explain the mechanism. Important
Answer
Answer: Each request opens and closes a new connection, the client closes first, so each 4-tuple stays in TIME_WAIT for 60 s. With 28232 ephemeral ports toward one Redis address, more than about 470 new connections per second exhaust them (EADDRNOTAVAIL). Use persistent connections. See TIME_WAIT.
5 — What is the difference between flow control and congestion control? Must-know
Answer
Answer: Flow control protects the receiver's buffer via the advertised receive window; congestion control protects the network via the sender's congestion window. The sender is limited by the smaller of the two. See Flow control and Congestion control.
6 — You see a constant extra ~40 ms on every call of a small RPC protocol on Linux. What do you check first? Good to know
Answer
Answer: A write-write-read pattern with Nagle on and delayed ACK on the peer. Write each message in one call and/or set TCP_NODELAY. See Nagle.
7 — Why is HTTP/3 better than HTTP/2 on a lossy mobile link, and what does it need from the network? Important
Answer
Answer: QUIC streams are independent, so one lost packet blocks only the streams with data in it, and connection migration survives network changes; HTTP/3 also needs one RTT less for a new connection. It needs UDP 443 to be allowed; clients fall back to TCP when it is blocked. See QUIC.
8 — You must send game player positions 30 times per second. TCP or UDP, and why? Must-know
Answer
Answer: UDP. A newer position replaces an older one, so retransmitting a lost one is useless, and TCP's head-of-line blocking would delay every later position behind the lost one. Add sequence numbers to drop stale packets, and send inputs that must arrive with acks. See Choosing.
9 — Your UDP sender with acks returns ErrNoAck. Did the receiver get the message? Important
Answer
Answer: Unknown: either every data datagram or every ack was lost. Treat it as "maybe delivered", and make the receiver deduplicate by message ID so a later resend is safe. See Application-level reliability.
10 — During a deploy, clients see connection times of exactly 1 s and 3 s to a freshly started service. What happened? Good to know
Answer
Answer: The accept queue (min(backlog, somaxconn)) overflowed during the reconnect storm, SYNs or final ACKs were dropped, and clients retransmitted after the 1 s initial RTO and the 2 s backoff. Raise somaxconn and the backlog, accept fast, and jitter reconnects. See SYN floods and backlog.
11 — Large uploads over a site-to-site VPN hang while small requests work. What is it and how do you fix it? Important
Answer
Answer: An MTU black hole: full-size segments with DF set exceed the tunnel MTU and the ICMP "Fragmentation Needed" replies are filtered. Clamp MSS on the tunnel, allow the ICMP type, or enable tcp_mtu_probing=1. See MSS and MTU.
Glossary
| Term | Meaning |
|---|---|
| TCP | Transmission Control Protocol: reliable, ordered, connection-oriented byte stream (RFC 9293) |
| UDP | User Datagram Protocol: connectionless datagrams with ports and a checksum (RFC 768) |
| Datagram | One self-contained UDP message; boundaries are preserved |
| Connectionless | No setup or shared state before sending |
| Sockets | The OS endpoints applications use to send and receive; see Ports, Sockets & Connections |
| 4-tuple / 5-tuple | Source IP, source port, destination IP, destination port (plus protocol); identifies a flow |
| Three-way handshake | SYN, SYN-ACK, ACK: agrees on initial sequence numbers and options |
| SYN | Flag that opens a connection and carries the ISN |
| SYN-ACK | Server's reply to SYN: its own ISN plus acknowledgement |
| ACK | Flag that makes the acknowledgement number valid |
| FIN | Flag meaning "no more data from me"; graceful close per direction |
| RST | Flag that aborts a connection immediately |
| ISN | Initial sequence number, chosen unpredictably |
| Sequence number | 32-bit number of the first data byte in a segment |
| Acknowledgement | Cumulative "next byte I expect" number |
| SACK | Selective acknowledgement of non-contiguous blocks (RFC 2018) |
| Retransmission | Sending unacknowledged data again |
| RTO | Retransmission timeout, computed from SRTT and RTTVAR (RFC 6298) |
| RTT | Round-trip time between the two endpoints |
| Fast retransmit | Resend after three duplicate ACKs without waiting for the RTO |
| Fast recovery | Continue sending with a reduced window after fast retransmit (NewReno, RFC 6582) |
| Flow control | Sender limited by the receiver's advertised window |
| Receive window (rwnd) | Free receive-buffer space the receiver advertises |
| Window scaling | RFC 7323 option shifting the 16-bit window up to 14 bits |
| BDP | Bandwidth-delay product: bytes that must be in flight to fill a path |
| Congestion control | Sender-side limit that protects the network |
| cwnd | Congestion window: sender's estimate of what the path can take |
| ssthresh | Threshold between slow start and congestion avoidance |
| Slow start | Exponential cwnd growth from the initial window |
| Congestion avoidance | Linear cwnd growth, about one MSS per RTT |
| Initial window (IW) | cwnd at connection start; 10 segments per RFC 6928 |
| CUBIC | Loss-based algorithm with cubic growth and 0.7 backoff (RFC 9438) |
| BBR | Model-based congestion control using bottleneck bandwidth and minimum RTT |
| Nagle | Algorithm coalescing small writes while data is unacknowledged (RFC 896) |
| Delayed ACK | Receiver delays ACKs (under 0.5 s) to piggy-back or combine them |
| TCP_NODELAY | Socket option that disables Nagle |
| TCP_CORK | Linux option holding partial frames (200 ms ceiling) |
| TCP_USER_TIMEOUT | Linux option bounding how long sent data may stay unacknowledged |
| Head-of-line blocking | Later data waits behind a lost earlier segment |
| TIME_WAIT | State of the active closer for 2 MSL (Linux 60 s) to absorb late segments |
| CLOSE_WAIT | Peer closed; local application has not called close yet |
| MSL | Maximum segment lifetime; 2 minutes in RFC 9293 |
| Ephemeral port | Local port picked by the kernel for outbound connections (ip_local_port_range) |
| Keepalive | Kernel probes on idle connections |
| Idle timeout | How long a middlebox or server keeps a silent flow |
| MTU | Largest IP packet a link carries (1500 on Ethernet) |
| MSS | Largest TCP payload per segment, advertised in the SYN |
| Path MTU discovery | Finding the smallest MTU on a path (RFC 1191, RFC 8899) |
| MSS clamping | Rewriting the SYN's MSS at a router or tunnel |
| SYN flood | Attack filling the SYN queue with half-open connections |
| SYN cookies | Stateless SYN-ACK encoding state in the sequence number (RFC 4987) |
| Backlog | Accept-queue length requested by listen() |
| somaxconn | Linux cap on the accept queue (net.core.somaxconn) |
| TCP Fast Open | Data in the SYN using a server cookie (RFC 7413) |
| Checksum | 16-bit error-detecting sum in TCP and UDP headers |
| Multicast | One datagram delivered to every member of a group address |
| Broadcast | One datagram delivered to every host on the local subnet |
| RTP | Real-time Transport Protocol for media over UDP (RFC 3550) |
| QUIC | UDP-based, encrypted, multiplexed reliable transport (RFC 9000) |
| 0-RTT | Sending application data in the first flight on resumption; replayable |
| Connection migration | QUIC connection continuing after an address change, via connection IDs |
| Bufferbloat | Latency caused by persistently full oversized buffers |
| CoDel / fq_codel | Active queue management keeping queue delay near a target (RFC 8289) |
| L4 load balancer | Balances TCP/UDP flows by 5-tuple without parsing the application protocol |
| NAT | Network address translation; keeps a mapping per flow with an idle timer |
| PROXY protocol | Header that carries the original client address through proxies |
| Dial timeout | Limit on how long to wait for a connection to be established |
| Read deadline | Absolute time after which a blocked read fails |
References
- RFC 9293: Transmission Control Protocol (TCP), August 2022, STD 7
- RFC 768: User Datagram Protocol, August 1980
- RFC 5681: TCP Congestion Control, September 2009; RFC 6582: NewReno, April 2012
- RFC 6298: Computing TCP's Retransmission Timer, June 2011; RFC 2018: TCP Selective Acknowledgment Options, October 1996
- RFC 7323: TCP Extensions for High Performance, September 2014; RFC 6928: Increasing TCP's Initial Window, April 2013
- RFC 8312: CUBIC, February 2018, obsoleted by RFC 9438: CUBIC for Fast and Long-Distance Networks, August 2023
- Cardwell, Cheng, Gunn, Hassas Yeganeh, Jacobson, "BBR: Congestion-Based Congestion Control", ACM Queue 14, September-October 2016 (abstract read on the Google Research page; queue.acm.org was not reachable from the research machine); draft-ietf-ccwg-bbr-07 (Internet-Draft)
- RFC 896: Congestion Control in IP/TCP Internetworks, January 1984; RFC 1122: Requirements for Internet Hosts, October 1989
- RFC 7413: TCP Fast Open, December 2014; RFC 4987: TCP SYN Flooding Attacks and Common Mitigations, August 2007
- RFC 1191: Path MTU Discovery, November 1990; RFC 8899: Packetization Layer Path MTU Discovery for Datagram Transports, September 2020
- RFC 9000: QUIC and RFC 9002: QUIC Loss Detection and Congestion Control, May 2021
- RFC 8085: UDP Usage Guidelines, March 2017; RFC 3550: RTP, July 2003; RFC 7766: DNS Transport over TCP
- RFC 8289: Controlled Delay Active Queue Management (CoDel), January 2018; bufferbloat.net introduction
- Linux man pages: tcp(7), udp(7), listen(2); kernel docs: IP sysctl, net sysctl
- Go: package net
- PHP: Socket context options, stream_socket_client, stream_set_timeout; php-src pdo_pgsql driver (connect_timeout)
- libcurl: CURLOPT_TCP_NODELAY, CURLOPT_TCP_KEEPALIVE; Guzzle: request options, FAQ: custom cURL options
- Laravel 13: HTTP Client, Reverb, Broadcasting, Redis, Database, Octane;
PendingRequestsource (13.x) - PostgreSQL: Connections and Authentication settings
- AWS: Network Load Balancers, Update the TCP idle timeout for an NLB listener, Troubleshoot NAT gateways
- NGINX: ngx_stream_core_module, ngx_stream_proxy_module; HAProxy 3.2 configuration manual and PROXY protocol; Envoy TCP proxy filter