Your Event Loop Is Spinning: Practical epoll Semantics on Linux
DEV Community

Your Event Loop Is Spinning: Practical epoll Semantics on Linux

A service I look after sat at 100% CPU with almost no traffic. top blamed the process. strace -c blamed nobody: the top two syscalls were epoll_wait and read, each called hundreds of thousands of times per second, and every read returned 0.

The socket was not busy. It was closed. A client had disconnected, the handler read zero bytes, treated that as "nothing yet," returned to the loop, and epoll reported the same descriptor as readable again. Immediately. Forever.

That is not a bug in epoll. It is epoll doing exactly what level-triggered readiness means: this descriptor is readable right now. A socket at end-of-file is readable right now, and it will stay readable until you remove it. read() returning 0 is not "wait", it is "done" - the peer will send nothing further.

The epoll API is three calls and a struct. The difficulty is never the API. It is the small set of rules about when a descriptor is reported, what identifies a registration, and what happens when you stop halfway.

Those rules are worth knowing precisely, because both failure modes - the busy loop above, and the silent stall in the other direction - look like application bugs and are almost always loop bugs.

Two lists, one descriptor

An epoll instance is a kernel object holding two lists:

  • the interest list: descriptors you registered with epoll_ctl()
  • the ready list: references to those descriptors that currently have I/O available

epoll_wait() pops from the ready list. That is why it scales: the work per call is proportional to what is ready, not to how many descriptors you watch. poll() and select() hand you an array and you scan it; epoll hands you only the entries that fired.

The price is memory accounting. Every registration is a kernel object, and there is a per-user cap:

cat /proc/sys/fs/epoll/max_user_watches
1801104

The limit is per real user ID, across all epoll instances on the system, and each registered descriptor costs roughly 160 bytes on a 64-bit kernel. The default is 1/25 of available low memory divided by that cost, which on this host works out to about 1.8 million registrations. Hitting it makes epoll_ctl(EPOLL_CTL_ADD) fail with ENOSPC - which is what you will see if a process with a million sockets is quietly running as root.

The registration key is a pair

The key is not the file descriptor number. It is the pair (fd number, open file description). That distinction explains three behaviors that otherwise look arbitrary:

  • Adding the same fd twice fails. EPOLL_CTL_ADD on an fd already in that instance returns EEXIST. But a dup() of it is a different fd number referring to the same open file description, so it can be added as a separate entry - useful when you want two different event masks on the same socket.
  • Closing one fd does not unregister it. The registration disappears only when all descriptors referring to the underlying open file description are closed. If a library dup()ed your socket, or a child inherited it across fork(), close() on your copy leaves the registration alive. The kernel keeps reporting events, your handler reads from a stale number, gets EBADF, and - if it treats errors as "try again" - spins.
  • Events already queued are still delivered. If a batch of 64 events contains the fd at index 13 and a handler for index 47 closes it, the queued event for 13 is still in your array. A handler that assumes "the fd in this event is valid" will dereference a freed structure. The man page calls this the event-cache pitfall; the fix is to delete from the epoll set and mark the connection dead before closing, then tolerate no-op events for dead entries.

The defensive habit: store a stable connection ID plus a generation counter in data.u64, not a bare fd. A stale event then maps to a dead ID and gets dropped instead of touching a recycled descriptor.

Level-triggered means "still true"

Level-triggered is the default and the simpler contract: if the condition holds, epoll reports it. Every time you ask. If you read 1 byte from a pipe that still has 2047 bytes, the next epoll_wait() reports it again. That is convenient - you cannot lose a wakeup - and it is exactly why a handler that fails to change the condition becomes a spin.

Two conditions in particular never clear on their own:

  • EOF. A socket whose peer has closed is readable, and read() returns 0 forever. You must EPOLL_CTL_DEL and close().
  • EPOLLERR and EPOLLHUP. These are always reported, whether or not you asked for them in events. A loop written as if (ev & EPOLLIN) handle(); will receive HUP-only events, match nothing, do no work, and return to epoll_wait(), which reports them again.

So the level-triggered discipline is short: every branch that receives an event must either consume the readiness or deregister the fd. There is no third option.

The compensating advantage is real. In level-triggered mode you may read one buffer per event and still make progress, because the kernel will tell you again. You do not have to drain. You just have to not lie to yourself about being done.

Edge-triggered means "changed"

EPOLLET flips the contract: you are notified when the state changes, not while it holds. The man page's example is the one to memorize. Register the read end of a pipe, write 2 kB, get an event, read 1 kB. The next epoll_wait() blocks - even though 1 kB is sitting in the buffer - because no new data arrived, so no new edge was generated. The process sleeps while the peer waits for a reply to data it already sent.

Edge-triggered mode only works with two rules:

  1. The fd must be non-blocking. A blocking read() on an edge-triggered fd can park the entire loop inside a handler.
  2. Drain until EAGAIN. Read in a loop until read() returns -1 with errno == EAGAIN. That is the only reliable signal that the edge has been fully consumed. For stream sockets you can sometimes use a short read as a hint that the buffer is empty, but not always - and never for datagram sockets or terminals, where a short read means one packet, not an empty queue. Draining to EAGAIN is the portable rule.

The same logic applies to accept(), and this is where edge-triggered servers most often break. Accept in a loop until accept4() returns EAGAIN. Accepting one connection per event leaves the rest in the queue with no pending edge; those clients complete the TCP handshake and then wait forever for a service that will never look at them. ss -tn shows established sockets, the backlog is non-empty, and the application looks idle. That is the silent stall that mirrors the busy loop.

Two more details worth knowing:

  • Multiple chunks of data generate multiple edges, so "one event, one read" is wrong even in edge mode. For performance you can register EPOLLIN | EPOLLOUT once at EPOLL_CTL_ADD and avoid EPOLL_CTL_MOD ping-pong - but then writability is also edge-triggered, so a partial write must be followed by writing until EAGAIN, not by waiting for the next EPOLLOUT.
  • EPOLLRDHUP is the flag that tells you the peer shut down its write side before a full close, so you can close without waiting for a read() that returns 0. It is a plain bit in glibc's <sys/epoll.h> on current releases; accept4(), which the example below uses, is the call that still needs _GNU_SOURCE.

One descriptor, several threads

Level-triggered readiness plus several threads blocked in epoll_wait() on the same instance means all of them wake for one connection - the thundering herd, and a waste of every core you own. EPOLLEXCLUSIVE (Linux 4.5+) fixes it: when several epoll instances watch the same fd, one or more of the exclusive ones is woken instead of all of them.

It comes with sharp edges that are documented but easy to miss: it may be used only with EPOLL_CTL_ADD; a later EPOLL_CTL_MOD on that same (epfd, fd) pair fails with EINVAL - permanently, because the exclusive flag is already set; combining it with EPOLLONESHOT is EINVAL; only EPOLLIN, EPOLLOUT, EPOLLWAKEUP, and EPOLLET may accompany it. If you need to change the mask of an exclusively-registered fd, you must delete and re-add it.

EPOLLONESHOT solves the other threading problem: after one delivery, the fd is disabled in the interest list and no further events are reported until you re-arm it with EPOLL_CTL_MOD. That gives you a safe handoff - worker A takes the connection, and worker B cannot receive the same readiness while A is mid-parse. The cost is discipline: every path that finishes with the connection must re-arm it, and every path that closes it must skip the re-arm, because EPOLL_CTL_MOD on a closed fd returns EBADF or ENOENT.

What epoll will not watch

Not every file descriptor is pollable in the epoll sense. On current kernels, epoll_ctl(EPOLL_CTL_ADD) on a regular file or a directory fails with EPERM. I checked on Debian 13, kernel 6.12.118:

int epfd = epoll_create1 ( 0 ) ;
int fd = open ( "/etc/hostname" , O_RDONLY ) ;
struct epoll_event ev = { . events = EPOLLIN , . data . fd = fd } ;
int rc = epoll_ctl ( epfd , EPOLL_CTL_ADD , fd , & ev ) ;
printf ( "rc=%d errno=%d (%s)\n" , rc , errno , strerror ( errno ) ) ;
rc=-1 errno=1 (Operation not permitted)

That is the kernel refusing a descriptor whose readiness is meaningless: a regular file is always ready, so "wait for it" has no answer. Watching files for changes is inotify or fanotify work, not epoll work. This also kills the tempting trick of epolling /proc files to wait for a value to change - it either fails or returns immediately, depending on the file and kernel.

Other errors worth knowing by name: EINVAL - you tried to add an epoll fd to itself; ELOOP - epoll-on-epoll nesting deeper than 5 levels, or a cycle; ENOSPC - max_user_watches reached; EINVAL from epoll_wait() - maxevents was 0 or negative.

And the timeouts: epoll_wait() takes milliseconds, -1 means block indefinitely, 0 means poll and return. The value is rounded up to the system clock granularity, so a 1 ms timeout is a hint, not a promise. If you need nanosecond resolution, epoll_pwait2() (Linux 5.11+) takes a timespec. And epoll_wait() can fail with EINTR; either retry on EINTR or block signals and read them through a signalfd in the same loop.

Put the clock in the loop

Timeouts are the other half of an event loop, and the usual implementation - pass a computed millisecond value to epoll_wait(), then recompute it after every event - is where drift and off-by-one bugs live. A timerfd is cleaner: it is a file descriptor that becomes readable when a timer expires, so the timer is just another event.

int tfd = timerfd_create ( CLOCK_MONOTONIC , TFD_NONBLOCK | TFD_CLOEXEC ) ;
struct itimerspec tick = { . it_interval = { . tv_sec = 1 , . tv_nsec = 0 } , . it_value = { . tv_sec = 1 , . tv_nsec = 0 } , } ;
timerfd_settime ( tfd , 0 , & tick , NULL ) ;
epoll_ctl ( epfd , EPOLL_CTL_ADD , tfd , & ( struct epoll_event ) { . events = EPOLLIN , . data . fd = tfd } ) ;

Reading it returns an 8-byte uint64_t with the number of expirations since the last read - so if the process was descheduled for five seconds, one read tells you five ticks passed instead of five separate wakeups. Use TFD_TIMER_ABSTIME if you want the timer pinned to a clock value rather than drifting by however long your handler took.

A loop that does not spin

Here is a complete single-file program that applies every rule above: level-triggered, non-blocking sockets, accept4() in a loop, a read loop that treats 0 as EOF, EPOLLERR / EPOLLHUP checked before the readable path, and a timerfd for reporting. It counts bytes and exits after five ticks, so it is safe to run anywhere.

#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#define MAX_EVENTS 64
#define READ_CHUNK 4096
#define MAX_CONN 1024
struct conn { uint64_t bytes ; } ;
static struct conn conns [ MAX_CONN ] ;
static uint64_t total_bytes ;
static int open_conns ;
static int add_fd ( int epfd , int fd , uint32_t events ) { struct epoll_event ev = { . events = events , . data . fd = fd } ; return epoll_ctl ( epfd , EPOLL_CTL_ADD , fd , & ev ) ; }
static void close_conn ( int epfd , int fd ) { epoll_ctl ( epfd , EPOLL_CTL_DEL , fd , NULL ) ; close ( fd ) ; conns [ fd ] . bytes = 0 ; open_conns -- ; }
/* Returns 1 if the fd is still usable, 0 on clean EOF, -1 on error. */
static int drain_conn ( int fd ) { char buf [ READ_CHUNK ] ; for ( ; ; ) { ssize_t n = read ( fd , buf , sizeof buf ) ; if ( n > 0 ) { conns [ fd ] . bytes += ( uint64_t ) n ; total_bytes += ( uint64_t ) n ; continue ; } if ( n == 0 ) return 0 ; /* peer closed: stop watching */ if ( errno == EINTR ) continue ; if ( errno == EAGAIN || errno == EWOULDBLOCK ) return 1 ; /* drained */ return - 1 ; } }
static void accept_all ( int epfd , int listener ) { for ( ; ; ) { int c = accept4 ( listener , NULL , NULL , SOCK_NONBLOCK | SOCK_CLOEXEC ) ; if ( c == - 1 ) { if ( errno == EAGAIN || errno == EWOULDBLOCK ) return ; if ( errno == EINTR ) continue ; perror ( "accept4" ) ; return ; } if ( c >= MAX_CONN ) { close ( c ) ; continue ; } conns [ c ] . bytes = 0 ; if ( add_fd ( epfd , c , EPOLLIN | EPOLLRDHUP ) == - 1 ) { perror ( "epoll_ctl ADD conn" ) ; close ( c ) ; continue ; } open_conns ++ ; } }
int main ( void ) { struct epoll_event evs [ MAX_EVENTS ] ; struct sockaddr_in addr = { . sin_family = AF_INET , . sin_port = htons ( 8080 ) , . sin_addr . s_addr = htonl ( INADDR_LOOPBACK ) , } ; int one = 1 ; signal ( SIGPIPE , SIG_IGN ) ; int epfd = epoll_create1 ( EPOLL_CLOEXEC ) ; if ( epfd == - 1 ) { perror ( "epoll_create1" ) ; return 1 ; } int listener = socket ( AF_INET , SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC , 0 ) ; if ( listener == - 1 ) { perror ( "socket" ) ; return 1 ; } setsockopt ( listener , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ; if ( bind ( listener , ( struct sockaddr * ) & addr , sizeof addr ) == - 1 ) { p
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.