knaxuslearn · build · ship

Projects / HTTP server

C · about 10 hours · 4 phases

Build a web server in C

Every website is, at the bottom, a program that waits on a network port, reads a few lines of text, and sends some bytes back. How does that program serve a thousand people at once? What happens when one of them is slow, or sends nonsense, or never hangs up? The best way to find out is to write one in C. In about 10 hours you will build a small web server that serves files, start it as the simplest thing that could work, watch it fall over, and then fix it step by step until it handles a thousand connections on a single thread.

You work in four phases of about 2.5 hours each, and every phase ends with something you can run. By the end you will have:

  • a server that speaks enough HTTP for curl and a browser to use it,
  • an event loop built on epoll that serves many clients without threads,
  • keep-alive connections, idle timeouts and limits that survive slow and hostile clients,
  • a load generator, a measured benchmark, and a leak check that comes back clean.

You need basic C (pointers, struct, arrays, printf) and a terminal. Sockets, HTTP and epoll are explained when they first show up.

If pointers or struct are new to you, write a few small C programs with them before you start. The listings assume you can read this kind of code.

The four phases

  1. The simplest server that works

    You end with a server that answers curl with a real web page, a 404, and a refusal for a path that tries to escape.

    • 1.1 Listen and accept30 min
    • 1.2 Writing all the bytes30 min
    • 1.3 Read and understand the request45 min
    • 1.4 Send the file and try it45 min
  2. Many clients on one thread

    You end with a server that answers a small request in under a millisecond while another client is still downloading a 20 MB file.

    • 2.1 One idle client blocks everyone25 min
    • 2.2 Non-blocking sockets and epoll35 min
    • 2.3 A small state machine per connection50 min
    • 2.4 sendfile, and the same test again40 min
  3. 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.

    • 3.1 Why keep the connection open?25 min
    • 3.2 Reuse the connection, and pipelining50 min
    • 3.3 Idle timeouts35 min
    • 3.4 Limits, garbage and a crowd40 min
  4. Measure, fix, harden

    You end with a benchmark you wrote yourself, a fixed performance bug, a clean leak check and a server that cannot be tricked out of its folder.

    • 4.1 Stop cleanly, then check for leaks35 min
    • 4.2 A load generator30 min
    • 4.3 Measure, and find a 40 millisecond stall50 min
    • 4.4 Stay inside the www folder35 min

Start with the setup →