Part 03 · The Language of the Web

Keep-Alive and Connection Reuse

KeepAliveConnections

Why opening a new connection per request is expensive, and how reuse saves the day.

⏱ 1 hours · Station 34 of 153

The payment API that was "slow"

Your checkout service calls a payment provider's API for every order. The provider promises responses in 20 ms, but your logs show every call taking 120 ms. You open a ticket. The provider replies: "Our server time is 18 ms. Are you reusing connections?"

You weren't. Your code created a new HTTP client for every call, so every call did DNS, a TCP handshake and a TLS handshake before sending a single byte, then threw the connection away. 100 ms of every request was setting up, not working.

Opening a connection is the most expensive thing an HTTP client does (Module 2: TCP costs a round trip, TLS another). Keep-alive means not closing the connection after a response, so the next request can go straight out. It's one of the cheapest, biggest performance wins in backend work, and also a source of strange bugs when idle connections quietly die.

The problem: setup costs more than the work

StepCostPaid on every new connection
DNS lookup0-50 ms (often cached)sometimes
TCP handshake1 round tripyes
TLS 1.3 handshake1 round trip + crypto CPU on both sidesyes
TCP slow startfirst round trips carry little datayes
The actual request and response1 round tripthat's the useful part

With a 50 ms round trip, a new HTTPS connection costs about 100 ms before the request even leaves. A small API call takes 50 ms more. Two thirds of the time is overhead, and the server burns CPU on TLS handshakes it didn't need to do.

Think of a phone call

You need to ask your friend five questions.

  • Without keep-alive: dial, wait for them to pick up, say hello, ask one question, hang up. Dial again for the second question. Five times.
  • With keep-alive: dial once, say hello once, ask all five questions, then hang up when you're done (or after a minute of silence).

The questions take the same time either way. The dialling and the hellos are pure waste. And if you keep the line open for an hour without talking, the phone company may cut it without telling you; the next time you speak, nobody's there.

new connection per requestone kept-alive connectionhandshakeGET 1handshakeGET 2handshakeGET 33 handshakes, 3 x the round tripshandshakeGET 1GET 2GET 31 handshake, then requests back to back
On top, every request opens its own connection: a handshake, then GET 1; another handshake, then GET 2; another handshake, then GET 3. Below, one handshake opens a kept-alive connection, and GET 1, GET 2 and GET 3 go out back to back on it.

Where the analogy stops working. A phone line is one conversation; an HTTP client usually keeps a pool of open connections to each host, handing them out to requests and taking them back. And unlike a dropped call, a dead TCP connection isn't always noticed until you try to use it.

The building blocks

  1. HTTP/1.1 keeps connections open by default. After a response, the connection stays open for the next request unless either side sends Connection: close. (In HTTP/1.0 it closed by default; Connection: keep-alive asked otherwise.)
  2. Framing makes it possible. The client knows where one response ends because of Content-Length or chunked encoding (lesson 1), so it can send the next request on the same bytes stream.
  3. Requests on one HTTP/1.1 connection take turns. One request, one response, next request. To run requests in parallel, clients open several connections (lesson 9); HTTP/2 multiplexes them on one.
  4. Connection pools. HTTP clients keep idle connections per host (scheme + host + port) and reuse them. Typical settings: maximum connections per host, maximum idle connections, and how long an idle connection is kept.
  5. Idle timeouts on both sides. Servers close connections that have been idle for a while (nginx's default keep-alive timeout is 75 s; many load balancers use 60 s). NAT devices and firewalls drop idle entries too (Module 2, lesson 12). Clients should close idle connections before the server does.
  6. Stale connections. If the server closes an idle connection at the same moment the client sends a request on it, the request fails (connection reset, EOF). Good clients retry idempotent requests once on a fresh connection.
  7. Server-side limits. Every open connection uses memory and a file descriptor. Servers limit concurrent connections and requests per connection, and may close long-lived connections to rebalance load.
  8. Reuse needs one long-lived client. In most languages, the pool lives inside the HTTP client object. Creating a new client per request creates a new pool, which means no reuse at all.
Predict first

A service makes 1,000 calls per second to another service in the same data centre (RTT 0.5 ms) over HTTPS. Each call creates a new HTTP client. What happens when they switch to one shared client with a pool?

Behind the scenes: a pooled client, from first call to idle timeout

Step through it

One host, one pool, many requests

Your codeConnection poolNetworkAPI server

Step 1/5 First request

The pool has no connection to api.pay.com yet. It dials: DNS, TCP handshake, TLS handshake. About 2 round trips before the request goes out.

pool
0 idle
round_trips
3

The picture to keep in your head

A connection is an expensive pipe: costly to build (handshakes), cheap to use (just a round trip per request).

  • Build once, use many times: one long-lived client per service, with a pool per host.
  • Return pipes after use: read the full response so the connection can go back to the pool.
  • Retire idle pipes before the other side does: client idle timeout < server and NAT timeouts.
  • Expect the occasional dead pipe: retry idempotent requests once on a fresh connection.

Try it: does this reuse connections?

Try each case

Reused or rebuilt?

def handler(): client = HttpClient(); client.get(...)
breaks: Every request gets a fresh client with an empty pool, so every call pays full setup. Create one client at startup and share it.

Code from first principles

A tiny HTTP/1.1 server that counts how many connections it accepted and how many requests arrived on each. A client sends five requests twice: first with a new connection for each (sending Connection: close), then on one connection kept alive, using Content-Length to know where each response ends. The last line turns the connection counts into time on a 50 ms network.

package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"strconv"
	"strings"
	"sync"
)

// The server counts how many TCP connections it accepted and how many requests came on each.
var (
	mu      sync.Mutex
	perConn []int
)

func serve(ln net.Listener) {
	for {
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		mu.Lock()
		perConn = append(perConn, 0)
		id := len(perConn) - 1
		mu.Unlock()
		r := bufio.NewReader(conn)
		for { // keep-alive: keep reading requests on this connection until the client closes it
			head := ""
			for !strings.HasSuffix(head, "\r\n\r\n") {
				line, err := r.ReadString('\n')
				if err != nil {
					break
				}
				head += line
			}
			if head == "" {
				break // the client closed the connection
			}
			mu.Lock()
			perConn[id]++
			mu.Unlock()
			body := "ok"
			fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s", len(body), body)
			if strings.Contains(head, "Connection: close") {
				break
			}
		}
		conn.Close()
	}
}

// readResponse reads one response, using Content-Length to know where it ends.
func readResponse(r *bufio.Reader) string {
	length := 0
	for {
		line, _ := r.ReadString('\n')
		if line == "\r\n" {
			break
		}
		if v, ok := strings.CutPrefix(line, "Content-Length: "); ok {
			length, _ = strconv.Atoi(strings.TrimSpace(v))
		}
	}
	body := make([]byte, length)
	io.ReadFull(r, body)
	return string(body)
}

func report(label string, requests int) {
	mu.Lock()
	defer mu.Unlock()
	fmt.Printf("%s: %d requests, server accepted %d connection(s), requests per connection %v\n", label, requests, len(perConn), perConn)
	perConn = nil
}

func main() {
	ln, _ := net.Listen("tcp", "127.0.0.1:8096")
	go serve(ln)
	const n = 5

	// A: a new connection for every request.
	for i := 0; i < n; i++ {
		conn, _ := net.Dial("tcp", "127.0.0.1:8096")
		fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n", i)
		readResponse(bufio.NewReader(conn))
		conn.Close()
	}
	report("new connection each time", n)

	// B: one connection, reused for every request.
	conn, _ := net.Dial("tcp", "127.0.0.1:8096")
	r := bufio.NewReader(conn)
	for i := 0; i < n; i++ {
		fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\n\r\n", i)
		readResponse(r)
	}
	report("one kept-alive connection", n)
	conn.Close()

	// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
	rtt := 50
	fmt.Printf("at %d ms RTT: new each time = %d x (2 + 1) round trips = %d ms, reused = (2 + %d) round trips = %d ms\n",
		rtt, n, n*3*rtt, n, (2+n)*rtt)
}

Output (the same in all five languages):

new connection each time: 5 requests, server accepted 5 connection(s), requests per connection [1 1 1 1 1]
one kept-alive connection: 5 requests, server accepted 1 connection(s), requests per connection [5]
at 50 ms RTT: new each time = 5 x (2 + 1) round trips = 750 ms, reused = (2 + 5) round trips = 350 ms

Reading the output:

  • New connection each time: 5 connections, 1 request each. Five TCP handshakes, and over the real internet five TLS handshakes too.
  • Kept alive: 1 connection, 5 requests. The server's loop kept reading requests on the same connection until the client closed it.
  • The client could reuse the connection only because of Content-Length: it knew the response was exactly 2 bytes, so the next bytes would belong to the next response.
  • At 50 ms RTT, 750 ms vs 350 ms for the same five requests. The work is identical; only the setup changed.

And the same effect against a real server, measured with curl's num_connects (new connections opened for that transfer):

$ curl -s -o /dev/null -o /dev/null -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/ https://example.com/ https://example.com/
new connections 1, tls done at 0.099458s, total 0.107765s
new connections 0, tls done at 0.000000s, total 0.006453s
new connections 0, tls done at 0.000000s, total 0.008123s
$ for i in 1 2 3; do curl -s -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/; done
new connections 1, tls done at 0.023686s, total 0.031295s
new connections 1, tls done at 0.019792s, total 0.029106s
new connections 1, tls done at 0.021939s, total 0.031011s
  • One curl process, three URLs: the first transfer opened a connection (DNS, TCP, TLS took 99 ms on this cold run), and the next two reused it: 0 new connections, about 6-8 ms each.
  • Three separate curl processes: each one is a new client with an empty pool, so every request opened a new connection and took about 30 ms, four times longer than a reused one.

Real engineering

  • One HTTP client per downstream service, created at startup. Go's http.Client, Python's requests.Session or httpx.Client, Node's undici agent or keepAlive: true agents, Java's HttpClient. Share it across requests and threads.
  • Always finish with the response. Read the body to the end (or close it). Unread bodies keep connections out of the pool.
  • Tune the pool: max connections per host (enough for peak concurrency, not unlimited), idle connections kept, idle timeout below the server's and the load balancer's.
  • Retry idempotent requests once on connection errors. Stale pooled connections are normal; a single retry on a fresh connection hides them. Don't auto-retry POST (lesson 4).
  • Same idea for databases and Redis. Use a connection pool; size it for your concurrency and the database's limits (Postgres handles hundreds of connections, not thousands; poolers like PgBouncer help).
  • Draining on deploy. When shutting a server down, stop accepting new requests and close keep-alive connections gracefully (send Connection: close on the last responses) so clients move to other servers without errors.

When it breaks

Try each case

Pick a failure

read tcp: connection reset by peer (first request after idle)
breaks: The server or a NAT/LB closed an idle pooled connection. Lower the client idle timeout below theirs, enable TCP keepalives, and retry idempotent requests once.

Think before you read on

Keep-alive saves time by holding connections open. Why might a server deliberately close a perfectly healthy connection after, say, 1,000 requests or 10 minutes?

Reveal

To spread load. A load balancer picks a server when a connection is opened, not for every request. A client with one long-lived connection sends everything to the same server forever, so after a scale-up the new servers sit idle and the old ones stay hot. Closing connections occasionally forces clients to reconnect, and each reconnect gets balanced again. It also lets servers recover leaked memory, rotate TLS certificates and drain cleanly before deploys. The cost is one handshake per 1,000 requests, which is tiny.

Check yourself

1. What is HTTP keep-alive, and what does it save?

Answer

Keeping a TCP (and TLS) connection open after a response so the next request can reuse it. It saves the TCP and TLS handshakes (round trips and CPU) and TCP slow start on every request after the first.

2. How does a client know where one response ends on a kept-alive connection?

Answer

From the response framing: Content-Length says exactly how many body bytes to read, or chunked encoding marks the end. Without that, the only end marker would be closing the connection.

3. Why should a client's idle timeout be shorter than the server's?

Answer

So the client retires idle connections before the server closes them. Otherwise the client may send a request on a connection the server has just closed, and the request fails with a reset.

4. Why does creating a new HTTP client for every request defeat keep-alive?

Answer

The connection pool lives inside the client. A new client has an empty pool, so every request opens a new connection and the old one is thrown away.

Your challenge: build a tiny pool

Extend the code with a connection pool:

  • Write get() that returns an idle connection if one exists, otherwise dials a new one, and put(conn) that returns it to the pool.
  • Give each pooled connection a "last used" time and an idle timeout of 3 seconds (use a fake clock you advance by hand, as in earlier lessons). get() must discard expired connections.
  • Send 3 requests, advance the clock by 5 seconds, then send 2 more.

Before you run it, predict how many connections the server will report accepting, and how many requests on each.

You've succeeded when the server reports 2 connections with [3 2] requests, your pool never hands out an expired connection, and making the idle timeout 10 seconds changes the report to 1 connection with [5].

The mental model

A connection is expensive to build (DNS, TCP, TLS, slow start) and cheap to use, so HTTP keeps it alive and clients keep a pool per host. Framing (Content-Length or chunked) is what lets several requests share one connection. Use one long-lived client, always finish reading responses, keep client idle timeouts below the server's and the network's, retry idempotent requests once on stale connections, and let servers recycle connections now and then so load stays balanced.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →