Sub topic 6
Opening a TCP connection
This chapter assumes you know what an IP address is and have read the previous chapter on DNS. At this point the browser has an IP address for the host, such as 93.184.216.34, and a port taken from the URL or the scheme default (80 for http, 443 for https). It still can't send an HTTP request. It first needs a TCP connection to that address and port.
What TCP provides
IP delivers individual packets on a best-effort basis. Packets can be lost, duplicated or reordered, and IP does nothing about it. TCP (Transmission Control Protocol) runs on top of IP and gives applications a simpler model: a reliable, ordered stream of bytes between two endpoints.
To do this, TCP keeps state on both sides:
- Sequence numbers label every byte sent, so the receiver can put data back in order and detect gaps.
- Acknowledgements tell the sender which bytes arrived. Unacknowledged data is retransmitted.
- Flow control lets the receiver advertise how much data it can buffer (the receive window).
- Congestion control lets the sender slow down when the network seems overloaded.
A connection is identified by four values: source IP, source port, destination IP and destination port. The server's port is well known (443). The browser's operating system picks the source port from a range of ephemeral ports, often 32768 to 60999 on Linux. Two tabs connecting to the same server get different source ports, so their connections never collide.
The three-way handshake
Before data flows, both sides must agree on starting sequence numbers and confirm they can reach each other. TCP does this with three segments.
- SYN. The client picks a random initial sequence number
xand sends a segment with the SYN flag set. It also advertises options such as the maximum segment size and window scaling. - SYN-ACK. The server picks its own initial sequence number
y. It acknowledgesx+1and sets both the SYN and ACK flags. - ACK. The client acknowledges
y+1. Both sides now consider the connection established.
Initial sequence numbers are random, not zero. This makes it hard for an attacker who can't see the traffic to forge segments that the endpoints would accept.
Why the handshake costs one round trip
The client can send its first data right after its ACK, and that segment can even carry the ACK itself. The client has to wait for the SYN-ACK first, though. Setup therefore costs one full round-trip time (RTT) before any application bytes move. At 80 ms RTT, every new connection costs about 80 ms before the browser can send a single byte of its request. For https, the TLS handshake in the next chapter adds more round trips on top.
This is why browsers and servers work to avoid new connections:
- Keep-alive. HTTP/1.1 reuses a connection for several requests by default. The
Connection: keep-aliveheader in the request example earlier in this tutorial relies on this. - Preconnect. A page can hint
<link rel="preconnect" href="https://cdn.example.com">so the browser opens a connection early. - Connection pools. Browsers keep idle connections open for a while and reuse them for later navigations to the same origin.
What the operating system does
The browser doesn't craft TCP segments itself. It calls the operating system's socket API, which handles the handshake:
- The browser asks for a new socket and calls
connect()with the destination IP and port. - The kernel chooses a source port and sends the SYN.
- The call completes when the SYN-ACK arrives and the kernel sends the final ACK. If no reply arrives, the kernel retransmits the SYN with growing delays (often 1, 2, 4 seconds and so on) until it gives up.
On the server side, the kernel keeps a queue of half-open connections (SYN received) and a queue of completed connections waiting for the application to call accept(). If a flood of SYNs fills the half-open queue, new clients can't connect. That attack is called a SYN flood, and servers defend against it with SYN cookies and rate limits.
Dual-stack hosts and Happy Eyeballs
A host name may resolve to both IPv6 (AAAA) and IPv4 (A) addresses. If the IPv6 path is broken and the browser waits for a full timeout, the page seems to hang. Browsers use an algorithm called Happy Eyeballs. They start with one address family, and if it hasn't connected after a short delay (a few hundred milliseconds at most), they start a second attempt in parallel with the other family. The first handshake to complete wins and the other attempt is cancelled.
Connection limits
HTTP/1.1 sends one request at a time per connection. To fetch many resources in parallel, browsers open several connections to the same host. Chrome and Firefox allow six per host. Each extra connection pays the handshake cost. HTTP/2 and HTTP/3, covered in a later chapter, multiplex many requests over a single connection, which largely removes the need for this workaround.
Observing the handshake
The curl timing variables show how long each phase took. time_connect is cumulative from the start of the command, so subtract time_namelookup to get the TCP setup time.
curl -s -o /dev/null \
-w 'dns: %{time_namelookup}s\ntcp done at: %{time_connect}s\n' \
http://example.com/With curl -v, the lines starting with * show the connection attempt:
curl -v http://example.com/ -o /dev/null 2>&1 | grep -E '^\* (Trying|Connected)'You can also time a connection from code. This Node.js script separates the DNS lookup from the TCP connect, using the lookup and connect events on the socket.
const net = require('net');
const start = process.hrtime.bigint();
let lookupDone = start;
const socket = net.connect({ host: 'example.com', port: 80 });
socket.on('lookup', () => {
lookupDone = process.hrtime.bigint();
});
socket.on('connect', () => {
const end = process.hrtime.bigint();
const dnsMs = Number(lookupDone - start) / 1e6;
const tcpMs = Number(end - lookupDone) / 1e6;
console.log(`Remote: ${socket.remoteAddress}:${socket.remotePort}`);
console.log(`Local port: ${socket.localPort}`);
console.log(`DNS: ${dnsMs.toFixed(1)} ms, TCP connect: ${tcpMs.toFixed(1)} ms`);
socket.end();
});
socket.on('error', (err) => {
console.error('Connection failed:', err.code);
});Run it several times. The local port changes on every run because the OS picks a fresh ephemeral port. The TCP time stays close to one RTT to the server.
In the browser, the Network panel's Timing tab shows this phase as Initial connection. For https requests that bar includes the TLS handshake. The Connection ID column, which you can enable from the column header menu, shows whether a request reused an existing connection. A reused connection has no connect bar at all.
Common failures
The error you see depends on what the network does with the SYN.
| Symptom | What happened | Typical cause |
|---|---|---|
| Connection refused (`ECONNREFUSED`) | The server's OS answered the SYN with a RST segment, meaning no one is listening | Wrong port, service not running |
| Connection timed out (`ETIMEDOUT`) | No answer came after repeated SYN retransmissions | Firewall silently dropping packets, host down, no route |
| Connection reset (`ECONNRESET`) | A RST arrived after the connection was established | Server crashed, idle timeout on a middlebox, load balancer limit |
| Very slow first connect, then success | The first SYN or SYN-ACK was lost and retransmitted, or Happy Eyeballs fell back | Packet loss, broken IPv6 path |
Exercise
A user is 120 ms RTT away from a server. The page needs 12 small resources from the same host, and the browser allows 6 connections per host with HTTP/1.1 and no connection reuse. Roughly how much time is spent on TCP handshakes in total if the connections are opened in parallel, and how does keep-alive change that?
Show answer
With 6 parallel connections, the browser needs two "waves" of requests. Without reuse, each request needs its own new connection, so each wave pays one handshake of about 120 ms. That makes about 240 ms of handshake delay along the critical path. With keep-alive, the 6 connections are opened once, costing about 120 ms, and the second wave of requests reuses them with no new handshake. The delay along the critical path drops to about 120 ms.