What is HTTP keep-alive, and why does it speed up page loads?
Keep-alive reuses one TCP connection for several HTTP requests instead of opening a new one each time. This saves the handshake round trips (and the TLS handshake for HTTPS) for every file after the first. It is the default in HTTP/1.1.
Explain it simply
Calling a shop for each of five items, hanging up after each, and dialling again would waste time on dialling. Keep-alive is staying on the line and asking for all five items one after another.
Example
Without keep-alive (HTTP/1.0 default), 3 files, RTT = 50 ms:
each file: TCP handshake 50 ms + request/response 50 ms = 100 ms
total = 300 ms
With keep-alive:
one handshake 50 ms + 3 x 50 ms request/response = 200 ms
HTTP/1.1 header: Connection: keep-alive (assumed by default)
To close: Connection: closeEach new HTTPS connection also needs a TLS handshake, so the saving is bigger than shown. Servers close idle connections after a timeout, such as 5 to 75 seconds, to free resources.
HTTP/2 and HTTP/3 take this idea further, with many concurrent streams on one connection.
What to say in the interview
"Keep-alive keeps the TCP connection open for further requests, saving handshake time and slow-start restarts. It is on by default in HTTP/1.1, and servers close idle connections after a timeout."
Common mistakes
- Thinking keep-alive means the server holds the connection forever.