Unit 4 · Networks · Lesson 2 of 10
TCP and UDP behavior
Step 1: Learn the ideas
- Byte streams and application framing
- Three-way handshake and initial sequence numbers
- Teardown, half-close, RST and TIME-WAIT
- TCP state machine (FIN-WAIT, CLOSE-WAIT, LAST-ACK)
- Sequence numbers, cumulative ACKs and SACK
- Retransmission timeout estimation and backoff
- Fast retransmit and fast recovery
- Keepalives and dead-peer detection
- End-to-end argument and application-level acknowledgments
- UDP semantics and when to choose it
Why it matters
Almost every service you build speaks TCP, directly or under HTTP, gRPC or a database driver. Bugs that look like application problems (truncated messages, requests that hang after a peer crashes, port exhaustion under load, duplicate side effects after a retry) come from misunderstanding what TCP guarantees. UDP matters because DNS, QUIC, media and games use it and must supply whatever reliability they need.
Core ideas
Byte stream, not messages. TCP delivers bytes in order without gaps or duplicates, but it does not preserve the boundaries of your send calls: one send may arrive in several reads and two sends may arrive in one. Applications therefore frame messages with a length prefix, a delimiter, or a self-describing format such as HTTP/1.1 headers plus Content-Length. UDP preserves datagram boundaries but may drop, duplicate or reorder datagrams.
Connection lifecycle. The three-way handshake (SYN, SYN-ACK, ACK) synchronizes initial sequence numbers in both directions and costs one round trip before data flows. Teardown is per direction: each side sends FIN when it has finished sending, so a connection can be half-closed. The side that closes first ends in TIME-WAIT for twice the maximum segment lifetime, so that a lost final ACK can be answered and delayed segments from the old connection cannot be mistaken for a new connection with the same four-tuple. A client that opens and closes many short connections to one server accumulates TIME-WAIT sockets and can run out of ephemeral ports; reusing connections is the usual fix. RST aborts immediately, for example when a segment arrives for a port with no listener.
Reliability machinery. Every byte has a sequence number and the receiver returns cumulative acknowledgments, plus selective acknowledgments (SACK) when both sides support them. The sender retransmits after a timeout computed from a smoothed RTT and its variance, doubling the timeout on repeated losses. Fast retransmit resends a segment after several duplicate ACKs reveal a hole, without waiting for the timer. Out-of-order data is buffered until the gap is filled, so one lost segment holds back everything behind it.
What an ACK means. A TCP acknowledgment says the peer's kernel received the bytes. It does not say the application read them, processed them or stored them durably. If a server crashes after its kernel acknowledged a request, the client saw transport-level success and gets no response. That is why protocols carry application-level acknowledgments (a response, a commit reply) and why retries need idempotency keys: after a timeout the client cannot know whether the request was executed.
UDP. Ports for demultiplexing and a checksum, nothing else: no connection state, retransmission, ordering or congestion control. Protocols built on UDP must add what they need, including congestion control when they send at volume.
client server
SYN seq=x ------>
<------ SYN-ACK seq=y ack=x+1
ACK ack=y+1 ------> (data flows both ways)
FIN ------> (server may still send: half-close)
<------ ACK
<------ FIN
ACK ------> client waits in TIME-WAIT (2 x MSL)
Common misconceptions
- "Each send arrives as one read." TCP has no message boundaries; readers must loop until a complete frame has been assembled.
- "An ACK means the server processed my request." It means the peer's kernel has the bytes; only an application-level response confirms processing.
- "TIME-WAIT is a bug to switch off." It protects new connections from stale segments; reduce churn by reusing connections rather than shortening it blindly.
- "TCP notices a dead peer quickly." With no data in flight, a silently dead peer is detected only by keepalives (off by default, and slow when enabled), an application heartbeat or a timeout on the next exchange.
- "UDP is faster than TCP." UDP does less for you; performance depends on what the application rebuilds on top and on how networks treat UDP traffic.
How to approach it
Be able to draw the handshake and teardown with state names (LISTEN, SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1 and -2, CLOSE-WAIT, LAST-ACK, TIME-WAIT) and explain each transition. Practice explaining framing with code. Mid and senior follow-ups include retransmission timing, thousands of CLOSE-WAIT sockets (the local application never called close), port exhaustion, idempotent retries, and when you would choose UDP plus your own reliability.
Suggested order
- 1Read Computer Networks: A Systems Approach Section 5.2 (Reliable Byte Stream (TCP)), especially connection establishment and termination, adaptive retransmission and record boundaries.
- 2Draw the TCP state diagram from memory, then check it against RFC 9293 Section 3.3.2 (State Machine Overview) and Sections 3.5 and 3.6.
- 3Read RFC 6298 Section 2 (The Basic Algorithm) and compute an RTO by hand from three RTT samples.
- 4Complete the CS144 byte-stream, reassembler, TCP receiver and TCP sender checkpoints, or at minimum the framed echo-server project in this app.
- 5Capture a short HTTP connection with tcpdump, label SYN, SYN-ACK, ACK, data, FIN and ACK, then watch the closed socket sit in TIME-WAIT with ss -tan.
- 6Skim RFC 8085 Section 3 (UDP Usage Guidelines) and list what UDP applications must provide themselves.
Step 2: Check off what you can do
Tap each one you can genuinely do or explain. Each earns 10 XP.
Step 3: Go deeper
Computer Networks: A Systems ApproachStart here
Systems Approach (open online edition)Section: 5.2 Reliable Byte Stream (TCP)
Main reading: segment format, connection setup and teardown, sliding window, adaptive retransmission and record boundaries.
Open(opens in a new tab)Link responded, 5 Oct 2026RFC 9293: Transmission Control Protocol (TCP)
IETF (RFC Editor)Section: Section 3.3.2: State Machine Overview
Authoritative reference for connection states and transitions, including TIME-WAIT; continue with Sections 3.5 and 3.6.
Open(opens in a new tab)Link responded, 5 Oct 2026Stanford CS144 Introduction to Computer NetworkingStart here
Stanford UniversitySection: Lab checkpoints: byte stream, reassembler, TCP receiver and TCP sender
Implement the reliability machinery so sequence numbers, windows and retransmission become concrete.
Open(opens in a new tab)Link responded, 5 Oct 2026RFC 6298: Computing TCP's Retransmission Timer
IETF (RFC Editor)Section: Section 2: The Basic Algorithm
How the retransmission timeout is computed from smoothed RTT and RTT variance.
Open(opens in a new tab)Not checkable automatically, 5 Oct 2026RFC 8085: UDP Usage Guidelines
IETF (RFC Editor)Section: Section 3: UDP Usage Guidelines
What protocols built on UDP must add: congestion control, message sizing and reliability.
Open(opens in a new tab)Not checkable automatically, 5 Oct 2026
Step 4: Practice
In the CS144 checkpoints, write tests for wraparound sequence numbers, out-of-order segments and retransmission before the implementation. In the framed echo-server project, send messages split across several writes and several messages in one write, and make the reader handle both. Capture a short connection with tcpdump -n -i any port 80 (or 443), label every packet, then run ss -tan state time-wait on the client to see the closed socket waiting.
- Stanford CS144 checkpoints: building TCPOpen(opens in a new tab)Not attemptedStanford CS144
- Build a framed TCP echo server and watch backpressureOpen(opens in a new tab)Not attemptedHands-on project (Beej's Guide as reference)
- Capture and annotate one HTTPS request end to end (DNS, TCP, TLS 1.3, HTTP)Open(opens in a new tab)Not attemptedHands-on project (Wireshark User's Guide as reference)
Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).
Step 5: Test yourself
Answer each one out loud or on paper before you finish the lesson.
- Question 1What happens if the final ACK of the handshake is lost?
- Question 2A server shows thousands of sockets in CLOSE-WAIT. Whose bug is it, and what is it?
- Question 3What problem does TIME-WAIT prevent, and why does it last two maximum segment lifetimes?
- Question 4How does a sender detect a loss without waiting for the retransmission timer?
- Question 5A client times out waiting for a payment response. Can it retry safely, and what does it need?
- Question 6Which guarantees does UDP give, and which ones must DNS or QUIC add?
- Question 7Why does one lost segment delay bytes that have already arrived?
You’re done when you can
- Explain why TCP needs TIME-WAIT and which side enters it in under two minutes, without notes.
- Write a length-prefixed message reader that passes tests for split and coalesced reads.
- Draw the state diagram for an active and a passive close from memory.
- Explain with a concrete failure scenario why a successful TCP write does not mean the request was processed.
Finish the lesson
Unlocks next: Flow control, congestion control and queueing, DNS, HTTP versions and TLS, Sockets, buffering and backpressure, Failure models, partial failure and timeouts


