5  Transmission Control Protocol (TCP)

In 60 Seconds

TCP is a connection-oriented transport protocol that guarantees reliable, ordered data delivery through a three-way handshake, acknowledgments, and retransmissions. While its 20-60 byte header and connection overhead add latency and power consumption, TCP is essential for IoT operations where data loss is unacceptable – firmware updates, configuration changes, and MQTT-based messaging.

Key Concepts
  • TCP Three-Way Handshake: Connection setup: SYN → SYN-ACK → ACK; establishes sequence numbers and window sizes; takes 1 RTT before any data can be sent (1.5 RTT to first data byte received)
  • TCP Sequence Number: 32-bit counter initialized to a random ISN (Initial Sequence Number) at handshake; incremented by bytes sent; used for ordering and acknowledgment
  • TCP ACK (Acknowledgment Number): Next expected sequence number from the sender’s perspective; cumulative acknowledgment; TCP uses delayed ACK (wait 200 ms or until 2 segments received) to reduce ACK traffic
  • TCP Window Scale Option: TCP extension (RFC 7323) allowing receive window >65535 bytes; window scale factor in SYN header allows windows up to 1 GB; required for high-throughput paths (>100 Mbps at 50 ms RTT)
  • MSS (Maximum Segment Size): Maximum TCP payload per segment; negotiated in SYN; typically 1460 bytes (1500 MTU - 20 IP - 20 TCP); critical for avoiding IP fragmentation
  • TCP SACK (Selective Acknowledgment): TCP extension allowing receiver to inform sender of non-contiguous received segments; enables sender to retransmit only missing segments vs Go-Back-N behavior
  • FIN/RST Close: TCP graceful close (FIN): orderly data flush; both sides send FIN+ACK; TCP abrupt close (RST): immediate connection tear-down, possible data loss; RST sent on error conditions
  • TCP Time-Wait: State after active close; lasts 2×MSL (typically 60–120 s); prevents old duplicate segments from interfering with new connections on the same 4-tuple

5.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Explain TCP’s connection-oriented architecture and three-way handshake mechanism
  • Analyze TCP header fields and their impact on IoT communication overhead
  • Compare TCP state machine transitions and their memory implications for constrained devices
  • Evaluate when to use TCP vs UDP for different IoT application requirements
  • Calculate latency and power consumption trade-offs for TCP in battery-powered devices
  • Configure TCP socket options (keepalive, TCP_NODELAY, SO_REUSEADDR) for IoT long-lived connections
  • Diagnose common TCP failure modes in IoT gateways, including TIME_WAIT accumulation and CLOSE_WAIT leaks
  • Select the appropriate transport protocol by applying a structured decision framework to real IoT deployment scenarios

5.2 Transmission Control Protocol (TCP)

⏱️ ~15 min | ⭐⭐ Intermediate | 📋 P07.C31.U03

MVU: TCP for IoT Engineers

Core Concept: TCP is a connection-oriented transport protocol that guarantees reliable, ordered data delivery through acknowledgments and retransmissions. Think of it as “certified mail” - you get confirmation that your message arrived.

Why It Matters: TCP is the foundation for critical IoT operations like firmware updates, configuration changes, and MQTT messaging. Using TCP when reliability matters (firmware) vs UDP when speed matters (sensor telemetry) can mean the difference between a successful deployment and a bricked device.

Key Takeaway: Use TCP for data that cannot be lost (firmware, commands, financial transactions). Use UDP for data that can be replaced (sensor readings, video streams). The 20-60 byte TCP header and 3-way handshake add latency and power consumption - only pay this cost when reliability is essential.

Sammy the Sensor says: “Hey friends! Let me tell you about TCP - the most careful messenger in the whole internet!”

Imagine This: You want to send a super important letter to your grandma with your birthday party photos. You could just drop it in a mailbox and hope it gets there… OR you could use certified mail where:

  1. 📬 You tell the post office “I’m sending a letter!” (SYN)
  2. 📮 They say “Got it, ready to help!” (SYN-ACK)
  3. ✅ You say “Great, here’s my letter!” (ACK)
  4. 🧾 Grandma signs when she gets it (Acknowledgment)
  5. 📋 If it gets lost, they send it again! (Retransmission)

That’s exactly how TCP works!

🖥️ → 🤝 → 🖥️ → 📦 → ✅

Your computer shakes hands with the other computer, then sends data, and waits to hear “I got it!” before sending more.

Why is this cool for IoT?

  • When your smart thermostat downloads new settings, TCP makes sure EVERY piece arrives correctly
  • If part gets lost, it automatically asks for it again
  • No missing puzzle pieces!

Fun Fact: TCP was invented in 1974 - that’s over 50 years old! It still works the same way today. 🌟

Try This: Next time you download an app, imagine millions of tiny packets racing to your device, each one saying “Did you get me?” and waiting for “Yes!” before the next one goes!

TCP is a connection-oriented protocol that guarantees establishment of connection before data transmission and ensures reliable, ordered delivery.

5.2.1 TCP Characteristics

TCP connection lifecycle diagram showing the three-way handshake (SYN, SYN-ACK, ACK), data transfer with acknowledgments, and four-way connection teardown (FIN, ACK, FIN, ACK) between client and server
Figure 5.1: TCP Connection Lifecycle with Three-Way Handshake
TCP provides reliable, ordered delivery through connection setup, acknowledgments, and graceful teardown

TCP connections go through several states during their lifetime. Think of it like a phone call:

  1. CLOSED: Phone is on the hook (no call)
  2. LISTEN: Waiting for someone to call
  3. SYN_SENT: You dialed, waiting for answer
  4. SYN_RECEIVED: Phone is ringing on their end
  5. ESTABLISHED: Both talking - connection active!
  6. FIN_WAIT: You said goodbye, waiting for them
  7. TIME_WAIT: Making sure the line is clear before hanging up

Why does this matter for IoT? Embedded devices have limited memory. Each TCP connection state consumes RAM (~4KB). A device managing 100 connections needs 400KB just for connection state!

5.2.2 TCP Properties

Connection-Oriented:

  • 3-way handshake: SYN, SYN-ACK, ACK before data transfer
  • Connection state: Both endpoints maintain connection information
  • 4-way termination: Graceful connection closure

Reliable:

  • Acknowledgments: Receiver confirms receipt of each segment
  • Retransmission: Lost packets automatically resent
  • Ordering: Sequence numbers ensure correct order
  • Error Detection: Checksum for data integrity

Flow Control:

  • Sliding window: Prevents sender from overwhelming receiver
  • Window size: Receiver advertises how much data it can accept

Congestion Control:

  • Slow start: Gradually increases transmission rate
  • Congestion avoidance: Backs off when network congested
  • Fast retransmit/recovery: Quickly recovers from packet loss

Use Cases:

  • Firmware updates (must be reliable)
  • Configuration data
  • File transfers
  • HTTP (web browsing)
  • MQTT (reliable pub/sub messaging)

5.2.3 TCP State Machine for IoT

Understanding TCP connection states is critical for IoT developers managing memory-constrained devices.

TCP state machine diagram showing connection lifecycle states including CLOSED LISTEN SYN_SENT SYN_RECEIVED ESTABLISHED FIN_WAIT CLOSE_WAIT and TIME_WAIT with transitions labeled by TCP flags and events

IoT Memory Impact by State:

State Memory Usage Duration IoT Concern
ESTABLISHED ~4 KB Connection lifetime Main operating state
TIME_WAIT ~280 bytes 2 × MSL (~2 min) Can accumulate on busy servers
CLOSE_WAIT ~280 bytes Until app closes Memory leak if not handled
SYN_RECEIVED ~280 bytes Until ACK SYN flood attack vector
Common IoT Pitfall: TIME_WAIT Accumulation

When an IoT gateway rapidly opens/closes TCP connections (e.g., polling 100 sensors), each closed connection stays in TIME_WAIT for ~2 minutes. With 100 connections/minute:

  • After 2 minutes: 200 sockets in TIME_WAIT
  • Memory used: 200 × 280 bytes = 56 KB
  • Port exhaustion: May run out of ephemeral ports (65535 max)

Solution: Use persistent connections (keep-alive) or connection pooling.

5.2.4 TCP Header Structure

TCP packet header structure showing source and destination port fields (16 bits each), sequence number (32 bits), acknowledgment number (32 bits), data offset, flags (SYN ACK FIN RST PSH URG), window size (16 bits), checksum (16 bits), urgent pointer, and options (0-40 bytes) totaling 20-60 bytes
Figure 5.2: TCP Packet Header Structure (20-60 Bytes)
TCP header is 20-60 bytes with extensive fields for reliability, ordering, and flow control - higher overhead than UDP

TCP Header Fields (simplified):

Field Size Purpose
Source/Dest Port 16 bits each Application endpoints
Sequence Number 32 bits Byte stream position
Acknowledgment Number 32 bits Next expected byte
Flags 9 bits SYN, ACK, FIN, RST, PSH, URG
Window Size 16 bits Flow control (receiver buffer)
Checksum 16 bits Error detection
Options 0-40 bytes MSS, timestamps, window scaling

Total Header: 20-60 bytes (vs 8 bytes for UDP)

5.2.5 TCP Handshake Timing for IoT

The TCP three-way handshake adds latency before any data can be sent. This diagram shows the timing impact for IoT devices:

TCP three-way handshake timing diagram showing client sending SYN, server responding SYN-ACK, client sending ACK, then data transmission with acknowledgments, demonstrating 1.5 RTT latency before first data byte with total connection overhead

The TCP handshake requires 1.5 round-trip times (RTT) before any data flows:

\[T_{\text{handshake}} = 1.5 \times \text{RTT}\]

For a cellular IoT device with RTT = 150 ms:

\[T_{\text{handshake}} = 1.5 \times 150\text{ ms} = 225\text{ ms}\]

The bandwidth-delay product determines how much data could have been sent during this setup time:

\[\text{BDP} = \text{bandwidth} \times \text{RTT} = 100\text{ kbps} \times 150\text{ ms} = 1,875\text{ bytes}\]

This means TCP’s handshake wastes enough time to transmit 37 complete 50-byte sensor readings. For applications sending small payloads frequently, this overhead is unacceptable.

IoT Latency Impact (assuming 100ms RTT over cellular):

Operation Packets Time Cumulative
SYN 1 50ms 50ms
SYN-ACK 1 50ms 100ms
ACK 1 0ms (piggyback) 100ms
DATA 1 50ms 150ms
DATA-ACK 1 50ms 200ms
FIN handshake 4 200ms 400ms

Result: Sending a 50-byte sensor reading takes 400ms with TCP vs 100ms with UDP (single packet, no handshake).

IoT Optimization: TCP Keep-Alive vs Short-Lived Connections
Approach Latency Battery Memory Best For
Keep-Alive Low (no handshake) Higher (keep-alive packets) Higher (4KB/conn) Frequent data, mains power
Short-Lived High (handshake each time) Lower (sleep between) Lower (no persistent state) Infrequent data, battery
UDP/CoAP Lowest Lowest Lowest Periodic telemetry

5.2.6 TCP Trade-offs for IoT

TCP’s reliability comes at a cost. The table below summarizes the key trade-offs IoT engineers must weigh:

TCP Advantage IoT Cost When the Cost is Worth It
Guaranteed delivery (ACKs + retransmission) Higher power (ACK packets, retransmit energy) Firmware updates, critical commands
Ordered delivery (sequence numbers) Head-of-line blocking on lossy links File transfers, sequential configuration
Flow and congestion control Variable latency, slow ramp-up Large data transfers over shared networks
Connection state tracking ~4 KB RAM per connection Long-lived MQTT broker connections

Common IoT Applications Using TCP: MQTT (pub/sub messaging), HTTP/HTTPS (web APIs), firmware OTA updates, device configuration, and log file transfers.

5.3 Summary and Key Takeaways

5.3.1 Core Concepts Recap

TCP for IoT summary diagram showing advantages of reliable ordered delivery and flow control versus disadvantages of high overhead latency and power consumption, with decision guide for when to use TCP versus UDP based on criticality and constraints

5.3.2 Key Takeaways

Remember These Critical Points
  1. TCP guarantees delivery through acknowledgments and retransmissions - use it when data cannot be lost (firmware updates, commands, financial transactions)

  2. TCP adds significant overhead compared to UDP:

    • Header size: 20-60 bytes vs 8 bytes for UDP
    • Latency: 1.5 RTT before first data byte (3-way handshake)
    • Memory: ~4 KB per connection for state management
    • Power: Keep-alive packets drain batteries
  3. TCP connection states impact IoT memory management:

    • ESTABLISHED: ~4 KB RAM per connection
    • TIME_WAIT: Can accumulate and exhaust resources
    • Always handle connection closure properly
  4. Protocol selection rule of thumb:

    • TCP: Reliability critical, power/latency not constrained
    • UDP: Periodic telemetry, battery-powered, real-time needs
    • Hybrid: TCP for critical ops, UDP for routine telemetry
  5. IoT-specific considerations:

    • Persistent connections (MQTT) vs short-lived (REST) depends on use case
    • TIME_WAIT accumulation can crash gateways with high connection turnover
    • CoAP over UDP often beats HTTP over TCP for constrained devices

5.3.3 Quick Reference Card

Decision Factor Choose TCP Choose UDP
Data criticality Must not lose any data Can tolerate occasional loss
Update frequency Infrequent (< 1/min) or streaming Frequent periodic (> 1/min)
Power source Mains-powered Battery-powered
Network type Reliable (Wi-Fi, Ethernet) Lossy (LPWAN, cellular)
Latency needs Flexible Real-time critical
Protocol layer HTTP, MQTT, AMQP CoAP, DNS, NTP, streaming

5.3.4 Common Pitfalls to Avoid

Avoid These TCP Mistakes in IoT
  1. Using TCP for periodic sensor readings - Wastes energy on handshakes when next reading replaces lost data

  2. Not handling TIME_WAIT - High connection turnover exhausts ports and memory

  3. Keeping connections open unnecessarily - Keep-alive packets drain batteries; close connections for battery devices

  4. Ignoring TCP state memory - 100 simultaneous connections need 400+ KB RAM

  5. Assuming TCP “just works” - Retransmissions cause variable latency; not suitable for real-time control

Concept Relationships

Depends on:

  • Layered Network Models - TCP operates at Layer 4 (Transport) between Application and Network layers
  • IP Addressing - TCP connections are identified by IP address + port combinations

Enables:

  • UDP Fundamentals - Understanding TCP’s complexity motivates UDP’s simplicity
  • MQTT Protocol - MQTT runs over TCP, relying on its reliability guarantees
  • TLS/DTLS Security - TLS adapts TCP’s reliable stream for encryption; DTLS adapts it for UDP

Related concepts:

  • TCP sequence numbers prevent out-of-order delivery but cause head-of-line blocking in lossy networks
  • The TIME_WAIT state (2 minutes) can exhaust ephemeral ports on high-throughput IoT gateways
  • Nagle’s algorithm improves throughput but adds 40-200ms latency for small IoT command packets
See Also

Prerequisites:

Deep dives:

External resources:

5.4 What’s Next

Now that you can evaluate TCP’s trade-offs and select appropriate transport protocols for IoT scenarios, continue building your protocol knowledge with these next chapters:

Topic Chapter Why It Follows
UDP Fundamentals UDP Fundamentals Contrast TCP’s reliability with UDP’s minimal overhead — the core trade-off for IoT telemetry
Transport Protocol Overview Transport Protocol Overview Compare TCP, UDP, and emerging protocols (QUIC, SCTP, DCCP) side by side
MQTT Messaging MQTT Protocol Implement pub/sub IoT messaging that runs over TCP, applying what you learned about persistent connections
CoAP for Constrained Devices CoAP Fundamentals Design a REST-like protocol interaction over UDP, the lightweight alternative to HTTP
Securing Transport Connections TLS and DTLS Security Configure encryption for both TCP (TLS) and UDP (DTLS) connections in IoT deployments
Protocol Selection Framework Transport Selection Framework Apply a systematic decision framework to select TCP, UDP, or application-layer protocols for any IoT scenario