What is TCP Handshake?

Complete guide to TCP three-way handshake, connection establishment, SYN/SYN-ACK/ACK sequence, and TCP connection management

The TCP handshake (three-way handshake) is a connection establishment process where a client and server exchange three messages (SYN, SYN-ACK, ACK) to synchronize sequence numbers, negotiate connection parameters, and establish a reliable TCP connection. This three-step process creates the foundation for TCP’s guaranteed delivery, ordered packets, and flow control before any application data transfers.

TCP (Transmission Control Protocol) is connection-oriented: before applications exchange data, TCP must establish a reliable connection between endpoints. The handshake ensures both sides agree on initial sequence numbers (ISN), window sizes for flow control, and optional parameters (MSS, window scaling, selective acknowledgment). Without proper handshake, TCP’s reliability guarantees fail.

The handshake begins with the client sending a SYN (synchronize) packet with an initial sequence number. The server responds with SYN-ACK (synchronize-acknowledge), acknowledging the client’s SYN and sending its own SYN with its initial sequence number. The client completes the handshake with an ACK (acknowledge) packet, acknowledging the server’s SYN. After these three packets, the connection enters ESTABLISHED state and data transfer begins.

Last updated: 2026-04-23

How TCP Handshake Works

The three-way handshake establishes a TCP connection through synchronized state between client and server. Each side must know the other’s initial sequence number to track packets for reliable delivery, acknowledgment, and retransmission.

Step 1: SYN (Synchronize)

The client initiates connection by sending a TCP segment with SYN flag set (SYN=1). The segment includes:

  • Initial Sequence Number (ISN): Random 32-bit number (e.g., ISN = 1000)
  • TCP options: Maximum Segment Size (MSS), window scaling, selective acknowledgment (SACK) permitted
  • Source port: Random ephemeral port (e.g., 54321)
  • Destination port: Server’s well-known port (e.g., 80 for HTTP, 443 for HTTPS)

The client enters SYN_SENT state, waiting for server response. The SYN consumes one sequence number (sequence number 1000 is used; next data starts at 1001).

Step 2: SYN-ACK (Synchronize-Acknowledge)

The server receives SYN, allocates resources for the connection, and responds with TCP segment having both SYN and ACK flags set (SYN=1, ACK=1):

  • Server’s Initial Sequence Number: Random 32-bit number (e.g., ISN = 5000)
  • Acknowledgment Number: Client’s ISN + 1 (1000 + 1 = 1001), acknowledging receipt of client’s SYN
  • TCP options: Server’s MSS, window scaling, SACK capability
  • Source port: Server’s port (e.g., 80)
  • Destination port: Client’s ephemeral port (e.g., 54321)

The server enters SYN_RCVD state, waiting for client’s ACK. The SYN consumes one sequence number (server’s sequence 5000 used; next data starts at 5001).

Step 3: ACK (Acknowledge)

The client receives SYN-ACK, validates the acknowledgment, and sends final ACK segment (ACK=1):

  • Sequence Number: Client’s ISN + 1 (1001)
  • Acknowledgment Number: Server’s ISN + 1 (5000 + 1 = 5001), acknowledging receipt of server’s SYN
  • Possible TCP options: Finalized window scaling factor

The client enters ESTABLISHED state. Upon receiving this ACK, the server also enters ESTABLISHED state. Connection is now ready for data transfer.

TCP Connection States

StateDescriptionPacket Sent
CLOSEDNo connection exists-
LISTENServer waiting for connection requests-
SYN_SENTClient sent SYN, waiting for SYN-ACKSYN
SYN_RCVDServer sent SYN-ACK, waiting for ACKSYN-ACK
ESTABLISHEDConnection established, ready for dataACK
FIN_WAIT_1Active close initiated, waiting for FIN-ACKFIN
FIN_WAIT_2Active close, waiting for server’s FIN-
CLOSINGSimultaneous close, waiting for FIN-ACKFIN
TIME_WAITActive close, waiting for delayed packets-
CLOSE_WAITPassive close, waiting for application to close-
LAST_ACKPassive close, waiting for final ACKFIN

The client transitions: CLOSED → SYN_SENT → ESTABLISHED. The server transitions: CLOSED → LISTEN → SYN_RCVD → ESTABLISHED. Understanding states helps troubleshoot connection failures with tools like netstat and ss.

TCP Flags

The TCP header contains 9 control flags (1-bit each) that govern connection behavior:

  • SYN (Synchronize): Initiates connection, synchronizes sequence numbers. Present only in first two handshake packets.
  • ACK (Acknowledge): Confirms receipt of data or control segments. Present in all packets after initial SYN.
  • FIN (Finish): Gracefully closes connection. Sender has no more data to send.
  • RST (Reset): Abnormally closes connection. Sent when invalid segment received or connection refused.
  • PSH (Push): Requests immediate delivery to application layer. Bypasses receive buffer.
  • URG (Urgent): Indicates urgent data present. Urgent pointer field specifies location.
  • ECE (ECN-Echo): Explicit Congestion Notification. Signals congestion experienced.
  • CWR (Congestion Window Reduced): ECN flag. Indicates congestion window reduced.
  • NS (Nonce Sum): ECN nonce. Protection against accidental concealment.

During handshake, SYN, ACK, and possibly ECE/CWR flags are active. Data transfer primarily uses ACK, PSH, and URG flags. Connection termination uses FIN or RST flags.

TCP Options During Handshake

TCP options negotiate connection parameters during the handshake. Options only sent in SYN packets (first two handshake segments); not negotiated mid-connection.

Maximum Segment Size (MSS)

Largest amount of data (payload) per TCP segment. Typically: MTU - 20 bytes IP header - 20 bytes TCP header = MSS. Ethernet MTU 1500 bytes → MSS 1460 bytes. Prevents fragmentation. Each side advertises its MSS; smaller value used.

Window Scaling

Extends TCP window size beyond 16-bit limit (65,535 bytes). Scaling factor (0-14) shifts window value left. Factor 7 enables 8MB window. Essential for high-bandwidth, high-latency links (satellite, long-haul fiber). Negotiated only during handshake.

Selective Acknowledgment (SACK)

Allows receiver to acknowledge non-contiguous data blocks. Without SACK, receiver can only acknowledge contiguous data, causing unnecessary retransmission. SACK option lists received block boundaries. Improves performance on lossy networks.

Timestamps

Adds timestamp value and echo reply to each segment. Measures round-trip time (RTT) accurately. Improves retransmission timeout calculation. Protects against wrapped sequence numbers (PAWS). Useful for high-speed networks.

TCP Handshake Duration and Latency

The handshake requires 1.5 RTT (round-trip times) before data transfer begins. On a network with 50ms RTT:

  • Client sends SYN (0ms)
  • Server receives SYN, sends SYN-ACK (50ms one-way)
  • Client receives SYN-ACK, sends ACK (50ms return = 100ms total)
  • Server receives ACK (50ms return = 150ms total)
  • Data transfer begins after 150ms (1.5 × RTT)

For HTTPS connections, TCP handshake precedes TLS handshake, adding another 1-2 RTT. TCP handshake (1.5 RTT) + TLS handshake (1-2 RTT) = 2.5-3.5 RTT before application data. On high-latency links (satellite with 600ms RTT), this overhead significantly impacts performance.

TCP Fast Open (TFO) reduces handshake latency by allowing data in initial SYN packet for previously established connections. Client includes data with SYN using cached cookie from prior connection. Saves 1 RTT for repeated connections. Supported in Linux, macOS, but requires application support.

TCP vs UDP Connection Model

CharacteristicTCPUDP
Connection establishmentThree-way handshake requiredNo handshake
ReliabilityGuaranteed delivery, acknowledgmentBest-effort, no acknowledgment
OrderingOrdered delivery, sequence numbersNo ordering guarantee
StateConnection state maintainedStateless
OverheadHigher (handshake, ACKs, flow control)Lower (send and forget)
Use caseWeb, email, file transfer, SSHDNS, video streaming, VoIP, gaming

UDP (User Datagram Protocol) sends data without establishing connection. No handshake, no acknowledgment, no guaranteed delivery. Lower latency but no reliability. DNS uses UDP for simple queries (no handshake overhead); TCP for zone transfers (reliability required).

When TCP Handshake Occurs

TCP handshake occurs when:

  • Client initiates HTTP/HTTPS connection to web server
  • Email client connects to SMTP server
  • SSH client establishes secure shell session
  • FTP client transfers files
  • Database client connects to database server
  • Any application requires reliable, connection-oriented communication

TCP handshake does NOT occur when:

  • Application uses UDP protocol (DNS queries, video streaming)
  • Connection already established (persistent connections reuse existing connection)
  • Connection pooled (database connection pools maintain open connections)

Signals of Handshake Issues

  • Connection timeout: SYN sent but no SYN-ACK received (server down, firewall blocking)
  • Connection refused: RST received instead of SYN-ACK (server not listening on port)
  • Long connection establishment time: High RTT, server overloaded, network congestion
  • SYN flood symptoms: Server unresponsive, high number of SYN_RCVD connections
  • Incomplete handshakes: ACK not received, connection stuck in SYN_RCVD or SYN_SENT

Metrics and Measurement

Handshake Performance Metrics:

  • TCP connection time: Time to complete handshake (target: <150ms for local, <300ms for regional, <500ms for global)
  • SYN rate: Connections initiated per second (server capacity planning)
  • SYN-ACK response time: Server processing time for incoming SYN (target: <10ms)
  • Handshake success rate: Percentage of successful connections (target: >99.9%)
  • Connections in SYN_RCVD: Potential SYN flood indicator (alert if >100 concurrent)

Network Metrics:

  • Round-trip time (RTT): Dominant factor in handshake duration
  • Packet loss: Retransmitted SYN or SYN-ACK increases handshake time
  • Jitter: Variation in RTT affects handshake predictability

According to HTTP Archive (2024), median TCP connection time for HTTPS is 65ms globally. High-latency regions (Asia-Pacific to US servers) see 200-400ms connection times. Each additional RTT directly impacts page load performance.

Real-World Use Cases

Web Browsing

  • Browser initiates TCP handshake to web server (port 80 or 443)
  • Persistent connections (HTTP/1.1 Keep-Alive) avoid repeated handshakes
  • Multiple concurrent connections for parallel resource loading
  • TLS handshake follows TCP handshake for HTTPS

Microservices Communication

  • Service mesh proxies establish TCP connections between services
  • Connection pooling reuses established connections
  • Health checks verify TCP handshake completion
  • Circuit breakers fail fast when handshake fails repeatedly

Database Connections

  • Application connects to database via TCP (MySQL port 3306, PostgreSQL port 5432)
  • Connection pools maintain open connections, avoiding handshake overhead
  • Authentication follows TCP handshake
  • Query latency measured after connection established

Load Balancer Health Checks

  • Load balancer sends SYN to backend server
  • SYN-ACK response indicates server healthy
  • Connection closed or reset after health check
  • Frequent health checks monitor server availability

SSH Remote Access

  • SSH client initiates TCP handshake to server (port 22)
  • Key exchange and authentication follow TCP handshake
  • Session maintains open TCP connection for command input/output
  • Keepalive packets prevent connection timeout

Common Mistakes and Fixes

Mistake: Not tuning SYN backlog for high-traffic servers Fix: Increase SYN backlog queue size (net.ipv4.tcp_max_syn_backlog on Linux) to handle connection bursts. Default value (128-1024) insufficient for high-traffic servers. Monitor SYN_RCVD connections; if backlog fills, server drops new SYN packets. Apply proper sizing based on connection rate.

Mistake: Ignoring SYN flood protection Fix: Enable SYN cookies (net.ipv4.tcp_syncookies on Linux) to mitigate SYN flood attacks. SYN cookies allow server to handle SYN floods without allocating full connection state until handshake completes. Combine with firewall rate limiting for defense-in-depth. Monitor for attack patterns.

Mistake: Disabling TCP Fast Open unnecessarily Fix: Enable TCP Fast Open (net.ipv4.tcp_fastopen on Linux) to reduce latency for repeat connections. Saves 1 RTT for connections to previously contacted servers. Requires application support (sendto() with MSG_FASTOPEN flag). Safe for most use cases with proper implementation.

Mistake: Not optimizing MSS for path MTU Fix: Configure correct MSS based on network path. MSS too large causes fragmentation; too small wastes bandwidth. For VPN/tunnel interfaces, reduce MSS to account for encapsulation overhead. Enable Path MTU Discovery to detect MTU along path. MSS clamping on routers handles tunnel scenarios.

Mistake: Overlooking SYN-RECEIVED state timeout Fix: Tune net.ipv4.tcp_synack_retries to balance between allowing slow networks and freeing resources. Default (5 retries, ~3 minutes) may be too long. High-traffic servers benefit from lower values (2-3 retries) to reclaim connection state faster. Match timeout to expected RTT distribution.

Mistake: Not monitoring half-open connections Fix: Monitor connections stuck in SYN_SENT or SYN_RCVD states. Half-open connections indicate network issues, server problems, or attacks. Set up alerts for abnormal counts. Use netstat -s or ss -s to track connection state distribution. Investigate root cause when anomalies detected.

Frequently Asked Questions

Why does TCP use a three-way handshake? Three-way handshake ensures both sides can send and receive reliably. SYN proves client can send. SYN-ACK proves server can receive and send. ACK proves client can receive. Two-way handshake could not verify bidirectional communication. Sequence number synchronization requires both sides to acknowledge each other’s ISN.

What happens if SYN packet is lost? Client retransmits SYN after timeout (typically 1-3 seconds, exponential backoff). Retransmission continues until maximum retries (default: 5-6 attempts, ~2 minutes total). Connection fails if no response after all retries. Application receives connection timeout error.

What happens if SYN-ACK is lost? Server retransmits SYN-ACK if no ACK received (controlled by tcp_synack_retries). Client may also retransmit SYN, triggering another SYN-ACK. Connection eventually succeeds when packets delivered, or times out if network unreliable. Duplicate SYN-ACK handled by ignoring duplicates after connection established.

Can a server refuse a connection during handshake? Yes. Server sends RST (reset) instead of SYN-ACK to refuse connection. Occurs when: port not listening (connection refused), server overloaded, access control lists block client IP, firewall rejects connection. Client receives “connection refused” error.

What is SYN flood attack? Attacker sends many SYN packets without completing handshake (no ACK). Server allocates resources for each SYN, eventually exhausting memory or SYN backlog queue. Legitimate connections cannot complete handshake. Defense: SYN cookies, increased backlog, rate limiting, firewall filtering.

How does TCP handshake differ for IPv6? Same handshake process. SYN, SYN-ACK, ACK sequence identical. TCP header format same. Difference: addresses are 128-bit IPv6 addresses instead of 32-bit IPv4. MSS negotiation may use larger values if path supports jumbo frames. No functional difference in handshake logic.

How does window scaling work in handshake? SYN packet includes window scale option (value 0-14). Advertised window value multiplied by 2^scale factor. Example: window value 65535, scale factor 7 = 65535 × 128 = 8,388,480 bytes. Allows windows larger than 16-bit field limit. Scale factor applies for entire connection.

How This Applies in Practice

Understanding TCP handshake is fundamental for network troubleshooting, performance optimization, and security hardening. Every connection-oriented service relies on successful handshake completion.

Performance Optimization:

  • Reduce RTT through CDN and edge computing (closer servers = faster handshake)
  • Enable TCP Fast Open for repeated connections
  • Use persistent connections to avoid repeated handshakes
  • Tune kernel parameters for high-traffic scenarios
  • Implement connection pooling in applications

Troubleshooting Connection Issues:

  • Check connection state with netstat or ss commands
  • Capture packets with tcpdump to visualize handshake
  • Verify server listening on expected port
  • Check firewall rules allowing SYN packets
  • Monitor for SYN flood attacks

Security Hardening:

  • Enable SYN cookies for SYN flood mitigation
  • Configure firewall rate limiting for SYN packets
  • Monitor half-open connection counts
  • Implement intrusion detection for SYN flood patterns
  • Keep systems updated for TCP vulnerability patches

TCP Handshake on Azion

Azion’s global network optimizes TCP handshake performance:

  • Edge locations terminate TCP connections close to users, reducing RTT
  • TCP Fast Open support for faster repeated connections
  • Optimized kernel parameters for high-throughput edge servers
  • Anycast routing ensures users connect to nearest edge location
  • TLS termination at edge reduces handshake overhead for origins
  • Connection pooling between edge and origin servers

Azion Edge Applications handle millions of TCP connections daily, with optimized handshake performance ensuring low latency for end users worldwide.

Learn more about TCP Protocol and Round-Trip Time.

Sources

stay up to date

Subscribe to our Newsletter

Get the latest product updates, event highlights, and tech industry insights delivered to your inbox.