1. The reply that waits for the client to ask again
A service that answers in 0.14 ms at the median begins answering in 200.6 ms after one line of code changes. Nothing else about the deployment moves: the same kernel, the same client, the same exchange of 12,288 bytes each way, and the same CPU graph, which stays near 0.07 seconds for the whole run. The dashboard shows a latency that has become a flat plateau rather than a distribution, no error rate, no queue depth, and a server doing nothing at all while it waits.
The plateau is one client poll interval per unread buffer. The server in table 1’s second row takes one 4 KiB buffer of the request per readiness event, on a socket registered edge-triggered, and the remaining 8 KiB of the 12 KiB request stay in the receive queue. The reply is an echo, so those bytes are also the end of the reply: there is nothing to send until they are read. What moves them is the client’s ping every 100 ms, the keep-alive of a reused connection – each byte is a new chunk on the server’s socket, and a new chunk is what an edge-triggered entry is reported for. One unread buffer per ping, so the reply ends two intervals late.
| Server | Reads per event | p50 | p99 | Slowest of 150 | Read calls |
|---|---|---|---|---|---|
| level-triggered | one buffer | 0.14 ms | 0.32 ms | 0.40 ms | 120 |
| edge, read once | one buffer | 200.6 ms | 201.0 ms | 201.1 ms | 120 |
| edge, drained | to EAGAIN | 0.09 ms | 0.46 ms | 0.46 ms | 150 |
TL;DR – the flag changes the contract, not the speed
- The delay. One 4 KiB read per event leaves 8 KiB of a 12 KiB request unread, and the echo finishes 200.6 ms after the request against 0.09 ms for the same loop draining to EAGAIN.
- What moves it, and what does not. One new byte re-reports the entry even with the buffer still full – 1 report at 8,193 bytes queued – and nothing else does: with the pings removed, the same server delivered 4,096 of 12,288 bytes and stopped.
- The cost of the fix. Draining to EAGAIN reads 1.0 MiB in 18 calls at a 64 KiB buffer, 266 at 4 KiB and 1,030 at 1,024 bytes.
- The second lever. Draining without a ceiling lets one connection hold the loop for 5.44 ms while every other waits; a 64 KiB budget returns it in 0.02 ms.
2. Two contracts behind one flag
An interest set is a row in the kernel’s table, keyed by file descriptor, holding the mask the caller asked for. The mask is not the contract; the flag is. A level mask means “report this descriptor while the condition holds”, so a socket with data left in it is placed in the ready list on every call. An edge mask means “report what happens to it”: the socket’s wait queue wakes the entry when a byte arrives, when the peer shuts its half down, or when the socket takes an error, and the entry joins the ready list once per wake-up – unless it is already there, in which case the arrival is folded into the report waiting to be collected.
The report therefore belongs to the arrival, not to the buffer. Two things follow, and this page is about the second. Bytes a reader leaves behind have no report of their own: announcing them was the job of the report it already collected. And a byte that arrives later announces the entry again even if earlier bytes were never read, which the manual states as a property – “even with edge-triggered epoll, multiple events can be generated upon receipt of multiple chunks of data”. Probe 12 measures both sides on one socket pair, 5 times per arm. With 8,192 bytes queued and nothing new arriving, the entry produced 0 reports in the next 100 ms. One byte from the peer produced 1, a mask of EPOLLIN, with 8,193 bytes still queued. Three one-byte arrivals produced 3 reports, one per arrival, and the queue after each of those reads held 4,097, 2 and 0 bytes; two bytes written before the wait were reported once, and the next byte was reported again.
"""The registration masks, and the two ways to ask the kernel for them.
An interest set is not a setting on the socket: it is an entry in one kernel table, keyed by
the file descriptor, and every mask this module builds is a statement about *when* the
kernel should place that descriptor in the ready list. Level-triggered means "while", and
edge-triggered means "when it changes", so the same event bits mean two different
contracts depending on one flag.
"""
from __future__ import annotations
import select
READ = select.EPOLLIN
WRITE = select.EPOLLOUT
PEER_SHUTDOWN = select.EPOLLRDHUP
HANGUP = select.EPOLLHUP
ERROR = select.EPOLLERR
ONESHOT = select.EPOLLONESHOT
EDGE = select.EPOLLET
WATCH = READ | PEER_SHUTDOWN
def arm(epoll: select.epoll, fd: int, *, edge: bool = True, oneshot: bool = False,
write: bool = False) -> int:
"""Register ``fd`` for reads and return the mask that was registered.
``oneshot`` is not a tuning knob: the kernel disables the entry after the first event,
so a caller that does not call :func:`rearm` receives exactly one notification per
registration and no error to tell it the rest of the stream was dropped.
"""
mask = WATCH
if write:
mask |= WRITE
if edge:
mask |= EDGE
if oneshot:
mask |= ONESHOT
epoll.register(fd, mask)
return mask
def rearm(epoll: select.epoll, fd: int, mask: int) -> None:
"""Put a one-shot entry back into the table with the mask it had before."""
epoll.modify(fd, mask)
def describe(mask: int) -> str:
"""The mask as the names a reader sees in strace output."""
names = [name for bit, name in ((READ, "EPOLLIN"), (WRITE, "EPOLLOUT"),
(PEER_SHUTDOWN, "EPOLLRDHUP"), (HANGUP, "EPOLLHUP"),
(ERROR, "EPOLLERR"), (EDGE, "EPOLLET"),
(ONESHOT, "EPOLLONESHOT"))
if mask & bit]
return "|".join(names) if names else "0"
That is why the discipline is to drain before waiting, and the reason is about who owns the information. The event says “this socket became readable”; it does not say “and it will keep telling you”. Only EAGAIN says the buffer is empty, and only the reader can produce it, so a loop that stops at one buffer has to be woken by traffic it does not control – which in a request-response exchange arrives only when the client sends something, and the client is waiting for the answer.
The mask this page registers is readability and the peer’s half-close, and describe prints it back as the names a reader sees in a trace: 8,193 is EPOLLIN|EPOLLRDHUP. Writability is deliberately absent: a socket with room in its send buffer is writable almost always, so an entry that asks for it is reported on every call and the loop spins – the defect section 10 measures from the other side. rearm exists for the one-shot case in section 7 and takes the mask the registration used, so a re-arm cannot silently drop the half-close bit.
Python’s binding has no data pointer. The C interface carries a 64-bit data word with every registration and returns it with every event, so a loop written in C can hand itself the object that owns the descriptor without a lookup. This binding’s register takes the descriptor and the mask and nothing else – the documentation says it “Registers a new fd or raises an OSError if the fd is already registered.” – so a Python loop keeps the map itself, and poll returns “as a list of (fd, events) 2-tuples.”
What the ready list is, and why one entry can be in it for two reasons
epoll keeps a set of interest entries attached to a file object, and a ready list that holds entries rather than events. A callback from the file’s wait queue marks an entry ready and adds it to the list; epoll_wait walks as much of the list as maxevents allows and reports what it finds. Because the list holds the entry, not the event, an entry that becomes ready for two reasons at once – data arrived and the peer then closed – is reported once, with both bits set. That is why a mask is read as a set of facts rather than as a verdict, and why a reader that only tests the read bit never sees the close.
The edge flag decides when an entry may join that list, and the rule is about the list rather than about the buffer: an entry already waiting to be collected absorbs further arrivals, and a collected entry is added again by the next one. The window between two reports is therefore the time the entry spent off the list – one wake-up for a busy socket, not one buffer’s worth of bytes. A level-triggered entry is instead re-checked and put back by epoll_wait while its condition holds, which is the cost edge-triggering avoids and the safety net that hides a partial read. The bits themselves are plain integers, quoted here because an operator reads them in a trace: readable 1, writable 4, error 8, hang-up 16, peer half-close 8,192, one-shot 1,073,741,824 and edge 2,147,483,648 – this host’s values, re-read at probe time.
The empty read is the other half of the contract, and the one Python makes easy to get wrong. A blocking socket’s recv returns an empty bytes object at end of stream, and a non-blocking socket raises BlockingIOError instead of returning nothing; the documentation of recv says “When the remote end is closed and all data is read, return the empty string.”. A loop that treats every empty result as the end of the connection closes on a socket that simply had nothing more to give – and a loop that treats BlockingIOError as the end of the buffer is right, which is why the exception is the signal to wait on and the empty string the signal to retire.
3. What was measured, and what was only read
Every number on this page comes from a probe in the tree, and every probe ran 5 times per arm on one guest of a virtualized host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 vCPUs in the affinity mask, and no cgroup quota file to read. The connection is loopback TCP where the question is about a server and a socket pair where it is about a single buffer: a pair stops accepting at 233,152 bytes and a loopback connection at 2,615,232, which is why the fairness probe uses TCP and the stall probes use the pair.
"""Shared helpers for the probes: percentiles, a loopback pair, and one way to save output.
Every probe writes one JSON file into ``results/``. The article reads only those files, so a
figure that is not in one of them cannot reach the page, and the file name fixes the order
the page's tables refer to.
"""
from __future__ import annotations
import socket
def tcp_pair() -> tuple[socket.socket, socket.socket]:
"""A connected loopback pair, both ends blocking until the caller changes that."""
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
client = socket.create_connection(listener.getsockname(), timeout=5)
server, _ = listener.accept()
listener.close()
return client, server
Two kinds of statement are kept apart. A sentence in the present tense with a figure is a measurement of this host in this session; a sentence about what the kernel interface guarantees is a description of the interface, and the article says so where it uses one. The distinction matters at the tail: 200.6 ms is this guest’s median, and a guest whose client polls every 100 ms cannot produce any other median, because the number is arithmetic rather than luck.
| Fact | Value | Read from |
|---|---|---|
| kernel | 6.12.118-guest-1.1 | uname, probe 01 |
| CPython | 3.12.16 | platform, probe 01 |
| vCPUs in the affinity mask | 2 | sched_getaffinity |
| socket pair capacity | 233,152 bytes | send until EAGAIN |
| loopback capacity | 2,615,232 bytes | send until EAGAIN |
| somaxconn | 4096 | /proc/sys/net/core |
| tcp_rmem | 4096 131072 6291456 | /proc/sys/net/ipv4 |
| tcp_wmem | 4096 16384 4194304 | /proc/sys/net/ipv4 |
| steal time during probe 01 | 0.00% of all CPU time | /proc/stat |
| open file limit | 1,024 | getrlimit |
Three limits on the method belong here, because they decide which figures can be compared. One guest with two vCPUs cannot produce a tail that needs a busy machine, so none is claimed. The call counts in section 5 are the reader’s own count of recv calls, and the kernel’s counter cannot corroborate them: /proc/self/io‘s syscr is incremented on the read path that serves read and readv, while a socket read through recv enters the socket layer’s recvfrom and never reaches it. Probe 11 reads the same 1.0 MiB both ways: 1,030 recv calls moved the counter by 0, and the same bytes through os.read moved it by 1,030. No probe here crosses a network, so nothing on this page is a statement about a real NIC or a load balancer’s buffer.
4. The stall, counted in bytes and in events
The first probe removes the server, the client and the network from the question. 8 socket pairs each queue 3 buffers of 4,096 bytes, and one reader serves them all with the same four lines: wait for events, and take one buffer for each event it gets. The only difference between the two runs is the flag in the registration.
"""Probe 02: one burst through the same reader, registered two ways.
Eight connections receive three buffers each before the loop runs once. The reader in both
arms is the same four-line loop: wait, then read one buffer per event. Nothing about the
application changes between the arms - only the flag in the registration - so the counts
separate the kernel's promise from the reader's behaviour.
"""
from __future__ import annotations
import select
import socket
import time
import probe
def run_arm(edge: bool, sockets: int = SOCKETS) -> dict:
pairs = [socket.socketpair() for _ in range(sockets)]
epoll = select.epoll()
try:
for reader, writer in pairs:
reader.setblocking(False)
writer.setblocking(False)
mask = select.EPOLLIN | (select.EPOLLET if edge else 0)
epoll.register(reader.fileno(), mask)
for _ in range(BUFFERS):
writer.sendall(b"x" * SIZE)
events = 0
delivered = 0
start = time.perf_counter()
while True:
ready = epoll.poll(0.05)
if not ready:
break
for fd, _mask in ready:
reader = next(r for r, _ in pairs if r.fileno() == fd)
events += 1
try:
data = reader.recv(SIZE)
except BlockingIOError:
continue
delivered += len(data)
wall = time.perf_counter() - start
remaining = sum(probe.drain_all(reader) for reader, _ in pairs)
return {"delivered": delivered, "events": events, "remaining": remaining,
"wall_ms": wall * 1000.0,
"bytes_per_event": delivered / events if events else 0}
finally:
epoll.close()
for reader, writer in pairs:
reader.close()
writer.close()
| Registration | Delivered | Events | Still queued | Bytes per event |
|---|---|---|---|---|
| level-triggered | 98,304 | 24 | 0 | 4,096 |
| edge-triggered | 32,768 | 8 | 65,536 | 4,096 |
Both arms take exactly the same number of bytes per event, 4,096, because both readers use the same buffer. What differs is how many events the kernel produces: 24 for the level registration – one per buffer, since each socket is reported again on the next call – and 8 for the edge registration, one per socket. The edge reader therefore stops at 32,768 bytes of the 98,304 queued, and 67% of the burst – 65,536 bytes – is left in the receive buffers. No peer writes again in this probe, so section 2’s rule has nothing to report and those bytes are still there when the loop stops.
The single-connection version turns those bytes into a delay. One pair queues 12,288 bytes, the edge reader takes 4,096 on the first pass, and the remaining 8 KiB wait for the next arrival. With a heartbeat every 100 ms the reply takes 2 beats and 200.5 ms to finish, against 17 µs for the same loop draining to EAGAIN and 11 µs for the level registration. Halving the heartbeat halves the delay – 100.4 ms at 50 ms – because the cost is one arrival per unread buffer, and the arrival rate is whatever the client’s patience is set to.
Take the pings away and the delay becomes a wait with no end. Probe 07 runs the same server against a client that sends its request and then listens, which is what a real one does: 4,096 of 12,288 bytes arrived, the first of them 0.13 ms after the request went out, and nothing else did for the 300 ms the client was willing to wait. That is the shape this failure takes in production: a request that hangs after its first chunk, a connection that stays open, and a server with an idle CPU and a full receive queue.
The event counts are the part worth carrying into a capacity plan. A level registration turns one queued buffer into one event per wait, so a service produces wake-ups proportional to the bytes it receives rather than to the connections it serves; an edge registration produces one per connection per arrival, and the difference is invisible until a client stops sending.
Production SRE Note: The delay is not a timeout and does not need one to appear: 2 beats is 2 pauses of 100 ms. A client that polls every second sees one second; a client that never polls sees nothing, until its own timeout closes a connection the server believed was healthy.
Why the buffers are this size, and what a socket pair will hold
The 4,096-byte buffer is not arbitrary: it is one page on this host, 4,096 bytes from probe 01, and it is what every reader passes because Python’s recv has no default size. The reply is 3 of them – enough that the first read cannot empty the queue, few enough that the whole reply fits in one pair, which accepts 233,152 bytes before the sender is told to stop. A probe that queued a megabyte there would measure the sender’s block instead of the reader’s loop. The TCP pair in section 6 accepts 2,615,232 bytes for the opposite reason, and the gap between the two is the send buffer’s autotuning rather than anything the application sets.
The empty read at the end costs a call in every arm of section 5. That call is the proof that the buffer is empty, and it is the only proof the kernel offers in the read path: FIONREAD reports what is queued without removing any of it, which makes it the right question for a detector and the wrong one for a reader.
5. What draining to EAGAIN costs
The fix for the stall is one loop: read until the kernel refuses. The price of that loop is syscalls, and the count is decided by the buffer size, not by the number of bytes. 1.0 MiB arrives on a loopback connection and is read at three buffer sizes, plus once more with a read that stops after the first buffer, on the same non-blocking socket.
"""Reading until the kernel says stop, and asking how much is still there.
An edge-triggered entry is a report about an arrival, and the report is spent when the caller
collects it: the bytes it announced stay readable whether or not they were read, and nothing
announces them again until something new happens to the socket. So the only question a reader
can settle by itself is whether the buffer is empty, and the one answer the kernel gives is
``recv`` raising ``BlockingIOError`` - EAGAIN. Stopping earlier is not an optimisation; it is
a wake-up left to the peer's next packet, and the data left in the receive buffer waits for a
byte that may never come.
"""
from __future__ import annotations
import socket
from dataclasses import dataclass, field
CHUNK = 65536
@dataclass
class Drain:
"""The outcome of one attempt to empty a socket."""
data: bytes = b""
reads: int = 0
exhausted: bool = False # the last read ended in EAGAIN, not in EOF
closed: bool = False # the stream is over, by FIN or by the socket's error
reset: bool = False # it ended because recv raised, not because it returned b""
budget_hit: bool = False # stopped on our own limit, not on EAGAIN
@property
def size(self) -> int:
return len(self.data)
@dataclass
class Budget:
"""A ceiling on how much one connection may take out of the loop in one pass.
The budget is the fairness knob an edge-triggered loop needs and a level-triggered one
gets for free: without it, one connection with a full 4 MiB buffer keeps the loop in a
single ``drain`` call while every other connection waits. With it the connection comes
back like any other - a level-triggered entry because the kernel reports it again while
its buffer holds data, an edge-triggered one because the caller kept it on its own
held-over list, which is the one piece of bookkeeping this dataclass cannot do alone.
"""
limit: int = 1 << 20
chunk: int = CHUNK
taken: int = field(default=0)
def left(self) -> int:
return max(0, self.limit - self.taken)
def read_once(sock: socket.socket, chunk: int = CHUNK) -> Drain:
"""One ``recv``. Never raises for a non-blocking socket that has finished.
Two endings arrive without a byte, and only one of them is a return value: the peer's
FIN comes back as an empty ``bytes``, and a reset the peer sent comes back as
``ConnectionResetError`` from the next read. Both mean the stream is over, and only
``EAGAIN`` means the caller should wait for an event.
"""
try:
data = sock.recv(chunk)
except BlockingIOError:
return Drain(exhausted=True, reads=1)
except (ConnectionResetError, ConnectionAbortedError):
return Drain(closed=True, reset=True, reads=1)
if not data:
return Drain(closed=True, reads=1)
return Drain(data=data, reads=1)
def to_eagain(sock: socket.socket, chunk: int = CHUNK, budget: Budget | None = None) -> Drain:
"""Read until EAGAIN, EOF or the budget, and report which of the three stopped it.
``exhausted`` is the only flag that licenses the caller to wait for the next event: it
is the kernel's confirmation that the buffer is empty. A ``budget_hit`` is the opposite,
and a caller that treats the two alike has just built the stall this page is about.
"""
box = budget or Budget(limit=1 << 62, chunk=chunk)
total = Drain()
while True:
room = min(box.chunk, box.left())
if room <= 0: # the ceiling was reached, so read nothing
total.budget_hit = True
return total
step = read_once(sock, room)
total.reads += step.reads
if step.closed:
total.closed = True
total.reset = step.reset
return total
if step.exhausted:
total.exhausted = True
return total
total.data += step.data
box.taken += step.size
if box.taken >= box.limit:
total.budget_hit = True
return total
| Buffer | Read calls | Delivered | Throughput | Per byte | CPU |
|---|---|---|---|---|---|
| 1,024 B | 1,030 | 1,048,576 | 32.3 MB/s | 31.0 ns | 31.9 ms |
| 4,096 B | 266 | 1,048,576 | 130.2 MB/s | 7.7 ns | 8.0 ms |
| 65,536 B | 18 | 1,048,576 | 723.0 MB/s | 1.4 ns | 0.0 ms |
| one read | 1 | 4,096 (0.39%) | – | – | – |
The ratio is worth stating in calls rather than in bytes, because calls are what a loop pays for. 1.0 MiB at 1,024 bytes costs 1,030 calls, at 4,096 bytes 266 and at 65,536 bytes 18. Dividing the size by the buffer gives a floor rather than the count, and the measurement sits above it for the two smaller buffers, because a stream sometimes hands back less than was asked for and each short read costs another call. One call in every arm is the final EAGAIN: the confirmation that the buffer is empty, and the only cue the reader controls.
The throughput gap is large enough to be surprising on a loopback connection that copies rather than sends: 32.3 MB/s against 723.0 MB/s. It is per-call overhead, not bandwidth – every call crosses into the kernel, looks up the file, copies what is queued and returns – which is why a service that drains one buffer per event can look CPU-bound while moving very little data. The other side of the same choice is memory: the buffer is allocated per read here, so 65,536 bytes per connection in flight is a number worth writing down.
The last caution is about fairness. Draining to EAGAIN is exactly the loop a fair scheduler cannot interrupt – the kernel is not consulted again until the read refuses – so the budget in the next section is not an optimisation of this one. It is what keeps this one from becoming the stall it replaces, in the other direction.
6. A budget, and who waits while one connection drains
Draining to EAGAIN fixes the stall and creates a different question: for how long may one connection hold the loop? The kernel answers readiness for every socket in the table, but a pass serves them one at a time, so a connection with a large buffer and no ceiling is one every other socket waits behind. 100 connections of 1,024 bytes measure the batching side, and one connection with 2.0 MiB queued measures the cost of a single turn.
| Arm | Waits | Masks | Taken in one turn | Left queued | Turn |
|---|---|---|---|---|---|
| 100 sockets, 16 per wait | 7 | 100 | – | – | – |
| 100 sockets, 100 per wait | 1 | 100 | – | – | – |
| 100 sockets, level, 16 per wait | 7 | 100 | – | – | – |
| 2 MiB, no budget | – | – | 2,097,152 | 0 | 5.44 ms |
| 2 MiB, 64 KiB budget | – | – | 65,536 | 128,704 | 0.02 ms |
maxevents and both registrations: the events are the same and the waits are not, which is the syscall the setting buys. The last two rows serve one 2.0 MiB connection and time the turn it takes.The batching result is the easy half. A hundred sockets that are all readable at once come back in rounds whenever the limit is below their number, so the loop needs 7 waits to hear about all 100 at the smaller limit and 1 when the limit is their whole number. The level registration needs the same 7 waits for its first pass and then keeps reporting sockets that still hold bytes, which is why its pass count is a floor rather than a cost.
The fairness result is the half that matters. One connection with 2.0 MiB queued, drained without a ceiling, holds the loop for 5.44 ms and takes all of it in a single call. The same connection with a 64 KiB budget holds the loop for 0.02 ms – 242.0× shorter – and leaves 128,704 bytes in the queue for its next turn. The remaining 1,902,912 bytes were not in the queue when the turn ended: they were still in the sender’s send buffer, waiting for the reader to make room, so the two figures are one turn’s worth of a stream rather than a subtraction. The turn is what the other connections in the probe wait behind.
from __future__ import annotations
from . import drain
def _service(self, connection: Connection, *, final: bool = False) -> None:
"""Read one connection to EAGAIN, EOF or its budget, and book the outcome.
A budget normally ends the turn and leaves the rest of the buffer for the next pass,
because the kernel has more to say about a live connection. ``final`` is the case
where it does not: the mask already said the connection is over, so this is the last
turn it will ever get. A ceiling there would keep the bytes behind it, and the loop
would retire the entry with them - the tail of the response, dropped by the one rule
that exists to prevent exactly that. With ``final`` the read repeats until the stream
itself ends, so the ceiling shapes the work per call and no longer bounds it.
"""
connection.events += 1
while True:
box = drain.Budget(limit=self.limit, chunk=self.chunk)
result = drain.to_eagain(connection.sock, self.chunk, box)
connection.last_size = result.size
connection.delivered += result.size
self.stats.bytes_read += result.size
if result.closed:
connection.closed = True
self.stats.closed += 1
self.drop(connection)
return
if not result.budget_hit:
return
connection.budget_hits += 1
self.stats.budget_hits += 1
if not final:
if self.edge and connection not in self.pending:
self.pending.append(connection)
return
The lines after the read are the whole of the budget’s contract. A read that ends on the ceiling is not a completed drain, so the connection goes back on a list that the next pass services before it waits at all – which is why the loop’s first action is to serve what it held over, and why timeout is forced to zero when that list is not empty. A connection that ends on EAGAIN is finished with its buffer and waits for the kernel like any other. Getting those two cases the wrong way round produces one of the two failures this page measures: treat a ceiling as a drain and the stall returns with a budget in front of it; treat a drain as a ceiling and the loop spins on a socket with nothing left to give.
The final argument is the exception, and it exists because a connection the kernel has finished with gets no next turn: a hang-up mask arrives once, so a ceiling there would leave the rest of the buffer in a socket nobody will ask about again. The loop keeps reading until the stream itself ends, which is a bound the kernel supplies; section 8 walks through the case, and the test suite probe 09 records is what pins it. A pass is otherwise three lists, and their order is the scheduler: what was held over first, because its work is known; the events the wait returned second, in the order the kernel listed them, which the application does not control; and whatever stopped on its budget goes back on the first list.
Production SRE Note: A ceiling and an empty buffer are different answers and the loop has to tell them apart. In this tree that is Drain.budget_hit against Drain.exhausted, set by the same call and never both, because the read that hits the ceiling has not yet seen EAGAIN (11) and the read that sees it has nothing left to prove.
What a fair budget costs, and the setting it replaces
The budget divides a connection’s work into turns of 64 KiB. A 2.0 MiB buffer therefore needs 32 turns instead of one, and each turn costs a wait the loop would otherwise have spent sleeping – a wait that returns immediately, because the entry is still ready. The alternative is a smaller maxevents, and the two are not equivalent: maxevents decides how many connections one wait may report, while the budget decides how much one of them may take. A loop with a large maxevents and no budget still serves the large connection first and completely, so the setting that looks like fairness is only batching.
What the budget cannot fix is a reader that never reaches EAGAIN because the sender keeps writing faster than the reader reads. That connection is not stalled, it is saturated, and the answer there is backpressure – a smaller receive window, a pause in the producer, a separate worker – rather than a bigger budget.
7. One-shot entries: one event, then silence
A one-shot registration is the deliberate version of this page’s failure. The kernel reports the entry once and then disables it, which is what a thread pool wants – one worker owns the connection until it decides to hand it back – and the shape of a permanent stall when the hand-back is forgotten. There is no error, no closed socket and no counter: the entry is still in the table, it simply no longer produces events. It differs from section 2’s case in where the silence comes from: an edge entry is reported again by the next arrival, a one-shot entry by nothing until it is modified.
| Step | Entry | Events returned |
|---|---|---|
| register, then write one byte | armed | 1 |
| read the byte, write another | disabled | 0 |
call modify with the same mask | armed again | 1 |
The re-arm is one call, and where it sits in the worker is the whole of the pattern: read first, re-arm after, and hand the connection back only once it has been re-armed. Reading first is what keeps the socket to one reader – the entry is disabled for the whole of the read, so a second worker cannot be woken on the same descriptor while the first is taking bytes out of it. The fear that re-arming late loses whatever arrived in the meantime is the one thing one-shot does not do: modify re-checks the condition as it arms, so a byte that landed during the read makes the entry ready immediately. Table 6’s third row is that claim tested.
- One-shot is not edge-triggering with fewer events. An edge entry is reported again by the next arrival; a one-shot entry is out of the ready set until it is modified, so the two fail differently and are diagnosed differently.
- The state is in the kernel, not in the object. A connection that has been one-shot and not re-armed looks identical from Python: the same descriptor, socket and buffer. The only evidence is that
pollstops returning it whileFIONREADreports bytes – the 4,096 bytes of a reply that arrived, and nothing after it.
8. How a connection ends, and the bits that say so
A peer can finish politely with a FIN, vanish with a reset, or be reported through a mask that carries the close beside the data that arrived before it. Each case is measured here with the mask the kernel actually returned – the integers are what an operator sees in a trace – and with the number of times the entry is reported again, which decides whether a loop retires the connection or spins on it.
| Case | First mask | Name | First read | Reported again |
|---|---|---|---|---|
FIN, watched with EPOLLRDHUP | 8,193 | EPOLLIN|EPOLLRDHUP | 10 bytes, then EOF | 0 |
| FIN, read bit only | 1 | EPOLLIN | 10 bytes, then EOF | 0 |
TCP reset, watched with EPOLLRDHUP | 8,217 | EPOLLIN|EPOLLRDHUP|EPOLLHUP|EPOLLERR | data:10, then ECONNRESET | 0 |
| TCP reset, read bit only | 25 | EPOLLIN|EPOLLHUP|EPOLLERR | data:10, then ECONNRESET | 0 |
| peer close with bytes queued | 8,209 | EPOLLIN|EPOLLRDHUP|EPOLLHUP | 10 bytes, then EOF | – |
| the same FIN, level-triggered, 5 polls | 17 | EPOLLIN|EPOLLHUP | reported 5 times | – |
EPOLLERR bit the resets carry and the closes do not. The last row is the spin: a finished connection under a level registration is reported on every call until removed.Those integers look arbitrary and are not. The peer half-close is 8,192, readability 1, the hang-up 16 and the error bit 8, so 8,193 is 8,192 + 1: a half-close beside data, which is what shutdown on the sending side produces. The peer close with bytes queued is 8,209, the same sum plus 16 – a whole socket gone rather than one direction – and the reset logged with the half-close watched is 8,217, that sum plus 8. The gap between the first and fifth rows is therefore not a different kind of data but how much of the connection the peer took with it.
The close bits arrive beside the read bit rather than instead of it, and that ordering is what a loop must respect. A socket whose peer has closed can still hold bytes that were sent before the close – 10 of them above, read normally – so a loop that retires on the first hang-up throws away the end of a response. The rule this tree’s loop follows is to drain when the mask is terminal and readable, and only then to remove the entry.
from __future__ import annotations
from . import events
def run_once(self, timeout: float = 0.05) -> list[Connection]:
"""One pass: the connections held over from last time, then one ``epoll_wait``.
Events a diagnostic looked at with :meth:`stalls` are served here first, so a check
cannot cost the connections it did not ask about their wake-up.
"""
served: list[Connection] = []
held, self.pending = self.pending, []
for connection in held:
if not connection.retired:
self._service(connection)
served.append(connection)
waiting, self.peeked = self.peeked, []
if (held or waiting) and timeout > 0:
timeout = 0.0 # work is already in hand; do not sleep on it
self.stats.waits += 1
for fd, mask in waiting + self.epoll.poll(timeout, self.max_events):
connection = self.connections.get(fd)
if connection is None:
continue
self.stats.masks += 1
verdict = events.classify(mask)
# A hang-up can arrive with bytes still queued: the peer is finished, the data it
# sent is not. Reading once more before retiring the entry is the difference
# between losing the tail of a response and returning it.
if verdict.terminal and not verdict.readable:
self.drop(connection)
continue
if verdict.readable:
self._service(connection, final=verdict.terminal)
if connection not in served:
served.append(connection)
if verdict.terminal and not connection.retired:
# A readable terminal entry that ended on EAGAIN has an empty buffer, so
# the drop here costs nothing; one that ended on EOF has already retired
# itself inside _service.
self.drop(connection)
return served
The second half of that rule is easy to state and easy to miss. Draining a terminal connection is still subject to section 6’s budget, and the kernel reports a finished entry exactly once. A hang-up arriving with 4,000 bytes queued and a 1,024-byte budget is four turns of work and one report: a naive loop reads the first turn, books a ceiling, and retires the entry on the terminal mask – with three turns of the peer’s data still in the socket, no error, and nothing left to report them. The final argument is the fix: when the mask already said the connection is over, the read repeats until the stream ends, and the budget shapes the work per call without ending it.
A harness can afford the opposite order and the four servers behind table 1 do: a finished connection is retired there without a read, because the question they answer is how much of the request one read takes, and a client they are done with is not part of it. That is a harness, not a service – and the buffer a harness drops is the one an operator sees as a truncated response.
Three facts about the masks are worth stating plainly. EPOLLERR is not a property of losing the peer but of the socket’s error state: the reset rows carry it (8,217 and 25) and the close row does not (8,209), because a reset leaves an error for the next call and a FIN leaves none. That error is what the read finds rather than what the mask says: after the queued bytes, the next read raised ECONNRESET instead of returning an empty string, which is why read_once treats the socket’s error as the end of the stream – a loop that only knows about b"" raises there, in the handler of a connection it had just served correctly. And EPOLLRDHUP changes nothing about what is readable: the delta between watching it and not is 8,192, one bit, so the flag is a convenience for the half-close case and not the mechanism behind it.
The practical consequence is a rule about ordering rather than about masks: the read comes first, the retirement second, and the mask decides whether a read is owed. A loop that inverts those steps loses exactly one buffer per closed connection – the last one – the defect a client sees as a truncated JSON document or a checksum mismatch on the final chunk, and a server log records as nothing at all.
Production SRE Note: A level registration on a finished connection is the spin in table 7’s last row: 5 reports over 5 calls, and no timeout was involved because the condition never became false. An edge registration reports it once, which is why the same defect that hides a stall also hides a dead connection until something else notices.
Reading a mask as a set of facts, not as a verdict
The bits this page quotes are independent: readable 1, writable 4, error 8, hang-up 16, and the peer half-close 8,192. One event can carry any combination, and the combination is the message: 8,209 is readability beside a hang-up, which means bytes are available on a finished connection.
The order the facts are acted on matters more than the order they are printed in. A hang-up retires the entry, but only after the bytes that arrived with it; a peer half-close is a fact about one direction and leaves the socket writable; readability is the only fact that leads to a read. The tests in this tree pin the combinations rather than the integers: classify is checked against every mask the five bits can form, so a refactor that folds two bits into one verdict fails a test instead of a service.
9. The reply size decides how many times you pay
The stall is charged per arrival, so the beats a reply needs are the buffers it holds beyond the first. Four replies are measured with the same naive reader and a 20 ms beat, and the beat count is what an operator multiplies by their own client interval to predict the latency of a payload they already know.
"""Reading until the kernel says stop, and asking how much is still there.
An edge-triggered entry is a report about an arrival, and the report is spent when the caller
collects it: the bytes it announced stay readable whether or not they were read, and nothing
announces them again until something new happens to the socket. So the only question a reader
can settle by itself is whether the buffer is empty, and the one answer the kernel gives is
``recv`` raising ``BlockingIOError`` - EAGAIN. Stopping earlier is not an optimisation; it is
a wake-up left to the peer's next packet, and the data left in the receive buffer waits for a
byte that may never come.
"""
from __future__ import annotations
import fcntl
import socket
import sys
import termios
def queued_bytes(sock: socket.socket) -> int:
"""Bytes already in the receive buffer, without reading one of them.
``FIONREAD`` is the answer to the question an incident produces - "the socket is in the
table and no event arrives, so is there anything to read?" A positive count beside an
empty ready list is the signature of a registration that is waiting for a transition it
has already reported, and no timeout, backlog or network counter will show it.
"""
raw = fcntl.ioctl(sock.fileno(), termios.FIONREAD, b"\0\0\0\0")
return int.from_bytes(raw, sys.byteorder)
| Reply | First pass | Beats needed | Latency | Complete |
|---|---|---|---|---|
| 4,096 B | 4,096 | 0 | 5 µs | yes |
| 12,288 B | 4,096 | 2 | 40.3 ms | yes |
| 65,536 B | 4,096 | 15 | 302.2 ms | yes |
| 131,072 B | 4,096 | 31 | 624.5 ms | yes |
The shape is arithmetic rather than a property of this host: a reply of 65,536 bytes read one buffer at a time needs 15 arrivals of the client’s interval, and the 302.2 ms in the table is that count at 20 ms. What the measurement adds is the confirmation that the count is exactly the buffer count and not a bounded tail: 31 beats for 131,072 bytes is the same rule at twice the size.
The practical use is the other direction: the table predicts what a service will see for the payloads it actually sends. A small JSON reply that fits in one buffer never shows the bug, which is why it survives code review and a staging environment where every fixture is short. A CSV export, a log tail, a generated PDF or a fetch of a few hundred kilobytes does – and the first report will describe a feature that works for the first page and hangs afterwards, at a size that looks like a limit in the code and is the reader’s buffer.
- Bytes in the queue, not bytes sent. The reader’s buffer size decides how much is left, so the same payload is fine for a client that reads a large buffer at a time and a stall for one that reads a page.
- The threshold is one buffer. A reply of exactly the reader’s buffer size leaves nothing behind and behaves; the case that fails is the one with a byte more than the reader took, which is why the boundary is the value worth testing rather than a round number.
FIONREADon a connection between requests answers it in one ioctl: a nonzero count beside an empty ready list is the defect.
10. What the loop costs when nothing happens
An idle loop still has to choose how long to sleep, and the choice is the difference between a service that uses a fraction of a core and one that spins. The three settings below are the three a real service uses: block until an event, wake every millisecond, and never sleep. The sockets are registered and silent in all three arms, so only the waiting is measured.
| Timeout | Waits in one second | CPU of one core |
|---|---|---|
| 0 ms | 2,492,153 | 98.7% |
| 1 ms | 918 | 2.4% |
| 50 ms | 20 | 0.2% |
epoll_wait calls it made before its second ran out, so the waits column is a rate – calls per second, per loop, on one core – not a total over the five runs. The CPU column is process CPU time as a share of one core, so the first row is a core spent on asking and the last is 513.1× less. No arm saw an event.The two failures this page measures meet in this table. A socket reported once and never drained looks, to the loop, exactly like a socket with nothing to say: no event arrives, so the loop sleeps. A level-triggered socket that is finished and never retired looks like the opposite – an event on every call – so the loop ends up at the first row, 98.7% of a core, with no request in flight. Both are visible in the same two counters, waits per second and CPU per wait, and neither needs the latency percentile the incident started with.
The timeout is a stop-flag check as much as a sleep
A loop that blocks on epoll_wait with an infinite timeout cannot notice a shutdown request, and the safest value is the longest delay the process can afford between checks. At 50 ms the loop spent 0.2% of a core. A flag set by a signal handler is read at the next wake-up rather than when the signal lands, because the binding retries a call a signal interrupted and recomputes the timeout (PEP 475): the timeout, not the signal, bounds the delay. The same number is the granularity of every timer the loop owns, so a timeout larger than the shortest deadline in the service adds that much lateness to it.
The measurement is blind to the cost of the wake-up itself: 50 entries is a small table, and a loop with far more would spend more per call on the walk. What the table shows is the ratio, and the ratio decides whether a busy loop is a bug or a style.
11. The order to fix it in
The levers on this page are not alternatives to debate; they are steps in an order, cheapest first, each decided by a number from a different table. The order matters because the later steps change how the loop is written, and because most services are fixed by the first two.
- Prove the stall before changing anything. Look for a socket whose receive queue holds bytes –
FIONREADanswers 8,192 in the case this page opened with – while the ready list is empty. A full queue beside no event is the finding; a latency percentile alone is not, because it cannot tell an edge-triggered partial read from a slow database. - Drain to EAGAIN in the reader. Read until the kernel refuses, and treat
EAGAINas the only signal that the buffer is empty. At a 65,536 byte buffer that is 18 calls per 1.0 MiB, against 1,030 calls at the smallest buffer measured here. - Put a budget on the drain. A ceiling of 64 KiB returns the loop in 0.02 ms where an unbounded drain of the same 2.0 MiB held it for 5.44 ms; the rest of that buffer comes back on the next pass, which is the contract section 6 prints.
- Handle the hang-up after the read, and re-arm a one-shot at the hand-back. A mask that carries the close beside the data still has bytes to give – 10 of them here – so retire the connection after that read and not before, and let that last read run past the budget: the entry is reported once, so bytes left behind it are lost rather than delayed. A one-shot entry stays silent until
modifyre-arms it, and the re-arm belongs after the read, so the connection never has two readers. - Watch the loop, not only the requests. A stalled socket and a spinning level registration cost the same counter in opposite ways: no wait with data queued, or 918 waits a second with nothing queued. Both are visible in waits per second and CPU per wait, which is why those two belong on the same dashboard as the latency this page started with.
Verifying the fix is step one run again, on the same connection, buffer size and client interval: a reply that took 200.6 ms at the median should take 0.09 ms, and the queue behind step one should read zero on an idle connection. A change that shortens the tail and leaves bytes queued has moved the stall rather than removed it – and if step one finds an empty queue on the connection that was slow, the registration is not the cause and the investigation belongs upstream or in the client.
Production SRE Note: The buffer size is the one setting not to change without a measurement: 1,024 against 65,536 bytes is 22.4× in throughput, and the same gap is memory the process holds per connection in flight.
12. What these numbers are not
The claims on this page are narrow enough to check, and this section states the boundary so a reader can tell which of them travel. Every arm ran on one guest of a shared machine: a virtualized Linux kernel, release 6.12.118-guest-1.1, with 2 vCPUs visible and no cgroup quota to read. Nothing crossed a network, and the hypervisor took 0.00% of the guest’s CPU time during probe 01’s sample.
- One guest, two vCPUs. A loop’s cost per call is a function of the table size and the syscall path, both of which a different kernel would move. The byte counts and the beat counts are properties of the protocol and would survive a different host; the microsecond figures would not.
- Loopback only. A real NIC adds segmentation, a send queue and a round-trip time, so the 200.6 ms plateau would be joined by whatever the network contributes. The plateau itself, one client interval per unread buffer, is independent of the network.
- The client interval is a parameter. The headline latency is 100 ms of client politeness multiplied by the number of unread buffers, not a constant: at 20 ms the same shape produces table 8. A client that does not poll at all does not see a slow reply – it sees the first buffer and then nothing, which is what probe 07 measures with the pings removed.
- The call counts are the reader’s own.
/proc/self/io‘ssyscrcounts read-family calls that go through the VFS, and a socket read throughrecvtakes the socket layer’srecvfrominstead, so the counter moved by 0 across the 1,030 reads of probe 11 and by 1,030 when the same bytes went throughos.read. The syscall columns are the loop’s count, corroborated by the CPU time they produce and by that second arm rather than by a tracer: no tracing tool is installed on this guest, so the cross-check is the same read through the other syscall. - Only the Linux interface is measured. The same idea exists in kqueue and in IOCP with different rules for when an edge is announced, and this page says nothing about either. That the contract is “report what happens” is the portable part; the bit values quoted here are this host’s.
- The appendix is the code the prose walks through. Five module files, the shared probe plumbing and four probes – the ones a section quotes or a table rests on – are printed whole; the other eight, which fill the remaining tables, the test record and the syscall cross-check, are named by number and left in the tree, and no test is reproduced.
None of those boundaries changes the fix: a reader still drains to EAGAIN before it waits, a loop still needs a budget so one connection cannot hold the turn, and a connection still has to be retired on a hang-up after the bytes that came with it have been read. A different host changes the cost of those three decisions, not which three they are.
Frequently asked questions
Why does an edge-triggered socket go quiet with data still in its buffer?
Because the report it was given belonged to the arrival, not to the buffer. The first bytes made the entry ready and were reported once; the reader took one buffer and left 8,192 behind, and nothing announces those again by itself – probe 12 saw 0 further reports in 100 ms, while one new byte reported them at once with 8,193 bytes still queued. So the next report depends on traffic the reader does not control: read until EAGAIN before waiting.
Is a level-triggered socket safe then?
Safe from this failure and not free of cost. It is reported again on the next call while the buffer holds data, which is why it delivered 98,304 bytes in table 3 where the edge registration delivered 32,768, and needed 24 events instead of 8 to do it. The re-check per event is the price, and a finished connection nobody retires turns it into the spin in table 7.
How much does draining to EAGAIN cost?
One read per buffer, plus the read that returns EAGAIN and the odd short read. At 65,536 bytes that is 18 calls per 1.0 MiB and 723.0 MB/s, where the same data at 1,024 bytes needs 1,030 calls and runs 22.4× slower.
Why is a budget needed if the drain already stops at EAGAIN?
Because EAGAIN arrives after the whole buffer, however large it is: a 2.0 MiB drained without a ceiling held the loop for 5.44 ms, and 64 KiB held it for 0.02 ms and came back next pass. The budget bounds the turn; the drain finishes the buffer each turn was given.
Does EPOLLRDHUP replace the read that discovers the end of stream?
No. It adds one bit to the mask – the delta in table 7 between watching the half-close and not is 8,192 – and says the peer has finished sending, not that the buffer is empty. Bytes that arrived before the close are still readable, which is why the hang-up is handled after the read and that last read runs past the budget.
Why did a one-shot registration stop delivering events with no error?
Because a one-shot entry is disabled after its first event and stays disabled until modify is called. Table 6 shows the sequence: 1 event, then 0 on the next write, then 1 after the re-arm. The entry is still in the table, so nothing reports it as broken.
How do I tell this apart from a slow upstream?
A slow upstream leaves the receive queue empty: the server has nothing to read, so the loop sleeps and the latency is the upstream’s. This failure leaves the queue full: FIONREAD answers a positive number while the ready list is empty, and the server’s CPU is idle. One ioctl separates the two, which is why it is the first step of section 11.
A client that sends its request and then waits – what does it see?
The first buffer of the reply and nothing else. Probe 07 sends 12,288 bytes, waits 300 ms without sending another, and received 4,096 bytes: no error, no close, no further event. In production that is a request that hangs until the client’s own timeout, and a server whose every counter says the connection is healthy.
Appendix: the code this article ran
Ten files are printed whole below: the edgedrive package – its __init__.py and the four modules that make it one importable package – the shared probe plumbing, and the four probes whose code a section quotes or a table rests on: probe 12 for section 2’s re-report, probe 03 for section 4’s heartbeats, probe 07 for Table 1 and the silent client, and probe 08 for Table 9. A module appears in full even where a section above has shown one of its functions, which is why the drain loop in section 5 and the loop pass in section 8 read as excerpts beside the whole file. No line of the ten is elided.
What is not here is as much a part of the statement. The tree holds 12 probes; the other eight are not reprinted, and each is named where its figures are used: probe 01 for Table 2, probe 02 for Table 3, probe 04 for Table 4, probe 06 for Table 5, probe 05 for the one-shot and mask tables, probe 10 for the reply sizes, probe 09 for the test record, and probe 11 for the syscall cross-check. The tests are absent for the same reason – they are a file of the same tree – and the final argument in section 8 is one behaviour they pin.
What the package exports, in one place __init__.py
"""The pieces this page's probes and tests import: masks, verdicts, drains and a loop."""
from __future__ import annotations
from .drain import CHUNK, Budget, Drain, queued_bytes, read_once, to_eagain
from .events import Readiness, classify, mask_of
from .interest import (EDGE, ERROR, HANGUP, ONESHOT, PEER_SHUTDOWN, READ, WATCH, WRITE, arm,
describe, level, rearm)
from .watcher import Connection, EdgeWatcher, Stats
__all__ = [
"CHUNK", "Budget", "Connection", "Drain", "EDGE", "ERROR", "EdgeWatcher", "HANGUP",
"ONESHOT", "PEER_SHUTDOWN", "READ", "Readiness", "Stats", "WATCH", "WRITE", "arm",
"classify", "describe", "level", "mask_of", "queued_bytes", "read_once", "rearm",
"to_eagain",
]
The masks, the two registrations and the name for a mask interest.py
"""The registration masks, and the two ways to ask the kernel for them.
An interest set is not a setting on the socket: it is an entry in one kernel table, keyed by
the file descriptor, and every mask this module builds is a statement about *when* the
kernel should place that descriptor in the ready list. Level-triggered means "while", and
edge-triggered means "when it changes", so the same event bits mean two different
contracts depending on one flag.
"""
from __future__ import annotations
import select
READ = select.EPOLLIN
WRITE = select.EPOLLOUT
PEER_SHUTDOWN = select.EPOLLRDHUP
HANGUP = select.EPOLLHUP
ERROR = select.EPOLLERR
ONESHOT = select.EPOLLONESHOT
EDGE = select.EPOLLET
# Every socket this project watches is watched for readability and for the peer's half-close.
# EPOLLOUT is not in the mask: a writable socket is writable almost always, so asking for it
# turns the descriptor into a permanently ready entry and the loop into a spin.
WATCH = READ | PEER_SHUTDOWN
def arm(epoll: select.epoll, fd: int, *, edge: bool = True, oneshot: bool = False,
write: bool = False) -> int:
"""Register ``fd`` for reads and return the mask that was registered.
``oneshot`` is not a tuning knob: the kernel disables the entry after the first event,
so a caller that does not call :func:`rearm` receives exactly one notification per
registration and no error to tell it the rest of the stream was dropped.
"""
mask = WATCH
if write:
mask |= WRITE
if edge:
mask |= EDGE
if oneshot:
mask |= ONESHOT
epoll.register(fd, mask)
return mask
def rearm(epoll: select.epoll, fd: int, mask: int) -> None:
"""Put a one-shot entry back into the table with the mask it had before."""
epoll.modify(fd, mask)
def level(epoll: select.epoll, fd: int) -> int:
"""Register ``fd`` the way a level-triggered loop does: no edge, no one-shot."""
return arm(epoll, fd, edge=False)
def describe(mask: int) -> str:
"""The mask as the names a reader sees in strace output."""
names = [name for bit, name in ((READ, "EPOLLIN"), (WRITE, "EPOLLOUT"),
(PEER_SHUTDOWN, "EPOLLRDHUP"), (HANGUP, "EPOLLHUP"),
(ERROR, "EPOLLERR"), (EDGE, "EPOLLET"),
(ONESHOT, "EPOLLONESHOT"))
if mask & bit]
return "|".join(names) if names else "0"
One mask read as independent facts events.py
"""What one returned event means, and the order those meanings have to be read in.
The kernel hands back a bit mask, not a verdict. Two of its bits are not requests to read:
EPOLLERR reports that the socket has an error queued, and EPOLLHUP reports that both
directions are gone. A watcher that folds every mask into "readable" runs ``recv`` on a
socket whose peer has already vanished, and one that ignores the close bits never removes
the descriptor from the table, so a level-triggered loop returns it again on the very next
call - the busy loop that shows up as a hundred percent of one core with no traffic.
"""
from __future__ import annotations
from dataclasses import dataclass
from . import interest
@dataclass(frozen=True)
class Readiness:
"""The parts of one event mask this project acts on, in the order it acts on them."""
error: bool = False
hangup: bool = False
peer_shutdown: bool = False
readable: bool = False
writable: bool = False
@property
def terminal(self) -> bool:
"""True when the connection cannot carry another byte in either direction."""
return self.error or self.hangup
def classify(mask: int) -> Readiness:
"""Read one mask. Every bit is reported; nothing is inferred from a missing one.
A mask that carries EPOLLIN beside EPOLLHUP is not a request to read a live stream: it
means the bytes already queued can still be read and the connection is finished, which
is why the close bits are reported beside the read bit rather than instead of it.
"""
return Readiness(
error=bool(mask & interest.ERROR),
hangup=bool(mask & interest.HANGUP),
peer_shutdown=bool(mask & interest.PEER_SHUTDOWN),
readable=bool(mask & interest.READ),
writable=bool(mask & interest.WRITE),
)
def mask_of(readiness: Readiness) -> int:
"""The mask that would produce this verdict, for the tests and the probe output."""
mask = 0
for flag, bit in ((readiness.error, interest.ERROR), (readiness.hangup, interest.HANGUP),
(readiness.peer_shutdown, interest.PEER_SHUTDOWN),
(readiness.readable, interest.READ),
(readiness.writable, interest.WRITE)):
if flag:
mask |= bit
return mask
Reading to EAGAIN, the budget, and how much is queued drain.py
"""Reading until the kernel says stop, and asking how much is still there.
An edge-triggered entry is a report about an arrival, and the report is spent when the caller
collects it: the bytes it announced stay readable whether or not they were read, and nothing
announces them again until something new happens to the socket. So the only question a reader
can settle by itself is whether the buffer is empty, and the one answer the kernel gives is
``recv`` raising ``BlockingIOError`` - EAGAIN. Stopping earlier is not an optimisation; it is
a wake-up left to the peer's next packet, and the data left in the receive buffer waits for a
byte that may never come.
"""
from __future__ import annotations
import fcntl
import socket
import sys
import termios
from dataclasses import dataclass, field
# 64 KiB is one pipe buffer and two default socket buffers: few enough calls that the
# per-call cost of recv disappears beside the copy, small enough that a 4 MiB burst does not
# pin a megabyte of Python heap in one connection's read.
CHUNK = 65536
@dataclass
class Drain:
"""The outcome of one attempt to empty a socket."""
data: bytes = b""
reads: int = 0
exhausted: bool = False # the last read ended in EAGAIN, not in EOF
closed: bool = False # the stream is over, by FIN or by the socket's error
reset: bool = False # it ended because recv raised, not because it returned b""
budget_hit: bool = False # stopped on our own limit, not on EAGAIN
@property
def size(self) -> int:
return len(self.data)
@dataclass
class Budget:
"""A ceiling on how much one connection may take out of the loop in one pass.
The budget is the fairness knob an edge-triggered loop needs and a level-triggered one
gets for free: without it, one connection with a full 4 MiB buffer keeps the loop in a
single ``drain`` call while every other connection waits. With it the connection comes
back like any other - a level-triggered entry because the kernel reports it again while
its buffer holds data, an edge-triggered one because the caller kept it on its own
held-over list, which is the one piece of bookkeeping this dataclass cannot do alone.
"""
limit: int = 1 << 20
chunk: int = CHUNK
taken: int = field(default=0)
def left(self) -> int:
return max(0, self.limit - self.taken)
def read_once(sock: socket.socket, chunk: int = CHUNK) -> Drain:
"""One ``recv``. Never raises for a non-blocking socket that has finished.
Two endings arrive without a byte, and only one of them is a return value: the peer's
FIN comes back as an empty ``bytes``, and a reset the peer sent comes back as
``ConnectionResetError`` from the next read. Both mean the stream is over, and only
``EAGAIN`` means the caller should wait for an event.
"""
try:
data = sock.recv(chunk)
except BlockingIOError:
return Drain(exhausted=True, reads=1)
except (ConnectionResetError, ConnectionAbortedError):
return Drain(closed=True, reset=True, reads=1)
if not data:
return Drain(closed=True, reads=1)
return Drain(data=data, reads=1)
def to_eagain(sock: socket.socket, chunk: int = CHUNK, budget: Budget | None = None) -> Drain:
"""Read until EAGAIN, EOF or the budget, and report which of the three stopped it.
``exhausted`` is the only flag that licenses the caller to wait for the next event: it
is the kernel's confirmation that the buffer is empty. A ``budget_hit`` is the opposite,
and a caller that treats the two alike has just built the stall this page is about.
"""
box = budget or Budget(limit=1 << 62, chunk=chunk)
total = Drain()
while True:
room = min(box.chunk, box.left())
if room <= 0: # the ceiling was reached, so read nothing
total.budget_hit = True
return total
step = read_once(sock, room)
total.reads += step.reads
if step.closed:
total.closed = True
total.reset = step.reset
return total
if step.exhausted:
total.exhausted = True
return total
total.data += step.data
box.taken += step.size
if box.taken >= box.limit:
total.budget_hit = True
return total
def queued_bytes(sock: socket.socket) -> int:
"""Bytes already in the receive buffer, without reading one of them.
``FIONREAD`` is the answer to the question an incident produces - "the socket is in the
table and no event arrives, so is there anything to read?" A positive count beside an
empty ready list is the signature of a registration that is waiting for a transition it
has already reported, and no timeout, backlog or network counter will show it.
"""
raw = fcntl.ioctl(sock.fileno(), termios.FIONREAD, b"\0\0\0\0")
return int.from_bytes(raw, sys.byteorder)
The loop, its held-over work and its stall check watcher.py
"""A small edge-triggered loop that keeps the one promise edge-triggering asks for.
The loop here exists to be measured, but it is written the way the article says a loop
should be: it reads to EAGAIN, it treats a budget that stopped it early as unfinished work
rather than as an empty socket, and it removes a connection when the kernel reports the
connection is over instead of waiting for a read that returns nothing. Those three rules are
each one line, and each of them is the difference between a working watcher and a socket
that goes quiet while its buffer is full.
"""
from __future__ import annotations
import select
import socket
import time
from dataclasses import dataclass, field
from . import drain, events, interest
@dataclass(eq=False)
class Connection:
"""One registered socket and what the loop has done with it.
Compared and hashed by identity: two connections are the same connection when they are
the same object, not when their counters happen to agree.
"""
sock: socket.socket
fd: int
edge: bool = True
delivered: int = 0
events: int = 0
budget_hits: int = 0
closed: bool = False
retired: bool = False
last_size: int = 0
@dataclass
class Stats:
waits: int = 0
masks: int = 0
bytes_read: int = 0
budget_hits: int = 0
closed: int = 0
stalls: int = 0
history: list = field(default_factory=list)
class EdgeWatcher:
"""The epoll set, its connections and the three rules in the module docstring."""
def __init__(self, *, edge: bool = True, chunk: int = drain.CHUNK,
limit: int = 1 << 20, max_events: int = 16) -> None:
self.epoll = select.epoll()
self.edge = edge
self.chunk = chunk
self.limit = limit
self.max_events = max_events
self.connections: dict[int, Connection] = {}
self.pending: list[Connection] = []
self.peeked: list[tuple[int, int]] = []
self.stats = Stats()
def add(self, sock: socket.socket) -> Connection:
sock.setblocking(False)
fd = sock.fileno()
interest.arm(self.epoll, fd, edge=self.edge)
connection = Connection(sock=sock, fd=fd, edge=self.edge)
self.connections[fd] = connection
return connection
def drop(self, connection: Connection) -> None:
if connection.retired:
return
try:
self.epoll.unregister(connection.fd)
except (KeyError, ValueError, OSError):
pass
connection.retired = True
self.connections.pop(connection.fd, None)
def _service(self, connection: Connection, *, final: bool = False) -> None:
"""Read one connection to EAGAIN, EOF or its budget, and book the outcome.
A budget normally ends the turn and leaves the rest of the buffer for the next pass,
because the kernel has more to say about a live connection. ``final`` is the case
where it does not: the mask already said the connection is over, so this is the last
turn it will ever get. A ceiling there would keep the bytes behind it, and the loop
would retire the entry with them - the tail of the response, dropped by the one rule
that exists to prevent exactly that. With ``final`` the read repeats until the stream
itself ends, so the ceiling shapes the work per call and no longer bounds it.
"""
connection.events += 1
while True:
box = drain.Budget(limit=self.limit, chunk=self.chunk)
result = drain.to_eagain(connection.sock, self.chunk, box)
connection.last_size = result.size
connection.delivered += result.size
self.stats.bytes_read += result.size
if result.closed:
connection.closed = True
self.stats.closed += 1
self.drop(connection)
return
if not result.budget_hit:
return
connection.budget_hits += 1
self.stats.budget_hits += 1
if not final:
if self.edge and connection not in self.pending:
self.pending.append(connection)
return
def run_once(self, timeout: float = 0.05) -> list[Connection]:
"""One pass: the connections held over from last time, then one ``epoll_wait``.
Events a diagnostic looked at with :meth:`stalls` are served here first, so a check
cannot cost the connections it did not ask about their wake-up.
"""
served: list[Connection] = []
held, self.pending = self.pending, []
for connection in held:
if not connection.retired:
self._service(connection)
served.append(connection)
waiting, self.peeked = self.peeked, []
if (held or waiting) and timeout > 0:
timeout = 0.0 # work is already in hand; do not sleep on it
self.stats.waits += 1
for fd, mask in waiting + self.epoll.poll(timeout, self.max_events):
connection = self.connections.get(fd)
if connection is None:
continue
self.stats.masks += 1
verdict = events.classify(mask)
# A hang-up can arrive with bytes still queued: the peer is finished, the data it
# sent is not. Reading once more before retiring the entry is the difference
# between losing the tail of a response and returning it.
if verdict.terminal and not verdict.readable:
self.drop(connection)
continue
if verdict.readable:
self._service(connection, final=verdict.terminal)
if connection not in served:
served.append(connection)
if verdict.terminal and not connection.retired:
# A readable terminal entry that ended on EAGAIN has an empty buffer, so
# the drop here costs nothing; one that ended on EOF has already retired
# itself inside _service.
self.drop(connection)
return served
def pump(self, seconds: float, timeout: float = 0.05) -> int:
"""Run the loop for a wall-clock budget and return the number of events served."""
deadline = time.monotonic() + seconds
served = 0
while time.monotonic() < deadline:
served += len(self.run_once(min(timeout, max(0.0, deadline - time.monotonic()))))
return served
def stalls(self) -> list[Connection]:
"""Connections whose buffer still holds bytes that no event is going to report.
This is the check an operator can run on a live process: ``FIONREAD`` is a direct
question to the kernel, so a positive answer beside an empty ready list can only
mean the registration is not going to report it. Seeing the ready list costs one
``poll``, so it is read once for the whole table rather than once per connection,
and the events it returned are handed to the next pass instead of being thrown
away - a stall check that swallowed another connection's wake-up would be the bug
it is looking for.
"""
ready = self.epoll.poll(0, self.max_events)
self.peeked.extend(ready)
reporting = {fd for fd, _mask in ready}
found = [connection for connection in self.connections.values()
if not connection.retired and connection.fd not in reporting
and drain.queued_bytes(connection.sock) > 0]
self.stats.stalls += len(found)
return found
def close(self) -> None:
for connection in list(self.connections.values()):
self.drop(connection)
try:
connection.sock.close()
except OSError:
pass
self.epoll.close()
Percentiles, the loopback pair and one JSON file probe.py
"""Shared helpers for the probes: percentiles, a loopback pair, and one way to save output.
Every probe writes one JSON file into ``results/``. The article reads only those files, so a
figure that is not in one of them cannot reach the page, and the file name fixes the order
the page's tables refer to.
"""
from __future__ import annotations
import json
import os
import pathlib
import platform
import socket
import statistics
import time
SANDBOX = pathlib.Path(__file__).resolve().parent
HERE = SANDBOX.parent
RESULTS = HERE / "results"
CHUNK = 65536
def percentiles(samples: list[float]) -> dict:
"""The five numbers the article quotes, from one list of samples."""
ordered = sorted(samples)
if not ordered:
return {"count": 0}
def pick(fraction: float) -> float:
index = min(len(ordered) - 1, max(0, int(round(fraction * (len(ordered) - 1)))))
return ordered[index]
return {
"count": len(ordered),
"min": ordered[0],
"p50": pick(0.50),
"p90": pick(0.90),
"p95": pick(0.95),
"p99": pick(0.99),
"max": ordered[-1],
"mean": statistics.fmean(ordered),
}
def describe(name: str, samples: list[float]) -> dict:
"""One arm: its name, its samples and the summary the page reads."""
summary = percentiles(samples)
summary["samples"] = len(samples)
return {"name": name, **summary}
def tcp_pair() -> tuple[socket.socket, socket.socket]:
"""A connected loopback pair, both ends blocking until the caller changes that."""
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
client = socket.create_connection(listener.getsockname(), timeout=5)
server, _ = listener.accept()
listener.close()
return client, server
def fill(sock: socket.socket, size: int, chunk: int = CHUNK) -> int:
"""Write until the socket refuses, and report how much went out."""
sent = 0
while sent < size:
try:
sent += sock.send(b"x" * min(chunk, size - sent))
except BlockingIOError:
break
return sent
def drain_all(sock: socket.socket, chunk: int = CHUNK) -> int:
"""Read until EAGAIN and report the byte count."""
total = 0
while True:
try:
data = sock.recv(chunk)
except BlockingIOError:
return total
if not data:
return total
total += len(data)
def rchar() -> int:
"""Bytes this process has read through read-family calls, from /proc/self/io.
A counter the kernel keeps is a better witness than a counter this code keeps: it says
the syscalls happened, not that the loop believes they did.
"""
for line in pathlib.Path("/proc/self/io").read_text().splitlines():
if line.startswith("rchar:"):
return int(line.split()[1])
return 0
def read_syscalls() -> int:
"""Read-family calls this process has made, from /proc/self/io.
One ``os.read`` of the file, so reading the counter costs exactly one call of the kind
the counter counts - which is what makes the subtraction in probe 11 exact.
"""
handle = os.open("/proc/self/io", os.O_RDONLY)
try:
text = os.read(handle, 4096).decode()
finally:
os.close(handle)
for line in text.splitlines():
if line.startswith("syscr:"):
return int(line.split()[1])
return 0
def cpu() -> tuple[float, float]:
"""(process CPU seconds, wall seconds) as one reading, for a delta."""
return time.process_time(), time.monotonic()
def elapsed(start: tuple[float, float]) -> dict:
"""The CPU and wall time spent since ``start``, with the share CPU took of one core."""
used = time.process_time() - start[0]
wall = time.monotonic() - start[1]
return {"cpu_s": used, "wall_s": wall, "cpu_pct": 100.0 * used / wall if wall else 0.0}
def save(name: str, payload: dict) -> None:
RESULTS.mkdir(exist_ok=True)
(RESULTS / name).write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
def host_facts() -> dict:
"""The conditions every probe ran under, read from the host rather than assumed."""
release = platform.release()
facts = {
"kernel": release,
"machine": platform.machine(),
"python": platform.python_version(),
"cpu_count": os.cpu_count(),
"affinity": len(os.sched_getaffinity(0)),
"page_size": os.sysconf("SC_PAGE_SIZE"),
"clock_resolution_ns": time.get_clock_info("monotonic").resolution * 1e9,
}
for key, path in (("somaxconn", "/proc/sys/net/core/somaxconn"),
("rmem_max", "/proc/sys/net/core/rmem_max"),
("wmem_max", "/proc/sys/net/core/wmem_max"),
("tcp_rmem", "/proc/sys/net/ipv4/tcp_rmem"),
("tcp_wmem", "/proc/sys/net/ipv4/tcp_wmem")):
try:
facts[key] = pathlib.Path(path).read_text().strip()
except OSError:
facts[key] = ""
facts["epoll_flags"] = {
name: int(getattr(socket, name, 0)) for name in
("EPOLLIN", "EPOLLOUT", "EPOLLERR", "EPOLLHUP", "EPOLLET", "EPOLLONESHOT",
"EPOLLRDHUP")
}
facts["import_epoll_flags"] = {
name: int(getattr(__import__("select"), name, 0)) for name in
("EPOLLIN", "EPOLLOUT", "EPOLLERR", "EPOLLHUP", "EPOLLET", "EPOLLONESHOT",
"EPOLLRDHUP")
}
facts["rlimit_nofile"] = list(__import__("resource").getrlimit(__import__("resource").RLIMIT_NOFILE))
return facts
The stall in heartbeats at two client intervals – section 4 03_stall.py
"""Probe 03: the stall, its price, and three registrations that answer it differently.
Each round queues a three-buffer reply, lets the reader take what the kernel will report, and
then runs a heartbeat at a fixed interval - the next keep-alive, poll or request a real
client sends. The number of heartbeats a reply needs is the number of round trips the
registration adds to it, and the latency column is that count multiplied by the interval the
client happens to use, which is why the same bug costs half as much at 50 ms.
The beat is counted on the reply's own bytes, not on the buffer's: the heartbeat byte is
appended behind whatever is queued, so a reader that has taken a heartbeat has not thereby
taken the reply, and a round that counted the two together would report one beat more than
the client waits.
"""
from __future__ import annotations
import select
import socket
import sys
import time
import probe
sys.path.insert(0, str(probe.HERE / "module"))
from edgedrive import Budget, queued_bytes, to_eagain # noqa: E402
BUFFERS = 3
SIZE = 4096
REPLY = BUFFERS * SIZE
ROUNDS = 10
REPEATS = 5
MAX_HEARTBEATS = 8
ARMS = {"level": (False, False, 0.1), "edge": (True, False, 0.1),
"edge_50ms": (True, False, 0.05), "drain": (True, False, 0.1)}
def register(epoll: select.epoll, fd: int, edge: bool, oneshot: bool) -> None:
mask = select.EPOLLIN
if edge:
mask |= select.EPOLLET
if oneshot:
mask |= select.EPOLLONESHOT
epoll.register(fd, mask)
def take(reader: socket.socket, arm: str) -> bytes:
"""Read the way the named arm's application reads one readiness event."""
if arm == "drain":
result = to_eagain(reader, chunk=SIZE, budget=Budget(limit=1 << 20, chunk=SIZE))
return result.data
try:
return reader.recv(SIZE)
except BlockingIOError:
return b""
def one_round(arm: str) -> dict:
edge, oneshot, heartbeat = ARMS[arm]
reader, writer = socket.socketpair()
epoll = select.epoll()
try:
reader.setblocking(False)
writer.setblocking(False)
register(epoll, reader.fileno(), edge, oneshot)
for _ in range(BUFFERS):
writer.sendall(b"x" * SIZE)
start = time.perf_counter()
reply = 0
while True:
ready = epoll.poll(0) # a pass ends when the table is empty
if not ready:
break
for _fd, _mask in ready:
reply += take(reader, arm).count(b"x")
immediate = reply
queued_at_stall = queued_bytes(reader)
elapsed = (time.perf_counter() - start) * 1000.0
beats = 0
while reply < REPLY and beats < MAX_HEARTBEATS:
time.sleep(heartbeat)
writer.send(b"h") # the client's next tick
beats += 1
if epoll.poll(0.05):
reply += take(reader, arm).count(b"x")
queued_at_stall = queued_bytes(reader)
if reply >= REPLY:
elapsed = (time.perf_counter() - start) * 1000.0
return {"immediate": immediate, "delivered": reply, "beats": beats,
"complete": int(reply >= REPLY), "total_ms": elapsed,
"queued_at_stall": queued_at_stall}
finally:
epoll.close()
reader.close()
writer.close()
def main() -> None:
arms: dict[str, dict] = {}
for arm in ARMS:
runs = [one_round(arm) for _ in range(ROUNDS * REPEATS)]
arms[arm] = {
"immediate": probe.describe(arm, [run["immediate"] for run in runs]),
"delivered": probe.describe(arm, [run["delivered"] for run in runs]),
"beats": probe.describe(arm, [run["beats"] for run in runs]),
"complete": probe.describe(arm, [run["complete"] for run in runs]),
"total_ms": probe.describe(arm, [run["total_ms"] for run in runs]),
}
payload = {"probe": 3, "repeats": REPEATS, "rounds": ROUNDS, "buffers": BUFFERS,
"size": SIZE, "reply": REPLY, "max_heartbeats": MAX_HEARTBEATS,
"heartbeat_ms": ARMS["edge"][2] * 1000, "arms": arms}
probe.save("03_stall.json", payload)
for arm, data in arms.items():
print(arm, "immediate", data["immediate"]["p50"], "beats", data["beats"]["p50"],
"complete", data["complete"]["p50"], "total_ms",
round(data["total_ms"]["p50"], 2), "p99", round(data["total_ms"]["p99"], 2))
if __name__ == "__main__":
main()
Three servers and one pinging client – Table 1, and the same server with the pings removed 07_server.py
"""Probe 07: the same exchange, four servers, one client that pings while it waits.
A loopback HTTP-shaped exchange: the client sends a 12 KiB request, then sends one byte every
100 ms - the keep-alive, the poll, the next request on a kept-alive connection - until the
12 KiB reply has arrived. The servers differ in one line each: how much of the request they
read per readiness event. Nothing else changes, so the latency column is the cost of that
line.
The request is what the server under-reads, and the reply is an echo of it: the last 8 KiB of
the reply cannot exist until the last 8 KiB of the request has been read. Each of the client's
one-byte pings is a new chunk on the server's socket, and a new chunk is what an edge-triggered
entry is reported for - so the pings are what keeps the exchange moving, one stranded buffer
per ping. ``edge_once_silent`` removes them: a client that sends its request and then waits,
which is what a real one does, and the reply stops where the first read stopped.
"""
from __future__ import annotations
import select
import socket
import sys
import threading
import time
import probe
sys.path.insert(0, str(probe.HERE / "module"))
from edgedrive import Budget, to_eagain # noqa: E402
REQUEST = 3 * 4096
CHUNK = 4096
REQUESTS = 30
REPEATS = 5
PING_S = 0.1
SILENT_REQUESTS = 10
SILENT_S = 0.3
MODES = ("level", "edge_once", "edge_drain", "edge_once_silent")
class Server(threading.Thread):
"""One epoll loop, reading the way its mode says, echoing whatever it read."""
def __init__(self, mode: str) -> None:
super().__init__(daemon=True)
self.mode = mode
self.listener = socket.socket()
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind(("127.0.0.1", 0))
self.listener.listen(16)
self.listener.setblocking(False)
self.epoll = select.epoll()
self.epoll.register(self.listener.fileno(), select.EPOLLIN)
self.connections: dict[int, socket.socket] = {}
self.stop = threading.Event()
self.reads = 0
self.cpu_start = time.process_time()
@property
def address(self):
return self.listener.getsockname()
def run(self) -> None:
edge = self.mode != "level"
while not self.stop.is_set():
for fd, mask in self.epoll.poll(0.005):
if fd == self.listener.fileno():
conn, _ = self.listener.accept()
conn.setblocking(False)
self.epoll.register(conn.fileno(), select.EPOLLIN | (select.EPOLLET if edge else 0))
self.connections[conn.fileno()] = conn
continue
conn = self.connections.get(fd)
if conn is None:
continue
if mask & (select.EPOLLHUP | select.EPOLLERR):
# Minimal echo harness: section 8 covers draining before the drop.
self.retire(conn)
continue
self.serve(conn)
def serve(self, conn: socket.socket) -> None:
if self.mode == "edge_drain":
result = to_eagain(conn, chunk=CHUNK, budget=Budget(limit=1 << 20, chunk=CHUNK))
self.reads += result.reads
if result.closed:
self.retire(conn)
return
if result.size:
conn.sendall(result.data)
return
try:
data = conn.recv(CHUNK)
except BlockingIOError:
return
self.reads += 1
if not data:
self.retire(conn)
return
conn.sendall(data)
def retire(self, conn: socket.socket) -> None:
try:
self.epoll.unregister(conn.fileno())
except (KeyError, ValueError, OSError):
pass
self.connections.pop(conn.fileno(), None)
conn.close()
def shutdown(self) -> float:
self.stop.set()
self.join(timeout=2.0)
cpu = time.process_time() - self.cpu_start
for conn in list(self.connections.values()):
conn.close()
self.epoll.close()
self.listener.close()
return cpu
def one_request(address) -> float:
"""Send the request, ping every PING_S, and return the time until the reply is whole."""
client = socket.create_connection(address, timeout=5)
try:
client.setblocking(True)
start = time.perf_counter()
payload = b"q" * REQUEST
client.sendall(payload)
received = 0
next_ping = start + PING_S
while received < REQUEST:
now = time.perf_counter()
if now >= next_ping:
client.sendall(b"p")
next_ping = now + PING_S
ready, _, _ = select.select([client], [], [], max(0.0, next_ping - now))
if not ready:
continue
chunk = client.recv(65536)
if not chunk:
break
received += len(chunk)
return (time.perf_counter() - start) * 1000.0
finally:
client.close()
def one_request_silent(address) -> dict:
"""Send the request, then wait like a real client does: nothing but the reply."""
client = socket.create_connection(address, timeout=5)
try:
client.setblocking(True)
start = time.perf_counter()
client.sendall(b"q" * REQUEST)
received = 0
first_byte_ms = -1.0
deadline = start + SILENT_S
while time.perf_counter() < deadline:
ready, _, _ = select.select([client], [], [], max(0.0, deadline - time.perf_counter()))
if not ready:
continue
chunk = client.recv(65536)
if not chunk:
break
if received == 0:
first_byte_ms = (time.perf_counter() - start) * 1000.0
received += len(chunk)
return {"received": received, "first_byte_ms": first_byte_ms,
"elapsed_ms": (time.perf_counter() - start) * 1000.0,
"complete": int(received >= REQUEST)}
finally:
client.close()
def run_silent() -> dict:
"""The same server, with the client's pings removed."""
server = Server("edge_once_silent")
server.start()
try:
rounds = [one_request_silent(server.address) for _ in range(SILENT_REQUESTS)]
cpu = server.shutdown()
return {"rounds": rounds, "cpu_s": cpu, "reads": server.reads}
finally:
if server.is_alive():
server.shutdown()
def run_mode(mode: str) -> dict:
server = Server(mode)
server.start()
try:
latencies = [one_request(server.address) for _ in range(REQUESTS)]
cpu = server.shutdown()
return {"latency_ms": latencies, "cpu_s": cpu, "reads": server.reads,
"completed": sum(1 for value in latencies if value < 5000)}
finally:
if server.is_alive():
server.shutdown()
def main() -> None:
arms: dict[str, dict] = {}
for mode in MODES:
if mode == "edge_once_silent":
continue
runs = [run_mode(mode) for _ in range(REPEATS)]
samples = [value for run in runs for value in run["latency_ms"]]
arms[mode] = {
"latency_ms": probe.describe(mode, samples),
"per_run_p99": probe.describe(mode, [probe.percentiles(run["latency_ms"])["p99"]
for run in runs]),
"per_run_p50": probe.describe(mode, [probe.percentiles(run["latency_ms"])["p50"]
for run in runs]),
"cpu_s": probe.describe(mode, [run["cpu_s"] for run in runs]),
"reads": probe.describe(mode, [run["reads"] for run in runs]),
}
payload = {"probe": 7, "repeats": REPEATS, "requests": REQUESTS, "request": REQUEST,
"chunk": CHUNK, "ping_ms": PING_S * 1000, "silent_ms": SILENT_S * 1000,
"silent_requests": SILENT_REQUESTS, "arms": arms}
silent_runs = [run_silent() for _ in range(REPEATS)]
silent_rounds = [round_ for run in silent_runs for round_ in run["rounds"]]
arms["edge_once_silent"] = {
key: probe.describe("edge_once_silent", [round_[key] for round_ in silent_rounds])
for key in ("received", "first_byte_ms", "elapsed_ms", "complete")
}
arms["edge_once_silent"]["cpu_s"] = probe.describe(
"edge_once_silent", [run["cpu_s"] for run in silent_runs])
arms["edge_once_silent"]["reads"] = probe.describe(
"edge_once_silent", [run["reads"] for run in silent_runs])
probe.save("07_server.json", payload)
for name, data in arms.items():
print(name, "p50", round(data["latency_ms"]["p50"], 2) if "latency_ms" in data
else data["received"]["p50"], "reads", data["reads"]["p50"])
if __name__ == "__main__":
main()
Fifty idle sockets at three timeouts – Table 9 08_timeout.py
"""Probe 08: what a zero timeout costs when nothing is ready.
An idle loop still has to decide how long to sleep. The three settings here are the three a
real service uses: block until something happens, wake every millisecond, and never sleep at
all. The only difference between them is how much CPU the same silence costs.
"""
from __future__ import annotations
import select
import socket
import time
import probe
SOCKETS = 50
SECONDS = 1.0
REPEATS = 5
TIMEOUTS = (0.0, 0.001, 0.05)
def spin(timeout: float) -> dict:
pairs = [socket.socketpair() for _ in range(SOCKETS)]
epoll = select.epoll()
try:
for reader, _writer in pairs:
reader.setblocking(False)
epoll.register(reader.fileno(), select.EPOLLIN | select.EPOLLET)
waits = 0
start = time.process_time()
wall = time.monotonic()
while time.monotonic() - wall < SECONDS:
epoll.poll(timeout)
waits += 1
cpu = time.process_time() - start
return {"waits": waits, "cpu_s": cpu, "cpu_pct": 100.0 * cpu / SECONDS,
"waits_per_s": waits / SECONDS}
finally:
epoll.close()
for reader, writer in pairs:
reader.close()
writer.close()
def main() -> None:
arms: dict[str, dict] = {}
for timeout in TIMEOUTS:
name = f"{int(timeout * 1000)}ms"
runs = [spin(timeout) for _ in range(REPEATS)]
arms[name] = {key: probe.describe(key, [run[key] for run in runs])
for key in runs[0]}
payload = {"probe": 8, "repeats": REPEATS, "sockets": SOCKETS, "seconds": SECONDS,
"timeouts_ms": [int(value * 1000) for value in TIMEOUTS], "arms": arms}
probe.save("08_timeout.json", payload)
for name, data in arms.items():
print(name, "waits", data["waits"]["p50"], "cpu_pct",
round(data["cpu_pct"]["p50"], 1))
if __name__ == "__main__":
main()
What an edge entry reports, and what it then stays silent about – section 2 12_retrigger.py
"""Probe 12: what an edge-triggered entry reports, and what it then stays silent about.
The question is the one the article's second section turns on: after a partial read, does the
kernel report the entry again because its buffer still holds bytes, or does it report only
when something new happens to the socket? The two answers imply different bugs, so this probe
asks the kernel instead of the manual.
Four arms on one socket pair, each five times:
partial_then_quiet collect the first report, read one buffer of three, then wait 100 ms:
how many reports arrive while 8,192 bytes are still queued?
byte_after_partial the same, plus one byte from the writer: does a new arrival report the
entry even though the buffer was never emptied?
per_arrival the same partial read, then three separate one-byte arrivals, each
followed by a wait and a read: one report per arrival, or one in total?
two_before_wait two bytes written before the wait: one report for both, or two?
``queued`` is `FIONREAD` at the moment of the last count, so a report can be read beside the
bytes it is - or is not - about.
"""
from __future__ import annotations
import select
import socket
import sys
import probe
sys.path.insert(0, str(probe.HERE / "module"))
from edgedrive import describe, queued_bytes # noqa: E402
REPEATS = 5
BUFFERS = 3
CHUNK = 4096
REPLY = BUFFERS * CHUNK
WAIT_S = 0.1
FLAGS = select.EPOLLIN | select.EPOLLET
def open_pair():
"""A registered edge-triggered reader with one report already waiting for it."""
reader, writer = socket.socketpair()
reader.setblocking(False)
writer.setblocking(False)
epoll = select.epoll()
epoll.register(reader.fileno(), FLAGS)
writer.sendall(b"x" * REPLY)
return reader, writer, epoll
def reports(epoll: select.epoll, timeout: float = WAIT_S) -> list[int]:
"""Every mask one wait returns, in the order the kernel listed them."""
return [mask for _fd, mask in epoll.poll(timeout)]
def one_buffer(reader: socket.socket) -> int:
"""Exactly one read, the size the naive reader in the article uses."""
return len(reader.recv(CHUNK))
def arm_partial_then_quiet() -> dict:
reader, writer, epoll = open_pair()
try:
first = len(reports(epoll))
read = one_buffer(reader)
after = reports(epoll)
return {"first_report": first, "read": read, "reports_after_read": len(after),
"mask": after[0] if after else 0, "mask_name": describe(after[0]) if after else "0",
"queued": queued_bytes(reader)}
finally:
epoll.close()
reader.close()
writer.close()
def arm_byte_after_partial() -> dict:
reader, writer, epoll = open_pair()
try:
first = len(reports(epoll))
read = one_buffer(reader)
writer.sendall(b"z")
after = reports(epoll)
return {"first_report": first, "read": read, "reports_after_read": len(after),
"mask": after[0] if after else 0, "mask_name": describe(after[0]) if after else "0",
"queued": queued_bytes(reader)}
finally:
epoll.close()
reader.close()
writer.close()
def arm_per_arrival() -> dict:
"""Three one-byte arrivals, each waited for and each followed by one read."""
reader, writer, epoll = open_pair()
try:
first = len(reports(epoll))
one_buffer(reader)
rounds: list[int] = []
queued: list[int] = []
for _ in range(3):
writer.sendall(b"z")
rounds.append(len(reports(epoll)))
one_buffer(reader)
queued.append(queued_bytes(reader))
return {"first_report": first, "rounds": rounds, "reports": sum(rounds),
"queued_after_each_round": queued, "queued": queued_bytes(reader)}
finally:
epoll.close()
reader.close()
writer.close()
def arm_two_before_wait() -> dict:
"""Two arrivals that land before the wait: one report or two?"""
reader, writer, epoll = open_pair()
try:
first = len(reports(epoll))
one_buffer(reader)
writer.sendall(b"z")
writer.sendall(b"z")
both = len(reports(epoll))
writer.sendall(b"z")
one_more = len(reports(epoll))
return {"first_report": first, "reports_for_two_bytes": both,
"reports_for_the_next_byte": one_more, "queued": queued_bytes(reader)}
finally:
epoll.close()
reader.close()
writer.close()
ARMS = {
"partial_then_quiet": arm_partial_then_quiet,
"byte_after_partial": arm_byte_after_partial,
"per_arrival": arm_per_arrival,
"two_before_wait": arm_two_before_wait,
}
def main() -> None:
summary: dict[str, dict] = {}
for name, function in ARMS.items():
runs = [function() for _ in range(REPEATS)]
keys = runs[0].keys()
summary[name] = {
key: probe.describe(key, [float(run[key]) for run in runs])
if all(isinstance(run[key], (int, float)) for run in runs)
else runs[0][key]
for key in keys
}
# A list-valued field is kept whole (every run produced the same list), so the page
# can quote the per-round counts without a second measurement.
for key, value in runs[0].items():
if isinstance(value, list):
summary[name][key] = value
payload = {"probe": 12, "repeats": REPEATS, "buffers": BUFFERS, "chunk": CHUNK,
"reply": REPLY, "wait_ms": WAIT_S * 1000, "et_bit": select.EPOLLET,
"arms": summary}
probe.save("12_retrigger.json", payload)
for name, data in summary.items():
print(name, {key: (value.get("p50") if isinstance(value, dict) else value)
for key, value in data.items()})
if __name__ == "__main__":
main()
Take the next step
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
