731  Transmission Control Protocol (TCP)

731.1 Transmission Control Protocol (TCP)

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

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

731.1.1 TCP Characteristics

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#ecf0f1','background':'#ffffff','mainBkg':'#2C3E50','secondBkg':'#16A085','tertiaryBorderColor':'#95a5a6','clusterBkg':'#ecf0f1','clusterBorder':'#95a5a6','titleColor':'#2C3E50','edgeLabelBackground':'#ffffff','nodeTextColor':'#2C3E50'}}}%%
sequenceDiagram
    participant C as Client
    participant S as Server

    Note over C,S: 1. Connection Establishment
    C->>S: SYN (seq=100)
    S->>C: SYN-ACK (seq=200, ack=101)
    C->>S: ACK (ack=201)
    Note over C,S: Connection OPEN

    Note over C,S: 2. Reliable Data Transfer
    C->>S: Data (seq=101, len=50)
    S->>C: ACK (ack=151)
    Note over C,S: ACK confirms receipt

    S->>C: Data (seq=201, len=100)
    C->>S: ACK (ack=301)

    Note over C,S: 3. Connection Termination
    C->>S: FIN (seq=151)
    S->>C: ACK (ack=152)
    S->>C: FIN (seq=301)
    C->>S: ACK (ack=302)
    Note over C,S: Connection CLOSED

Figure 731.1: TCP Connection Lifecycle with Three-Way Handshake
TCP provides reliable, ordered delivery through connection setup, acknowledgments, and graceful teardown

Question 4: A smart home gateway maintains persistent MQTT connections (over TCP) to 50 sensors. Each sensor sends data every 5 minutes. What is the main downside?

💡 Explanation: TCP persistent connections are expensive for battery-powered IoT:

TCP connection overhead: - Keep-alive packets: TCP sends periodic packets (default 2 hours) to detect dead connections - Connection state: Buffers, sequence numbers, timers consume RAM - Energy cost: Wake from sleep every 2 hours to send keep-alive (~5-10% battery drain)

Calculation (per sensor):

Scenario: Sensor sends data every 5 minutes

TCP persistent connection:
- Keep-alive: Every 2 hours = 12 keep-alive/day
- Data transmit: Every 5 min = 288 data/day
- Total TX: 300 packets/day
- Always maintain connection state in RAM

UDP + CoAP:
- Data transmit: 288/day
- No keep-alive needed
- Connection state released after each message
- Energy: ~4% less than TCP

Gateway perspective (50 sensors): - TCP: 50 simultaneous connections × 4 KB state = 200 KB RAM minimum - Memory: Must handle all connections simultaneously - Scaling: Limited by TCP connection limits (typically 1000-10000)

Why not other answers: - A (header overhead): 12 bytes difference trivial for 5-minute interval - B (QoS 2): MQTT QoS 2 optional, can use QoS 0 or 1 - C (duplicate processing): TCP prevents duplicates (sequence numbers)

Better approach: Use MQTT-SN over UDP for battery sensors, or use short-lived TCP connections (connect, send, disconnect) trading latency for battery life.

Real-world: Zigbee, Thread use UDP-based protocols precisely to avoid TCP’s connection overhead.

731.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)

731.2.1 TCP Header Structure

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#ecf0f1','background':'#ffffff','mainBkg':'#2C3E50','secondBkg':'#16A085','tertiaryBorderColor':'#95a5a6','clusterBkg':'#ecf0f1','clusterBorder':'#95a5a6','titleColor':'#2C3E50','edgeLabelBackground':'#ffffff','nodeTextColor':'#2C3E50'}}}%%
graph TB
    subgraph "TCP Segment"
        subgraph "TCP Header: 20-60 bytes"
            H1[Source Port<br/>16 bits]
            H2[Dest Port<br/>16 bits]
            H3[Sequence Number<br/>32 bits<br/>Ordering]
            H4[Ack Number<br/>32 bits<br/>Reliability]
            H5[Header Length<br/>4 bits]
            H6[Flags<br/>SYN/ACK/FIN<br/>9 bits]
            H7[Window Size<br/>16 bits<br/>Flow Control]
            H8[Checksum<br/>16 bits]
            H9[Options<br/>0-40 bytes]
        end
        subgraph "Data"
            D[Application Payload]
        end
    end

    H1 --> D
    H2 --> D
    H3 --> D
    H4 --> D
    H5 --> D
    H6 --> D
    H7 --> D
    H8 --> D
    H9 --> D

    style H1 fill:#2C3E50,stroke:#16A085,color:#fff
    style H2 fill:#2C3E50,stroke:#16A085,color:#fff
    style H3 fill:#E67E22,stroke:#16A085,color:#fff
    style H4 fill:#E67E22,stroke:#16A085,color:#fff
    style H5 fill:#2C3E50,stroke:#16A085,color:#fff
    style H6 fill:#E67E22,stroke:#16A085,color:#fff
    style H7 fill:#16A085,stroke:#2C3E50,color:#fff
    style H8 fill:#2C3E50,stroke:#16A085,color:#fff
    style H9 fill:#2C3E50,stroke:#16A085,color:#fff
    style D fill:#27ae60,stroke:#16a085,color:#fff

Figure 731.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)

731.2.2 Why TCP for IoT?

Advantages:

  1. Reliability: Guaranteed delivery (critical for firmware updates)
  2. Ordering: Data arrives in correct sequence
  3. Error Recovery: Automatic retransmission
  4. Flow Control: Prevents buffer overflow
  5. Congestion Control: Network-friendly

Disadvantages:

  1. High Overhead: 20-60 byte header + connection state
  2. Higher Latency: 3-way handshake before data, retransmission delays
  3. Power Consumption: Connection state, acknowledgments, retransmissions
  4. Memory: Connection state requires RAM
  5. Not Real-Time: Retransmissions cause variable latency

IoT Applications Using TCP: - MQTT (Message Queue Telemetry Transport): Pub/sub messaging - HTTP/HTTPS: Web APIs, RESTful services - Firmware Updates: OTA (Over-The-Air) updates - Configuration: Device configuration and management - File Transfer: Log files, images

Artistic visualization of the TCP/IP model showing four layers: Application (HTTP, MQTT, CoAP), Transport (TCP, UDP), Internet (IP, ICMP), and Network Access (Ethernet, Wi-Fi), with data encapsulation at each layer adding headers.

TCP/IP Model
Figure 731.3: TCP/IP model with four-layer architecture

The TCP/IP model simplifies the OSI reference model into four practical layers. The transport layer (TCP/UDP) provides end-to-end communication, while the internet layer (IP) handles addressing and routing across networks.

Artistic representation of the TCP/IP protocol stack showing how application data is encapsulated with TCP/UDP header at transport layer, IP header at internet layer, and frame header/trailer at network access layer.

TCP/IP Stack
Figure 731.4: TCP/IP stack with data encapsulation

Artistic visualization of the TCP three-way handshake showing client sending SYN (synchronize) to server, server responding with SYN-ACK (synchronize-acknowledge), and client confirming with ACK (acknowledge) to establish bidirectional connection.

TCP Three-Way Handshake
Figure 731.5: TCP three-way handshake for connection establishment

The three-way handshake ensures both endpoints are ready to communicate and synchronizes sequence numbers. For IoT, this overhead of 3 packets before any data transfer makes TCP costly for infrequent sensor readings.

Artistic comparison of TCP and UDP protocols showing TCP with connection establishment, reliability, ordering, and flow control versus UDP with connectionless operation, no guarantees, and minimal overhead. Highlights trade-offs between reliability and efficiency for IoT applications.

TCP vs UDP Comparison
Figure 731.6: TCP vs UDP protocol comparison

TCP provides reliability through acknowledgments, sequencing, and retransmission but at the cost of overhead and latency. UDP offers minimal overhead and low latency but provides no delivery guarantees. IoT protocols like CoAP build reliability on top of UDP when needed.

Geometric diagram of transport layer protocols showing TCP (connection-oriented, reliable stream), UDP (connectionless, datagram), and newer protocols like QUIC (UDP-based with TLS), SCTP (multi-streaming), and DCCP (datagram congestion control).

Transport Protocols
Figure 731.7: Transport protocol family overview

Beyond TCP and UDP, modern transport protocols include QUIC (Google’s UDP-based protocol with built-in TLS, used by HTTP/3), SCTP (multi-stream with failover), and DCCP (datagram with congestion control). For IoT, understanding when to use each helps optimize performance.

Geometric comparison table of transport protocols showing TCP with 20-60 byte header, connection-oriented, reliable, ordered delivery versus UDP with 8-byte header, connectionless, best-effort, unordered delivery, plus DTLS for secured UDP datagrams.

Transport Protocol Comparison
Figure 731.8: Transport protocol feature comparison

Artistic visualization of UDP datagram flow showing simple client-to-server communication with no connection establishment, no acknowledgments, and independent datagram handling, demonstrating the fire-and-forget nature of UDP suitable for real-time and loss-tolerant IoT applications.

UDP Datagram Flow
Figure 731.9: UDP datagram flow without connection state

UDP’s connectionless model means each datagram is independent. The sender fires off datagrams without waiting for acknowledgments, and the receiver processes them as they arrive. This simplicity makes UDP ideal for real-time applications where occasional loss is acceptable.

731.2.3 TCP Analogy

TipTCP is Like a Telephone Call

TCP is similar to a telephone system:

  • Dial number (SYN - request connection)
  • Other person answers (SYN-ACK - acknowledge request)
  • You say hello (ACK - confirm connection)
  • Connection established - can now talk
  • Conversation - back-and-forth communication
  • “Did you hear me?” - acknowledgments
  • Repeat if needed - retransmission
  • “Goodbye” (FIN - close connection)
  • “Goodbye back” (FIN-ACK - confirm closure)

Both ends must be connected before communication can begin.

731.3 TCP vs UDP Comparison

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#ecf0f1','background':'#ffffff','mainBkg':'#2C3E50','secondBkg':'#16A085','tertiaryBorderColor':'#95a5a6','clusterBkg':'#ecf0f1','clusterBorder':'#95a5a6','titleColor':'#2C3E50','edgeLabelBackground':'#ffffff','nodeTextColor':'#2C3E50'}}}%%
graph TB
    subgraph "TCP Characteristics"
        T1[Connection-Oriented<br/>3-way handshake]
        T2[Reliable<br/>ACKs + Retransmission]
        T3[Ordered<br/>Sequence numbers]
        T4[Flow Control<br/>Window size]
        T5[Header: 20-60 bytes]
        T6[Higher Power]
    end

    subgraph "UDP Characteristics"
        U1[Connectionless<br/>No handshake]
        U2[Best-Effort<br/>No guarantees]
        U3[Unordered<br/>No sequencing]
        U4[No Flow Control]
        U5[Header: 8 bytes]
        U6[Lower Power]
    end

    subgraph "Best Use Cases"
        TC[TCP:<br/>Firmware Updates<br/>Configuration<br/>MQTT]
        UC[UDP:<br/>Sensor Readings<br/>CoAP<br/>Video Streaming]
    end

    T1 & T2 & T3 & T4 & T5 & T6 --> TC
    U1 & U2 & U3 & U4 & U5 & U6 --> UC

    style T1 fill:#2C3E50,stroke:#16A085,color:#fff
    style T2 fill:#2C3E50,stroke:#16A085,color:#fff
    style T3 fill:#2C3E50,stroke:#16A085,color:#fff
    style T4 fill:#2C3E50,stroke:#16A085,color:#fff
    style T5 fill:#e74c3c,stroke:#c0392b,color:#fff
    style T6 fill:#e74c3c,stroke:#c0392b,color:#fff
    style U1 fill:#16A085,stroke:#2C3E50,color:#fff
    style U2 fill:#16A085,stroke:#2C3E50,color:#fff
    style U3 fill:#16A085,stroke:#2C3E50,color:#fff
    style U4 fill:#16A085,stroke:#2C3E50,color:#fff
    style U5 fill:#27ae60,stroke:#16a085,color:#fff
    style U6 fill:#27ae60,stroke:#16a085,color:#fff
    style TC fill:#E67E22,stroke:#16A085,color:#fff
    style UC fill:#E67E22,stroke:#16A085,color:#fff

Figure 731.10: TCP vs UDP Feature Comparison and Use Cases
TCP vs UDP trade-offs: reliability and ordering vs low overhead and power efficiency

731.3.1 Detailed Comparison Table

Feature TCP UDP
Connection Connection-oriented (handshake) Connectionless
Reliability Reliable (ACKs, retransmission) Best-effort (no guarantees)
Ordering Ordered delivery Unordered (may arrive out of sequence)
Header Size 20-60 bytes 8 bytes
Overhead High (ACKs, state, retrans) Low (fire and forget)
Speed Slower (handshake, ACKs) Faster (immediate transmission)
Latency Higher (variable due to retrans) Lower (predictable)
Flow Control Yes (sliding window) No
Congestion Control Yes (slow start, etc.) No
Error Recovery Automatic retransmission None (app must handle)
Broadcast/Multicast No (point-to-point only) Yes
Power Consumption Higher (state, ACKs) Lower (minimal processing)
Memory Usage Higher (connection state) Lower (stateless)
Best For Reliability critical Low latency, real-time
IoT Use Cases Firmware, config, MQTT CoAP, telemetry, streaming

This variant shows how TCP and UDP behave differently during network congestion - critical for understanding IoT performance during high-traffic periods.

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#E8F6F3', 'fontSize': '10px'}}}%%
sequenceDiagram
    box rgb(46, 125, 50) TCP Congestion Control
    participant TS as Sensor
    participant TN as Network
    participant TG as Gateway
    end

    box rgb(231, 76, 60) UDP No Congestion Control
    participant US as Sensor
    participant UN as Network
    participant UG as Gateway
    end

    Note over TS,TG: TCP: Backs off when congested
    TS->>TN: Data (window=4)
    TN--xTG: Congestion detected!
    TN->>TS: ACK (window=2)
    Note over TS: Reduce rate by 50%
    TS->>TN: Data (window=2)
    TN->>TG: OK
    Note over TS,TG: TCP adapts, network recovers

    Note over US,UG: UDP: Ignores congestion
    US->>UN: Data 1
    US->>UN: Data 2
    US->>UN: Data 3
    US->>UN: Data 4
    UN--xUG: Packets 2,3 dropped!
    UN->>UG: Data 1, 4
    Note over US,UG: UDP keeps sending<br/>Congestion persists

Figure 731.11: TCP vs UDP Congestion Behavior - TCP adapts to network conditions while UDP continues at same rate regardless of congestion

Key Insight: TCP’s congestion control is “network-friendly” but adds latency. For IoT with bursty traffic, UDP with application-level rate limiting often provides better predictable performance.

731.3.2 When to Use TCP vs UDP in IoT

Question 1: A temperature sensor sends 20-byte readings every 30 seconds over a network with 2% packet loss. Should you use UDP or TCP?

💡 Explanation: UDP is ideal for periodic telemetry where fresh data replaces old:

Why UDP: - Data is replaceable: If reading at T=0 is lost, reading at T=30 provides current status - Low overhead: UDP 8-byte header vs TCP 20+ bytes (40% less overhead for small payloads) - No connection setup: No 3-way handshake, saves energy and latency - 2% loss is acceptable: 98% reliability sufficient for monitoring (not control)

When 2% loss matters: - Billing data (need every measurement) - Alarm events (can’t miss alerts) - Configuration changes (must be delivered)

Overhead comparison:

UDP: 20 bytes data + 8 header = 28 bytes total
TCP: 20 bytes data + 20 header = 40 bytes (+43% overhead)
TCP first transmission: +3-way handshake (3× round trips)

Battery impact: Temperature sensor sending every 30s: - UDP: ~2,880 messages/day × 28 bytes = 80 KB/day - TCP: ~2,880 messages/day × 40 bytes = 115 KB/day (+44% more transmission time/energy)

Real-world: CoAP uses UDP for this exact reason - periodic sensor data where timeliness > completeness.

731.4 Decision Guide

Use TCP when: - Reliability is critical: Firmware updates, configuration - Data must be ordered: Sequential commands, file transfers - Data loss unacceptable: Financial transactions, critical commands - Network is reliable: Wired connections, stable Wi-Fi - Power not a constraint: Mains-powered devices

Use UDP when: - Low latency required: Real-time monitoring, video streaming - Periodic data: Sensor readings every N seconds - Data loss tolerable: Occasional reading loss OK - Broadcast/multicast needed: One-to-many communication - Power constrained: Battery-powered sensors - Overhead matters: 6LoWPAN, constrained networks

Consider hybrid approach: - UDP for telemetry (sensor data) - TCP for critical ops (firmware, config) - Application-level reliability on UDP (CoAP confirmable messages)

731.5 Interactive Tool: TCP vs UDP Protocol Selector

Use this interactive tool to help determine whether TCP or UDP is more appropriate for your IoT application. Select the requirements that apply to your use case, and the tool will recommend a protocol based on a weighted scoring system.