/ HTTP Headers

Keep-Alive

The primary purpose of the Keep-Alive header is to allow multiple requests and responses to be sent over a single connection, reducing the overhead of establishing and closing multiple connections. This results in improved performance and reduced latency.

Before HTTP/1.1, connections were closed by default after each request-response pair, which led to increased overhead. HTTP/1.1 introduced the concept of persistent connections, where connections are kept open by default, allowing multiple request-response pairs to be sent over the same connection. The Keep-Alive header is used to control this behavior.

Keep-Alive in HTTP Requests

When a client sends an HTTP request, it can include the Keep-Alive header to indicate that it wishes to keep the connection open for a specific period or for a specific number of requests. The header can include two optional parameters: timeout and max. The timeout parameter specifies the number of seconds the connection should be kept open, while the max parameter indicates the maximum number of requests that can be sent over the connection.

Here is an example of an HTTP request with the Keep-Alive header:

GET /index.html HTTP/1.1
Host: www.example.com
Connection: keep-alive
Keep-Alive: timeout=5, max=10

In this example, the client requests that the connection be kept open for 5 seconds (timeout=5) and allows up to 10 requests to be sent over the connection (max=10).

Keep-Alive in HTTP Responses

When a server receives an HTTP request with the Keep-Alive header, it can respond with the Keep-Alive header as well, indicating that it agrees to keep the connection open according to the client’s preferences. The server can also provide its own timeout and max values if it cannot fulfill the client’s request.

Here is an example of an HTTP response with the Keep-Alive header:

HTTP/1.1 200 OK
Content-Type: text/html
Connection: keep-alive
Keep-Alive: timeout=5, max=10

<!DOCTYPE html>
<html>
...
</html>

In this example, the server agrees to keep the connection open for 5 seconds (timeout=5) and allows up to 10 requests to be sent over the connection (max=10).

Connection Header and Keep-Alive

It is important to note that the Keep-Alive header must be accompanied by the Connection header with the value keep-alive. The Connection header is used to specify whether the connection should be kept open or closed, and the Keep-Alive header provides additional information about the connection’s behavior.

Summary

The Keep-Alive header plays a crucial role in improving the performance of HTTP connections by allowing multiple requests and responses to be sent over a single connection. Both clients and servers can use the Keep-Alive header to specify their preferences for connection persistence, including timeout and max parameters.

Was this helpful?

Thanks for your feedback!