Non-blocking I/O & event loops
Structure a server as a non-blocking event loop with per-connection buffers.
By Invicly Tech, , in Linux System Programming. About 13 minutes to read.
In short
An event loop is a single thread that waits for readiness, runs a short non-blocking handler for each ready descriptor and goes back to waiting. Because handlers must never block, every connection keeps its own read buffer, write buffer and state. nginx, Redis and Node.js are built this way.
Explained simply
An event loop is one worker doing many small jobs in turns. It asks the kernel which connections are ready, handles each ready one for a moment, and goes back to asking. As long as every job is short, thousands of clients feel served at the same time.
The golden rule: never wait inside a handler. If a handler blocks on a slow client, the whole loop stops and every other client waits. So sockets are switched to non-blocking mode, where a read or write that cannot happen right now returns at once with the error EAGAIN instead of waiting.
Because a handler cannot wait, it must remember where it left off. Each connection gets its own little record: bytes received so far, bytes still to send, and what state the conversation is in.
This is how nginx, Redis and Node.js handle huge numbers of connections with very few threads. The price is code that is split into small steps instead of one simple top-to-bottom function.
Press Play on a diagram to walk through it one step at a time.
- 1Wait
epoll_wait with a timeout set by the next timer.
- 2Dispatch
Call the handler for each ready descriptor.
- 3Read until EAGAIN
Append to the input buffer and parse complete messages.
- 4Write what fits
Keep the rest and watch EPOLLOUT.
- 5Run timers
Expire idle connections and periodic tasks.
- Back to step 1
- Simple blocking code
- A stack per client
- Locks for shared data
- Good up to hundreds of clients
- Small struct per client
- No context switch per client
- Handlers must never block
- Scales to tens of thousands
- One loop per CPU core
- Thread pool for CPU and disk work
- Used by nginx and Node.js style servers
- Best of both, more design work
In depth
Non-blocking mode in practice
Set O_NONBLOCK on a descriptor with fcntl(fd, F_SETFL, flags | O_NONBLOCK), after reading the current flags with F_GETFL. Better, create sockets non-blocking from the start: socket(..., SOCK_STREAM | SOCK_NONBLOCK, 0) and accept4(lfd, NULL, NULL, SOCK_NONBLOCK). The listening socket should be non-blocking too, so that if another process or thread already took the connection, accept returns EAGAIN instead of hanging.
In non-blocking mode, read and recv return -1 with EAGAIN (on Linux the same value as EWOULDBLOCK) when no data is waiting. Writes return a short count, or EAGAIN when the send buffer is full. connect returns -1 with EINPROGRESS; wait until the socket is writable, then read the result with getsockopt(fd, SOL_SOCKET, SO_ERROR, ...).
One gap: O_NONBLOCK has no effect on regular files. A read from a slow disk still blocks the loop, so servers use a thread pool or io_uring for file I/O.
- accept4(..., SOCK_NONBLOCK | SOCK_CLOEXEC) saves two fcntl calls
- EAGAIN means not now, not failure
- Non-blocking connect: EINPROGRESS, then check SO_ERROR
The write path and back-pressure
Writing seems easy until a client reads slowly. The kernel send buffer fills, and write starts returning short counts or EAGAIN. The loop must not wait, so it copies the unsent bytes into the connection's output buffer and asks epoll for EPOLLOUT. When the socket becomes writable, the loop sends more. Once the output buffer is empty, it removes EPOLLOUT again; leaving it on makes epoll report the socket as writable on every turn, and the loop spins at 100% CPU.
Now the slow-reader problem. If a client keeps sending requests but never reads the replies, its output buffer grows without end. Apply back-pressure: when the output buffer passes a limit (say 1 MiB), stop reading from that client (remove EPOLLIN) until the buffer drains. If it never drains, close the connection. Redis, for example, disconnects clients whose output buffers exceed configured limits.
- 1Try write now
Usually the whole reply fits
- 2Short or EAGAIN
Append the rest to the output buffer
- 3Enable EPOLLOUT
Ask to hear when the socket can take more
- 4Writable event
Write from the buffer, drop what was sent
- 5Buffer empty
Disable EPOLLOUT so the loop does not spin
Per-connection buffers and state
Each connection carries a struct: the descriptor, an input buffer with its fill level, an output buffer with how much is already sent, a protocol state (reading a header, reading a body, closing), and the time of the last activity for timeouts.
The input side works like this: append whatever read returns, then parse as many complete messages as the buffer holds, then move any partial message to the front (memmove) and keep it for next time. Parsing must never assume a message arrived in one read. The output side appends replies and tracks an offset of what has been sent.
Put hard limits on both buffers. Without them a client can send a giant header or never read, and use up the server's memory. Fixed-size buffers are simplest; growable ones need an upper bound.
- struct conn { int fd; char in[8192]; size_t in_len; char *out; size_t out_len, out_sent; time_t last; }
- Parse in a loop: there may be several messages in one read
- Close connections that exceed buffer limits
Timers inside the loop
Servers need time-based work too: close idle clients after 60 seconds, retry an upstream, flush stats every 10 seconds. A loop cannot sleep for these, so it folds them into the wait. Keep timers sorted by deadline, for example in a min-heap or a timer wheel. Before each epoll_wait, compute how many milliseconds remain until the nearest deadline and pass that as the timeout (or -1 if there are none). After epoll_wait returns, whether because of events or the timeout, run every timer whose deadline has passed.
Use CLOCK_MONOTONIC for these deadlines, not the wall clock, so a clock change cannot fire every timer at once. Another way is timerfd, which turns a timer into a descriptor that epoll watches like a socket; the next module covers it. For idle timeouts with thousands of connections, a common trick is to keep connections in a list ordered by last activity and only check the oldest ones.
Thread-per-connection or event loop?
Thread-per-connection is the simplest model: each client gets a thread that runs straight-line blocking code. It works well for hundreds of connections. Its costs grow with scale: each thread needs a stack (virtual memory and some real memory), the scheduler must switch between thousands of threads, and shared data needs locks.
An event loop keeps each connection as a small struct, so 10,000 idle clients cost little memory and no context switches. The price is that logic is cut into callbacks and state machines, and one slow handler, CPU-heavy job or blocking call stalls everyone on that loop.
Real servers combine both. nginx runs one event loop per worker process, one per core. Memcached and many proxies run one loop per thread. Node.js runs JavaScript on one loop and sends file I/O and DNS lookups to a small thread pool in libuv. The rule: loops for waiting, threads for computing.
Learn it in 4 short steps
About 55m each. Track them with a timer in your plan.
- 1Set sockets to O_NONBLOCK~55m
- 2Handle EAGAIN on read and write~55m
- 3Keep per-connection read and write buffers~55m
- 4Compare thread-per-connection with event loops~55m
Key points
- EAGAIN or EWOULDBLOCK means try again later, not an error.
- Only enable EPOLLOUT interest while output is pending, or the loop spins.
- Any blocking call, such as a DNS lookup or sleep, stalls every connection.
- Run one loop per core, or hand CPU-heavy work to a thread pool.
Key terms
Tap a card to flip it. 0/5 known
Examples
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int set_nonblocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
return flags < 0 ? -1 : fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
int drain(int fd, char *buf, size_t cap, size_t *len) { // 0 EOF, -1 error, 1 drained
for (;;) {
ssize_t n = read(fd, buf + *len, cap - *len);
if (n > 0) { *len += n; if (*len == cap) return 1; continue; }
if (n == 0) return 0;
return (errno == EAGAIN || errno == EWOULDBLOCK) ? 1 : -1;
}
}Helpers every event-loop server needs.
Queueing output and toggling EPOLLOUT
conn_send is called when a handler has a reply. Step 1: if nothing is queued, try to write directly; usually everything goes out at once. Step 2: anything left (short write or EAGAIN) is appended to the output buffer, with a limit for back-pressure. Step 3: if data is now pending, switch the epoll registration to watch EPOLLOUT as well. on_writable runs on EPOLLOUT: it sends from the buffer and, once empty, switches back to EPOLLIN only.
int conn_send(struct conn *c, const char *p, size_t n) {
if (c->out_len == 0) { /* nothing queued: try now */
ssize_t w = send(c->fd, p, n, MSG_NOSIGNAL);
if (w < 0 && errno != EAGAIN && errno != EWOULDBLOCK) return -1;
if (w > 0) { p += w; n -= (size_t)w; }
}
if (n == 0) return 0;
if (c->out_len + n > sizeof c->out) return -1; /* too slow: caller closes */
memcpy(c->out + c->out_len, p, n); c->out_len += n;
struct epoll_event ev = { .events = EPOLLIN | EPOLLOUT, .data.ptr = c };
return epoll_ctl(c->ep, EPOLL_CTL_MOD, c->fd, &ev);
}
/* on_writable: send from c->out, memmove the rest down;
when c->out_len == 0, EPOLL_CTL_MOD back to EPOLLIN only */Parsing complete lines from a partial buffer
Bytes arrive in random chunks: "GET a\nGE" then "T b\n". Step 1: after each read, scan the input buffer for newlines. Step 2: hand every complete line to the handler. Step 3: move the unfinished tail ("GE") to the front of the buffer and keep it. Step 4: if the buffer is full and still has no newline, the line is too long, so report an error and let the caller close the connection.
int handle_lines(struct conn *c) { /* -1 = protocol error */
size_t start = 0;
for (size_t i = 0; i < c->in_len; i++) {
if (c->in[i] != '\n') continue;
c->in[i] = '\0';
if (on_line(c, c->in + start) < 0) return -1; /* one complete line */
start = i + 1;
}
memmove(c->in, c->in + start, c->in_len - start); /* keep the partial tail */
c->in_len -= start;
if (c->in_len == sizeof c->in) return -1; /* full, no newline: too long */
return 0;
}Quick reference
- fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) makes a fd non-blocking
- accept4(lfd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC) for new clients
- EAGAIN == EWOULDBLOCK on Linux: stop and wait for the next event
- Enable EPOLLOUT only while output is queued, or the loop spins
- Cap input and output buffers per connection; close offenders
- epoll_wait timeout = ms until the nearest timer, or -1 if none
- O_NONBLOCK does nothing for regular files: use a thread pool or io_uring
- Never call sleep, blocking DNS or heavy CPU work inside a handler
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make a socket non-blocking, call read on it with no data available, and print errno's name to see EAGAIN.
- Exercise 2medium
Write on_writable for the conn_send example: send as much of the output buffer as possible, keep the rest, and switch back to EPOLLIN only when the buffer is empty.
- Exercise 3hard
Add idle timeouts: close any connection that sent nothing for 30 seconds. Use CLOCK_MONOTONIC and pass the right timeout to epoll_wait.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is an event loop always faster than threads?
- No. For a few hundred connections, thread-per-connection is often just as fast and much simpler. Event loops win when you have many mostly idle connections and memory or context switches become the limit.
- What is the difference between EAGAIN and EWOULDBLOCK?
- On Linux they are the same number. POSIX allows them to differ, so portable code checks both.
- How does Node.js read files without blocking its loop?
- File operations are sent to libuv's thread pool, which blocks on disk in the background and reports the result back to the loop.
- Can I use several threads with one event loop?
- Usually you run one loop per thread, each with its own epoll instance and its own connections. Sharing one epoll between threads is possible with EPOLLONESHOT or EPOLLEXCLUSIVE but harder to get right.