Skip to content

About

Minimal http server that implements reactor pattern with epoll.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

http project

The motivation for this project was purely educational. Implementation of minimal http server based on reactor design pattern and epoll allowed me to revise the material of Operating systems college course and C in general. Http server is not fully finished (GET ONLY), more important was full implementation and understanding of reactor design pattern.

Build & run

make
./main <port> <server_path>

Example: ./main 8080 ./wwwroot

Event I/O multiplexing

Server uses epoll (specific only to Linux kernel) - the most effiecient way to monitor multiple descriptors without really blocking the processes. Instead of continuously checking every descriptor (polling), epoll delegates descriptor tracking directly to the operating system kernel. When network activity occurs (such as an incoming TCP packet), the network card hardware triggers an interrupt. For now it's only level-triggered (default safer way ~ less effiecient).

Server type thoughts

Why not thread-per-connection so that any clients were concurrently dealt? Memory: Even though the heap is shared among thread, each thread requires a stack (typically 2MB-8MB). 10k threads equals ~20GB-80GB of RAM just for stacks.

Context Switching: The OS Scheduler must juggle thousands of threads. The CPU spends more time switching tasks (saving/restoring registers) than doing actual work.

Still one threaded event-driven servers might also no be the solution, for sure we need to use epoll but one thread is not enough.

Server type solution

We use thread_pool. Using fork requires little work. But it’s better to use Posix Thread (pthread_create()).

Possible Solution #1 EPOLLET | EPOLLONESHOT Shared epoll among all thread. Edge-triggered mode delivers events only when changes occur on the monitored file descriptor. Each change is delivered to a single thread chosen by the kernel. EPOLLONESHOT allows to avoid splitting chunks of the same stream between multiple threads. After I/O is done, the chosen thread must re-arm it with EPOLL_CTL_MOD("I am done processing I/O on this socket. You can resume monitoring it and alert me when the next event happens.")

BUT It does not scale out accept() at all. No other thread may accept while the socket is disarmed.

Solution: Have independent epoll instances in each worker. Dedicated acceptor thread assigns accepted clients to one of workers in a round-robin fashion via thread-safe epoll_ctl_add() into worker's epoll instance.

Also Epoll loop can be very long and have performace issues that's why we use REACTOR_PATTERN. image source

Structs

  1. handler_t object that consist of fd, on_read, on_write and app_data. Dispatcher sends any event to the handler that knows what to with it next.
  2. htto_conn_t before there was only http_request (we though of our connection that it's stateless in some sense). Consists of fd, read_buf[], read_len, char method[], char path[], char protocol[], char response[], size_t reponse_len, size_t reponse_sent.
  3. worker_ctx_t is one thread that runs its own reactor loop on its own epoll instance. Contains id, epoll_fd, pthread_t id. Why need of worker? Only worker knows what is his epoll_fd so which reactor loop he is in. So we need to know epoll_fd so that we can f.e reactor_modify / reactor_remove. reactor_remove = "this fd's life is over — remove from epoll, close the socket, forget it."

Architecture

1. Server startup

sequenceDiagram
    participant Main as main
    participant Listener as Listening socket
    participant AcceptLoop as Accept loop (epoll)
    participant Workers as 16 workers (threads)

    Main->>Listener: bind_tcp_socket() → listening socket (non-blocking)
    Main->>AcceptLoop: reactor_register(listener, on_read=accept_handler)<br/>→ "tell me when a new client arrives"
    Main->>Workers: start 16 threads, each with its own epoll
    Workers->>Workers: reactor_run(worker->epoll_fd) → own event loop
    Main->>AcceptLoop: main thread runs reactor_run(acceptor_epoll)<br/>→ never returns
Loading

2. Event loop — the dispatcher (reactor_run)

flowchart TD
    A["epoll_wait() — wait for an event on any watched socket"] --> B{"Is the socket failing?<br/>(EPOLLERR / EPOLLHUP)"}
    B -->|yes| R["reactor_remove()<br/>remove from epoll, close socket, forget it"]
    B -->|no| C{"Can we read? (EPOLLIN)"}
    C -->|yes| E["Run read handler (item->on_read):<br/>accept_handler → accept a new client<br/>http_on_read → read a request"]
    C -->|no| D{"Can we write? (EPOLLOUT)"}
    D -->|yes| G["Run write handler (item->on_write):<br/>http_on_write → send the rest of the response"]
    D -->|no| A
    E --> A
    G --> A
    R --> A
Loading

3. Accepting a client, then handling its request

sequenceDiagram
    participant AcceptLoop as Accept loop (reactor_run)
    participant Accept as accept_handler
    participant Worker as Worker event loop
    participant Client as http_on_read / http_on_write

    AcceptLoop->>Accept: EPOLLIN on listener → on_read
    loop keep accepting until accept() returns EAGAIN
        Accept->>Accept: accept() → new client socket
        Accept->>Accept: create per-client state (http_conn_t)<br/>+ handler (reactor_registry[fd])<br/>on_read=http_on_read, on_write=http_on_write
        Accept->>Worker: round-robin → reactor_register(worker epoll_fd, item, EPOLLIN)<br/>→ "tell me when I can read"
    end
    Worker->>Client: EPOLLIN → http_on_read
    Client->>Client: read until full request (\r\n\r\n), parse it,<br/>build response (or error like 400/403/404)
    Client->>Worker: reactor_modify(item, EPOLLOUT)<br/>→ "now tell me when I can write"
    Worker->>Client: EPOLLOUT → http_on_write
    Client->>Client: write() the response, chunk by chunk (EAGAIN → retry)
    Client->>Worker: response sent → reactor_remove()<br/>close connection (Connection: close)
Loading

Common mistakes

Socket Cleanup: If the browser closes the socket while your server is still trying to write to it (s_send_reponse), your process receives a SIGPIPE signal or a read_by_1_byte returning EOF. Solution sethandler(SIG_IGN, SIGPIPE)

Further Comments

Accepting thousands incoming connections per second is more tricky. Single accepting socket with its backlog is a bottleneck. That's why: For modern kernel Linux (3.9+), new feature emerged SO_REUSEPORT it's socker option that allows many threads/processes to bind to the same ip and port, so that the kernel is responsible for even managment of packets to threads.

Solution: Get rid of accepting thread - and make all the workers equally accept and do the work

About

Minimal http server that implements reactor pattern with epoll.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages