Why does an edge-triggered epoll handler stall mid-request?
Question
A Linux server switches its non-blocking sockets from level-triggered (EPOLLIN) to edge-triggered (EPOLLIN | EPOLLET). A client sends a 10 KiB request in one burst. The handler reads one 4 KiB chunk and returns to epoll_wait, then the connection stalls until the client times out.
- Why does
epoll_waitstay silent while 6 KiB remain unread in the kernel buffer? - Fix
on_readableso it drains untilBlockingIOError(EAGAIN) while capping bytes per tick to avoid starving other sockets. - When should you prefer level-triggered (
EPOLLIN) instead?
def on_readable(sock, buf): # Registered with EPOLLIN | EPOLLET chunk = sock.recv(4096) if chunk: buf.extend(chunk)
Show hints (3)
- "EDGE VERSUS LEVEL"
Level-triggered fires whenever data is present. Edge-triggered (
EPOLLET) fires only when new data changes the socket state. - "DRAIN TO EAGAIN"
Loop non-blocking
recv()calls untilBlockingIOError(EAGAIN) tells you the kernel buffer is empty, orb""signals EOF. - "PREVENT PEER STARVATION"
Cap reads per tick (such as 8 KiB) and return a
"more"status so the event loop keeps that socket in its own ready list.
Show checked explanation
With EPOLLET, epoll_wait notifies only on new arrivals, not on bytes left unread in the socket buffer. Reading 4 KiB of a 10 KiB burst leaves 6 KiB stranded until the client sends more or times out. Drain non-blocking recv() in a loop until BlockingIOError (EAGAIN), close on EOF, and cap reads per tick with a ready list.
import io class BufSock(io.BytesIO): def recv(self, n): if data := self.read(n): return data raise BlockingIOError def on_readable(sock, buf, budget=8192): while budget > 0: try: chunk = sock.recv(min(4096, budget)) except BlockingIOError: return "eagain" if not chunk: sock.close() return "eof" buf.extend(chunk) budget -= len(chunk) return "more" s, b = BufSock(b"x" * 10240), bytearray() print(on_readable(s, b), len(b), on_readable(s, b), len(b))
more 8192 eagain 10240
Ran the solution and an epoll edge-vs-level state-machine simulator on CPython 3.12.10 (Windows x64); Linux epoll(7) semantics checked against man7.org. Checked by an editor other than the author.
Walkthrough
Level-triggered (EPOLLIN) asks: "Is data ready right now?" Edge-triggered (EPOLLIN | EPOLLET) asks: "Did new data arrive since the last notification?"
When all 10,240 bytes arrive in one burst, epoll_wait wakes the handler once. The buggy starter reads 4,096 bytes and returns. Because the client is now waiting for a reply, no new packets arrive. Even though 6,144 bytes sit in the kernel receive buffer, EPOLLET emits no second event, so the request hangs.
| mode | when epoll_wait wakes | unread 6,144 B after 4 KiB read | handler rule |
|---|---|---|---|
Level (EPOLLIN) | Buffer is non-empty | Wakes again on next poll | Partial read is safe |
Edge (EPOLLET) | New state change only | Silent until new packet arrives | Drain to EAGAIN or track ready |
The fixed on_readable loops non-blocking recv() calls until one of three things happens:
BlockingIOError(EAGAINorEWOULDBLOCK): the kernel buffer is truly empty. Return"eagain"so the event loop waits onepoll_waitagain.- Empty bytes (
b""): the peer closed the connection (EOF). Callsock.close()and return"eof"so the event loop drops the socket cleanly. - Per-tick
budget(8,192bytes) runs out: return"more". Asepoll(7)recommends, the event loop keeps this socket in an application ready list and serves other sockets before taking the remaining2,048bytes on tick 2.
Stick with level-triggered (EPOLLIN) by default. It makes partial reads safe, avoids missed-wakeup bugs, and matches EPOLLET performance for most workloads unless you handle huge bursts of short-lived descriptors.
Common mistakes
- Using
EPOLLETon a blocking socket. The drain loop callsrecv()after the last byte and blocks forever, freezing every other connection on that event loop. - Draining without a per-tick cap on a fast streaming client. A noisy socket that refills its buffer continuously can starve all other connections.
- Treating an empty
b""return fromrecv()asEAGAIN. Empty bytes mean peer EOF; failing to close the socket leaks file descriptors or causes a tight infinite loop. - Stopping after a partial
send()underEPOLLOUT | EPOLLET. Keep writing until your send buffer is empty orsend()raisesEAGAIN; only afterEAGAINwill the kernel fire the next write edge.
Follow-up questions
- "If new data arrives while you are already inside the drain loop, can you miss it?" Not if you loop until
EAGAIN. Any bytes that arrive beforerecv()returnsEAGAINget read in the same loop. Bytes that arrive afterEAGAINtrigger a fresh edge event inepoll_wait. - "What happens if multiple worker threads call
epoll_waiton the sameEPOLLETsocket?" New packets arriving mid-read can wake a second thread for the same socket, causing concurrent reads and scrambled bytes. AddEPOLLONESHOTso the kernel disables the descriptor after one wakeup until the worker re-arms it withepoll_ctl. - "Why does
epollscale better thanselectorpollfor 50,000 mostly idle sockets?"selectandpollcopy and scan all 50,000 descriptors on every call (O(N)), andselectcaps descriptor numbers atFD_SETSIZE(usually 1,024).epoll_waitreturns only the ready list (O(ready)).
What a strong answer covers
Contrasts edge state transitions with level readiness and explains why 6 KiB strand under EPOLLET. Drains non-blocking recv() to EAGAIN with EOF checks and a per-tick cap, and names level-triggered as the safer default.
Open in interactive practice deck →