Backend Development 15 min read

Understanding HTTP/1.1 Keep‑Alive, TCP Keepalive, and Nginx Configuration

This article explains the differences between HTTP/1.1 and HTTP/1.0 keep‑alive, the TCP keepalive mechanism and its kernel parameters, how to configure them in applications, and how Nginx implements and manages keepalive for client and upstream connections with detailed code examples.

Xueersi Online School Tech Team
Xueersi Online School Tech Team
Xueersi Online School Tech Team
Understanding HTTP/1.1 Keep‑Alive, TCP Keepalive, and Nginx Configuration

HTTP/1.1 differs from HTTP/1.0 by enabling keep‑alive by default, allowing persistent TCP connections; the article explains the TCP keepalive mechanism, its three kernel parameters (keepalive_probes, keepalive_time, keepalive_intvl) and how to view and modify them on Linux.

It then shows how applications can set these options via setsockopt(rs, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(keepalive)); and related calls, providing example C code for configuring keepalive, idle time, interval, and probe count.

Next, the article distinguishes TCP‑level keepalive from the HTTP “Connection: keep‑alive” header and describes how Nginx implements and configures keepalive on both client‑side and upstream connections, including so_keepalive , keepalive_timeout , keepalive_requests , and the keepalive directive in upstream blocks.

Configuration snippets illustrate enabling keepalive, adjusting idle, interval, and probe counts, and forcing HTTP/1.1 for upstream communication, e.g., listen 127.0.0.1:3306 so_keepalive=7m:75s:9; and keepalive_timeout 120s 120s; .

The internal Nginx workflow is detailed: parsing listen directives, inheriting socket options, managing connection pools, handling client requests, and cleaning up or reusing connections based on timeout and request limits, with code such as if (ls[i].keepalive) { setsockopt(ls[i].fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&value, sizeof(int)); } .

Finally, the article warns of potential issues such as “connection reset by peer” when upstream servers close idle connections, and concludes with a brief summary of the keepalive concepts.

ConfigurationTCPnginxnetworkingkeepalivehttp1.1
Xueersi Online School Tech Team
Written by

Xueersi Online School Tech Team

The Xueersi Online School Tech Team, dedicated to innovating and promoting internet education technology.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.