knaxuslearn · build · ship

Projects / HTTP server / Phase 3

Phase 3 of 4 · about 2.5 hours

Keep-alive, timeouts and limits

You end with a server that reuses connections, closes idle ones, refuses garbage, caps its own load, and survives 1,000 simultaneous clients without leaking descriptors.

Step 3.1: Why keep the connection open? (about 25 minutes)

Opening a TCP connection costs a round trip before any data moves. A web page needs a document, a stylesheet and some images, so closing the connection after every response makes the browser pay that cost again and again. Keep-alive means leaving the connection open for the next request. HTTP/1.1 does it by default, and HTTP/1.0 only when the client asks. These two helpers make that decision:

// Does the header block contain "Name: ... token ..."? Case does not matter in HTTP header names or tokens.
static int header_has(const char *req, const char *name, const char *token) {
  char needle[64];
  snprintf(needle, sizeof needle, "\r\n%s:", name);
  const char *line = strcasestr(req, needle);
  if (line == NULL) return 0;
  const char *end = strstr(line + 2, "\r\n");
  const char *hit = strcasestr(line, token);
  return hit != NULL && end != NULL && hit < end;
}

// HTTP/1.1 keeps the connection open unless told to close. HTTP/1.0 closes unless told to keep it.
static int wants_keep_alive(const char *req, const char *version) {
  if (strcmp(version, "HTTP/1.1") == 0) return !header_has(req, "Connection", "close");
  return header_has(req, "Connection", "keep-alive");
}
  • Header names and values are case-insensitive in HTTP, so we search with strcasestr.
  • header_has makes sure the word it found is on the right header line, not somewhere further down the request.
  • wants_keep_alive returns true for HTTP/1.1 unless the client sent Connection: close, and for HTTP/1.0 only if it sent Connection: keep-alive.

build_response now stores the answer in a new keep_alive field, and the response header says Connection: keep-alive or Connection: close to match. Errors we cannot recover from (bad request line, bad path, oversized headers) set keep_alive to 0 first, because after garbage we no longer trust where the next request would start.

Step 3.2: Reuse the connection, and pipelining (about 50 minutes)

After a response is fully sent, we either close the connection or reset it for the next request. The reset is the interesting part:

// The response is out. Close the connection, or get ready for the next request on it.
static void finish_response(Conn *c) {
  if (!c->keep_alive) { close_conn(c); return; }
  char *end = strstr(c->in, "\r\n\r\n");
  size_t used = (size_t)(end - c->in) + 4;
  memmove(c->in, c->in + used, c->in_len - used);  // bytes after this request may be the next one
  c->in_len -= used;
  c->in[c->in_len] = '\0';
  if (c->file >= 0) close(c->file);
  c->file = -1;
  c->head_len = c->head_sent = c->body_len = c->body_sent = 0;
  c->body = NULL;
  c->file_off = c->file_len = 0;
  if (strstr(c->in, "\r\n\r\n") != NULL) {  // a whole second request was already waiting
    build_response(c);
    watch(c, EPOLLOUT);
  } else {
    watch(c, EPOLLIN);
  }
}

Look at the memmove. A client may send a second request before it has read the first answer. This is called pipelining, and the bytes of request two may already be sitting in our in buffer, right behind request one. So we cut request one off the front, slide the rest down, and check whether a whole request is already waiting. If so, we answer it straight away. If not, we go back to watching for EPOLLIN. Responses must go out in the same order as the requests, and handling one request at a time per connection guarantees that.

Test three things: that curl really reuses one connection, that two requests in one write both get answered, and that Connection: close and HTTP/1.0 still close.

import os
import socket
import subprocess
import time


def start_server(port, *args):
    proc = subprocess.Popen(["./server", str(port), *map(str, args)], stderr=subprocess.DEVNULL)
    for _ in range(50):
        try:
            socket.create_connection(("localhost", port), timeout=0.2).close()
            time.sleep(0.2)  # let the server finish with that probe connection
            return proc
        except OSError:
            time.sleep(0.05)
    raise RuntimeError("server did not start")


_leftover = {}  # bytes already read from a socket that belong to its next response


def read_response(sock):
    """Read one HTTP response (headers plus Content-Length body). Returns (status line, body)."""
    data = _leftover.pop(id(sock), b"")
    while b"\r\n\r\n" not in data:
        chunk = sock.recv(4096)
        if not chunk:
            return None, b""
        data += chunk
    head, _, rest = data.partition(b"\r\n\r\n")
    length = 0
    for line in head.split(b"\r\n")[1:]:
        name, _, value = line.partition(b":")
        if name.lower() == b"content-length":
            length = int(value)
    while len(rest) < length:
        chunk = sock.recv(65536)
        if not chunk:
            break
        rest += chunk
    _leftover[id(sock)] = rest[length:]
    return head.split(b"\r\n")[0].decode(), rest[:length]


def open_fds(pid):
    return len(os.listdir(f"/proc/{pid}/fd"))
import socket
import subprocess

from helpers import read_response, start_server

server = start_server(8083)

# 1. curl asked for two URLs: does it reuse one connection?
out = subprocess.run(
    ["curl", "-sv", "-o", "/dev/null", "-o", "/dev/null", "localhost:8083/", "localhost:8083/style.css"],
    capture_output=True, text=True,
).stderr
print("curl lines:", [l.strip("* ").strip() for l in out.splitlines() if "Re-using" in l or l.startswith("* Connected")])

# 2. Two requests sent in a single write (pipelining): both must be answered, in order.
s = socket.create_connection(("localhost", 8083))
s.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\nGET /style.css HTTP/1.1\r\nHost: x\r\n\r\n")
for _ in range(2):
    status, body = read_response(s)
    print("pipelined:", status, len(body), "bytes")

# 3. Connection: close is respected.
s2 = socket.create_connection(("localhost", 8083))
s2.sendall(b"GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
print("with Connection: close:", read_response(s2)[0], "| server closed the socket:", s2.recv(10) == b"")

# 4. HTTP/1.0 closes by default.
s3 = socket.create_connection(("localhost", 8083))
s3.sendall(b"GET / HTTP/1.0\r\n\r\n")
print("HTTP/1.0:", read_response(s3)[0], "| server closed the socket:", s3.recv(10) == b"")
server.kill()
curl lines: ['Connected to localhost (127.0.0.1) port 8083', 'Re-using existing connection with host localhost']
pipelined: HTTP/1.1 200 OK 70 bytes
pipelined: HTTP/1.1 200 OK 34 bytes
with Connection: close: HTTP/1.1 200 OK | server closed the socket: True
HTTP/1.0: HTTP/1.1 200 OK | server closed the socket: True

The line Re-using existing connection comes from curl itself and shows the second request travelled on the first socket.

Step 3.3: Idle timeouts (about 35 minutes)

Keep-alive creates a new problem: a client can now hold a connection open forever. Our server keeps about 9.8 KB for each one (the size of Conn), so ten thousand lazy clients cost about 98 MB of memory and a slice of the file descriptor limit. A cousin of the idle client is the slow client who sends one byte of a request every few seconds, known as a slowloris attack. Both are cured by the same rule: a connection that does nothing for a while is closed.

Each Conn has a last_active time that every read and write refreshes, and the main loop wakes at least once a second to sweep:

static void close_idle(void) {
  for (int fd = 0; fd <= max_fd; fd++) {
    Conn *c = conns[fd];
    if (c != NULL && now_s - c->last_active >= idle_seconds) close_conn(c);
  }
}

The loop in main already has the pieces: epoll_wait takes a one second timeout so we wake even when nobody is talking, and the sweep runs when the clock has moved on to a new second.

  struct epoll_event events[MAX_EVENTS];
  for (;;) {
    int ready = epoll_wait(epoll_fd, events, MAX_EVENTS, 1000);  // wake at least once a second
    time_t before = now_s;
    now_s = time(NULL);
    for (int i = 0; i < ready; i++) {
      int fd = events[i].data.fd;
      if (fd == server) { accept_all(server); continue; }
      Conn *c = conns[fd];
      if (c == NULL) continue;
      if (events[i].events & (EPOLLERR | EPOLLHUP)) { close_conn(c); continue; }
      if (events[i].events & EPOLLIN) on_readable(c);
      else if (events[i].events & EPOLLOUT) {
        int done = on_writable(c);
        if (done < 0) close_conn(c);         // the client went away
        else if (done > 0) finish_response(c);
      }
    }
    if (now_s != before) close_idle();
  }
}

max_fd is the highest descriptor in use, so the sweep scans a few thousand slots and not all 65,536. Scanning every connection each second is simple, and fine at this scale. Production servers keep timers in a heap or a timing wheel so they never scan.

Step 3.4: Limits, garbage and a crowd (about 40 minutes)

A server that talks to the internet should assume that some clients are broken or hostile, and set limits so that one of them cannot hurt the others. We already limit headers to 8 KB. Two more limits and one repair finish the job.

A cap on connections. Past max_conns, new clients are closed at once instead of using memory we may not have:

static void accept_all(int server) {
  for (;;) {  // accept until the queue is empty: one wake-up may mean many waiting clients
    int fd = accept(server, NULL, NULL);
    if (fd < 0) return;  // EAGAIN: nobody else is waiting
    if (fd >= MAX_FDS || open_conns >= max_conns || set_nonblocking(fd) < 0) { close(fd); continue; }
    Conn *c = calloc(1, sizeof *c);
    if (c == NULL) { close(fd); continue; }
    c->fd = fd;
    c->file = -1;
    c->last_active = now_s;
    conns[fd] = c;
    open_conns++;
    if (fd > max_fd) max_fd = fd;
    struct epoll_event ev = {.events = EPOLLIN, .data.fd = fd};
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
  }
}

Garbage with a NUL byte. C strings end at the first zero byte. If a client sends \x00 in the middle of a request, strstr stops searching there, never sees the blank line that follows, and waits for headers that already arrived. Binary garbage is also never valid HTTP. So on_readable refuses any request that contains a zero byte:

    if (memchr(c->in + c->in_len, '\0', (size_t)n) != NULL) {  // a NUL byte would end our string functions early
      c->keep_alive = 0;
      respond_text(c, 400, "Bad Request", "bad bytes\n");
      watch(c, EPOLLOUT);
      return;
    }

The test starts the server with a 2 second idle limit and room for 5 connections, then throws each of these at it:

import socket
import time

from helpers import read_response, start_server

# 1. Idle connections are closed. (Server started with a 2 second idle limit.)
server = start_server(8084, 2)
idle = socket.create_connection(("localhost", 8084))
idle.settimeout(5)
start = time.time()
print("idle client closed by server:", idle.recv(10) == b"", f"after {time.time() - start:.1f}s")

# 2. Slowloris: send half a request, then stop. The server must not wait forever.
slow = socket.create_connection(("localhost", 8084))
slow.sendall(b"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: ")
slow.settimeout(5)
start = time.time()
print("half-sent request closed:", slow.recv(10) == b"", f"after {time.time() - start:.1f}s")

# 3. Headers that never end: answered with 431 once they pass 8 KB.
big = socket.create_connection(("localhost", 8084))
big.sendall(b"GET / HTTP/1.1\r\nX-Big: " + b"a" * 10000 + b"\r\n\r\n")
print("oversized headers:", read_response(big)[0])

# 4. Garbage.
bad = socket.create_connection(("localhost", 8084))
bad.sendall(b"\x00\x01\x02 not http \r\n\r\n")
print("garbage:", read_response(bad)[0])
server.kill()

# 5. A cap on connections. (Server started with room for 5.)
server = start_server(8085, 10, 5)
clients = [socket.create_connection(("localhost", 8085)) for _ in range(8)]
time.sleep(0.3)
answered = 0
for c in clients:
    c.settimeout(1)
    try:
        c.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
        if read_response(c)[0] == "HTTP/1.1 200 OK":
            answered += 1
    except OSError:
        pass
print(f"8 clients, room for 5: {answered} were served")
server.kill()
idle client closed by server: True after 2.0s
half-sent request closed: True after 2.0s
oversized headers: HTTP/1.1 431 Request Header Fields Too Large
garbage: HTTP/1.1 400 Bad Request
8 clients, room for 5: 5 were served

Idle clients and half-sent requests are closed after the 2 seconds we asked for, oversized headers get a 431, garbage gets a 400, and when 8 clients arrive for 5 places, 5 are served.

Finally the crowd. This test connects 1,000 clients at once, lets them all ask together, and checks that every one is answered and that no file descriptor is left open afterwards, including after 5,000 short connections in a row:

import resource
import socket
import time

from helpers import open_fds, read_response, start_server

resource.setrlimit(resource.RLIMIT_NOFILE, (8192, 8192))
server = start_server(8086, 30)
before = open_fds(server.pid)

# 1,000 clients connect first and stay connected. Then they all ask at once.
start = time.time()
clients = [socket.create_connection(("localhost", 8086)) for _ in range(1000)]
for c in clients:
    c.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
ok = sum(read_response(c)[0] == "HTTP/1.1 200 OK" for c in clients)
print(f"1000 simultaneous clients: {ok} answered with 200 in {time.time() - start:.2f}s")
print("server open file descriptors while they are connected:", open_fds(server.pid))

for c in clients:
    c.close()
time.sleep(0.5)
after = open_fds(server.pid)
print(f"descriptors before: {before}, after everyone left: {after}")

# Connect, ask, hang up, 5000 times: nothing must pile up.
for _ in range(5000):
    s = socket.create_connection(("localhost", 8086))
    s.sendall(b"GET /style.css HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
    read_response(s)
    s.close()
time.sleep(0.5)
print("after 5000 more short connections:", open_fds(server.pid))
server.kill()
1000 simultaneous clients: 1000 answered with 200 in 0.04s
server open file descriptors while they are connected: 1005
descriptors before: 5, after everyone left: 5
after 5000 more short connections: 5

One thread answered all 1,000 clients, and the descriptor count went from 1,005 while they were connected back to the same 5 it started with. A server that leaks one descriptor per connection would show a growing number in the last line, and would crash when it hit the limit. Your own shell limits how many descriptors a process may open (see it with ulimit -n), which is why the test raises the limit before it starts the server.

Phase 3 done

The server now does what a small production server does with connections: it reuses them, closes the idle ones, refuses nonsense and protects itself from being overloaded. Phase 4 measures it, and the measurement finds a real problem.