cd ~/projects

HTTP server in C++

C++Socketsepoll

I’d read about the C10K problem plenty of times. I wanted to watch it actually happen to my own code, and then fix it.

results
built_with
C++, Linux sockets, epoll. No libraries.
speaks
HTTP/1.1 with keep-alive. GET, POST, DELETE on files.
thread_per_connection
Hit its limit at 5,889 connections
epoll_one_thread
About 14k req/s, flat up to 15,000 connections
socket_errors
0 at every level tested

Starting from a socket

The first version did one thing: open a socket on port 8080 and accept a connection. Then I added a request parser, then responses, and eventually it behaved like a real HTTP server, just for one client at a time. It serves files out of a ./public folder, makes a new file on POST, removes one on DELETE, and guesses the Content-Type from the file extension.

The parser checks the request line properly (a known method, a path starting with /, a version that looks like HTTP/1.1) and stores header names in lowercase so lookups don’t care about case. Because the server reads files from disk, I also guard against path traversal. Each requested path gets resolved to a real path and compared against ./public, so GET /../../etc/passwd returns a 403 instead of the file.

The first bug that taught me something

POST requests with bigger bodies came in cut off. The parser was reading the body out of whatever bytes had arrived so far. But TCP is a stream, not a list of messages, and a body can easily arrive split across several recv() calls. The fix was to stop treating the parser as the thing that reads from the network. The socket layer now keeps calling recv() until it has Content-Length bytes, and only then hands the full request over.

Version one: a thread for every connection

The simple way to handle many clients is to start a thread for each one. It’s easy to write, and each thread just blocks on recv() as if it were the only client. To find where it breaks, I wrapped thread creation in a try/catch and counted every thread with an atomic counter. Then I pushed it with wrk.

It hit a hard wall at 5,889 concurrent connections. That’s where the system ran out of resources for new threads, mostly because every thread reserves its own stack. Up to that point it was actually fast. It used all four cores and did about 40k requests per second. It just couldn’t take one more client.

wrk output for the thread-per-connection server at 5,889 connections: 39,954 requests per second
The threaded server at its limit: fast, but stuck at 5,889 connections.

Version two: one thread, epoll, and a state machine

The fix for C10K is to stop giving each client its own thread. One thread asks the kernel, through epoll, “which of these sockets are ready?”, and only deals with those. Every socket is non-blocking, so nothing ever waits.

The tricky part is that you lose the call stack that used to remember how far along each client was. A thread could just sit in the middle of reading headers. Now each connection has to remember that itself:

connection.h
enum class ConnectionState {
    READING_HEADERS, // Still accumulating bytes, haven't seen \r\n\r\n yet
    READING_BODY,    // Headers are done, this is a POST, still waiting for the full body
    WRITING          // Response is built, sending it out
};

Connections live in a map keyed by their file descriptor. When the response is ready, the socket switches from waiting to read to waiting to write. Writes can be partial too, so each connection tracks how much of its response has gone out so far:

main.cpp
ssize_t n = send(fd, conn.write_buf.c_str() + conn.write_offset,
                 conn.write_buf.size() - conn.write_offset, 0);
if (n > 0) {
    conn.write_offset += n;
    if (conn.write_offset >= conn.write_buf.size()) {
        if (conn.keep_alive) {
            conn.state = ConnectionState::READING_HEADERS;
            conn.buffer.clear();
            // ...switch the socket back to waiting for reads

The numbers

All runs used the same 4-core machine, ulimit -n 65535, a listen backlog of 4096, and 10-second wrk runs.

Bar chart of requests per second for the epoll server: about 14,000 from 100 to 15,000 connections, then 8,036 at 20,000 and 5,754 at 25,000
connectionsreq/secavg latencysocket errors
10014,5406.86 ms0
1,00014,24569.5 ms0
5,00014,476333 ms0
10,00013,852669 ms0
15,00013,942927 ms0
20,0008,0361.33 s0
25,0005,7541.62 s0

The epoll server under wrk. The thread-per-connection version couldn’t start a run past 5,889 connections.

Throughput stays flat at about 14k requests per second all the way to 15,000 connections, well past the 10k target, with zero socket errors. Latency grows roughly in line with the number of connections, which is what you’d expect: there’s one thread, so every request waits its turn.