If you have ever profiled a busy Python service and watched the bulk of CPU time go to scheduling rather than to your handlers, you already know the cheapest speed-up available: swap the event loop. The project people swap to is uvloop; its own README states the pitch plainly — “uvloop makes asyncio 2-4x faster” (README.rst, line 24) — and it is widely recognized that servers like Uvicorn expose a single flag to adopt it, which is why our Uvicorn source tour keeps meeting this library at the edge. Nothing about your application code changes, because uvloop implements the same asyncio interfaces.

The pain point is not adoption, it is comprehension. Open the repository and you find no normal Python package: the logic lives in .pyx files, one class swallows most of the behavior, and dozens of modules are stitched together with Cython include directives before compilation. Reading it casually, you cannot tell where call_soon goes, who drains the ready queue, or how TLS ends up on the same loop as socket polling.

This tour reads the real tree of MagicStack/uvloop at master (release 0.23.0, verified from uvloop/_version.py) and follows the layers: the Python entry shim, the Cython Loop class, the libuv handle wrappers, and the build glue that turns a vendored C library plus 23 .pyx files into exactly one importable extension. Every file path and line number below was checked against that checkout.

uvloop overview architecture: Python API, Cython core, libuv handles, TLS/DNS/serving, and the build gluing libuv into one extension

Overview of uvloop: a thin Python API over a single Cython compilation unit that drives vendored libuv, with TLS, DNS and serving layered on top of raw handle wrappers.

Reading the overview from left to right:

  • uvloop.run(), L38 — the documented entry point; it dispatches per sys.version_info — a manual runner before 3.11, asyncio.Runner on 3.11, asyncio.run(loop_factory=...) from 3.12.
  • cdef class Loop, L123 — the whole event loop is one Cython class marked no_gc_clear, inside a file whose header opts into freethreading_compatible=True.
  • uv.uv_run(self.uvloop, mode), L500 — the heart of __run: libuv takes over inside a with nogil block, so no Python bytecode executes while C waits on I/O.
  • self.uvloop.data = <void*> self, L164 — the two-way binding: the raw uv_loop_t struct points back at the Python object, letting C callbacks recover their owner.
  • cdef class UVHandle, L1 — base class of every libuv handle wrapper: raw memory, close ordering, and a defensive __dealloc__ for handles the GC catches while still open.
  • UVStream._try_write, L347 — the fast path that asks the kernel to accept bytes immediately via uv_try_write before falling back to queued writes.
  • cdef class SSLProtocol, L195 — uvloop’s Cython reimplementation of asyncio’s SSL plumbing, paired with the app-facing _SSLProtocolTransport defined at line 15.
  • LruCache sockaddrs, L79 — resolution goes through uv_getaddrinfo on libuv’s threadpool, with sockaddr conversions cached in an LRU sized at compile time.
uvloop detail architecture: run() dispatch, Loop internals, scheduling handles, transport inheritance chain, TLS and DNS modules, and build glue

The detailed view traces run() into uv_run, the scheduling trio (async, idle, check), the transport inheritance chain from UVHandle down to TCP, and the DNS/build modules.

One Cython class, one extension

The single most important structural fact: uvloop/loop.pyx is 3,420 lines, and it is the only compilation unit. Near its end, a block of include directives at lines 3337–3361 pulls in cbhandles.pyx, pseudosock.pyx, lru.pyx, all fourteen handles/*.pyx files, request.pyx, dns.pyx, sslproto.pyx, and server.pyx — textual inclusion, the C preprocessor’s habit reborn in Cython. That is why setup.py declares exactly one Extension named "uvloop.loop" with the single source uvloop/loop.pyx — the “extension glue” is this file plus the build script, not any pyuvloop package.

The Python-side shim in uvloop/__init__.py (230 lines) exists mostly to satisfy interface checks. It defines class Loop(__BaseLoop, _AbstractEventLoop) at line 18 so that isinstance(loop, asyncio.AbstractEventLoop) passes, and new_event_loop() at line 22 which just calls Loop(). Note what has disappeared: install() and EventLoopPolicy are now created lazily in a module-level __getattr__, deprecated since Python 3.12, and slated for removal in Python 3.16 (uvloop/__init__.py, lines 129–157).

Construction is where C and Python meet. Loop.__cinit__ (starting line 124 of loop.pyx) installs PyMem-family allocators for libuv (line 128), registers pthread_atfork handlers (line 131), mallocs a uv_loop_t (line 133), and calls uv.uv_loop_init at line 161. It then wires three pacing primitives: a UVAsync (line 180) for cross-thread wake-ups, a UVIdle (line 183) that keeps the poll alive while work remains, and a UVCheck (line 190) for deferred write execution.

The run loop is libuv’s; the bookkeeping is Cython’s

run_forever (line 1357) picks UV_RUN_DEFAULT — or UV_RUN_NOWAIT if stop() was already called, mirroring asyncio behavior (lines 1360–1364) — and hands control to _run (line 506). _run validates state, records the thread id, starts the check and idle handlers, then enters __run (line 493), which reference-counts the loop manually and releases the GIL for the duration of uv.uv_run (lines 499–501). Everything user-visible — coroutine resumption, timer firing, socket events — happens when libuv’s C callbacks re-enter Cython code.

Scheduling is deliberately boring. call_soon (line 1259) wraps the callback in a Handle (defined in cbhandles.pyx at line 3) and appends it to the _ready deque created at line 178. The threadsafe variant (line 1276) also calls handler_async.send() — the one libuv call safe from other threads — which fires _on_wake (line 436) to start the idle handler; _on_idle (line 441) then drains the queue one Handle._run() at a time. Timers map onto uv_timer_t through UVTimer: call_later (line 1288) rounds to milliseconds and clamps anything above MAX_SLEEP (line 53, roughly a century) to infinity (lines 1312–1315), while call_at (line 1325) subtracts self.time() and delegates.

Raw-socket helpers bypass transports entirely: sock_recv, sock_sendall, and sock_accept (lines 2484, 2539, 2593) poll file descriptors through UVPoll (handles/poll.pyx, line 2). This is what examples/bench/echoserver.py exploits — its echo_server coroutine (line 13) sits in a tight await loop.sock_accept(sock) loop (line 26), measuring the loop, not the transport stack.

Handles, transports, and the memory contract

Every wrapper inherits from UVHandle (line 1 of handles/handle.pyx, 395 lines); its docstring states two rules: call _ensure_alive() before touching libuv, and call __ensure_handle_data in all callbacks. The memory story is strict — handles are malloc’d with PyMem_RawMalloc and freed in _free — yet __dealloc__ (line 27) accepts reality: if the handle is still open it closes it via uv.uv_close(self._handle, __uv_close_handle_cb) at line 63 rather than leaking it. That defensive posture is why the tree has so many tiny files: UVAsync (line 2 of async_.pyx), UVIdle (line 2 of idle.pyx), UVCheck (line 2 of check.pyx), UVTimer (line 2 of timer.pyx), and UVPoll (line 2 of poll.pyx) each add one small behavior to a shared base.

Transports stack on top. UVBaseTransport(UVSocketHandle) (line 1 of basetransport.pyx) initializes flow-control water marks from FLOW_CONTROL_HIGH_WATER (64 KiB, includes/consts.pxi line 4) with the low mark at a quarter of it. UVStream (line 210 of stream.pyx, 1,046 lines total) adds the 256,000-byte receive buffer — UV_STREAM_RECV_BUF_SIZE = 256000 at consts.pxi line 2, embedded as char _recv_buffer[UV_STREAM_RECV_BUF_SIZE] in the transport struct declared in loop.pxd line 87 — plus write machinery where _try_write (line 347) attempts an immediate uv_try_write and _StreamWriteContext (line 7) bookkeeps buffered writes. TCP specifics live in tcp.pyx: TCPServer(UVStreamServer) at line 56, TCPTransport(UVStream) at line 103, and connect attempts as _TCPConnectRequest(UVRequest) at line 185, all feeding into the generic listener UVStreamServer (line 2 of streamserver.pyx). The object create_server() returns is cdef class Server (line 4 of server.pyx, 136 lines) — a small bookkeeper of listeners, waiters, and active handler counts.

TLS and DNS, rewritten in Cython

sslproto.pyx (1,007 lines) is uvloop’s answer to a subtle asyncio bottleneck: the SSL handshake and shutdown state machines run as callbacks on the loop instead of separate tasks. SSLProtocol (line 195) owns that machine; _SSLProtocolTransport (line 15) is the face your protocol sees. The timeouts are compile-time C constants in consts.pxi: SSL_HANDSHAKE_TIMEOUT 60.0 (line 25) — the file comments that the default matches Nginx — and SSL_SHUTDOWN_TIMEOUT 30.0 (line 29). Read-side flow control gets its own, larger high-water mark (FLOW_CONTROL_HIGH_WATER_SSL_READ = 256, line 5) because decrypted bytes cost more than raw bytes.

DNS is a two-layer design. AddrInfoRequest(UVRequest) (line 333 of dns.pyx) drives uv.uv_getaddrinfo (line 374) on libuv’s threadpool, so resolution never blocks the loop, and static fast paths short-circuit literal addresses without touching the pool. Beneath it, the module-level sockaddrs cache (line 79) — an LruCache capped at DNS_PYADDR_TO_SOCKADDR_CACHE_SIZE = 2048 (consts.pxi line 9) — memoizes the address conversion. The cache itself (line 5 of lru.pyx) is a 79-line @cython.final class around an OrderedDict, with bound methods like move_to_end captured once in __init__ to skip attribute lookups on the hot path.

From 23 Cython files to one .so

The build facts are worth their own ledger. The package contains 23 .pyx sources and 24 .pxd declaration files; textual inclusion collapses them all into the one uvloop.loop extension. libuv itself is a git submodule pinned in .gitmodules (lines 1–3, pointing at the upstream libuv/libuv repository); build_libuv() in setup.py (line 155) copies it into a per-machine build directory, runs ./configure and make -j, and the resulting static archive is linked straight into the extension via extra_objects (lines 202–209). setup.py enforces Cython~=3.1 (line 25) and a Python floor of 3.9 (lines 4–5), and hard-rejects Windows (lines 7–8). Cython receives compile_time_env=dict(DEFAULT_FREELIST_SIZE=250) (line 150), matching the constant in consts.pxi line 8 that sizes the free lists used for buffer recycling.

Testing discipline holds the rewrite honest. uvloop/_testbase.py (552 lines) defines twin harnesses — UVTestCase (line 301) and AIOTestCase (line 312), under a meta-class-driven BaseTestCase (line 62) — so the suite in tests/ runs each scenario against both uvloop and stock asyncio; the Makefile test target even runs discovery twice, once with PYTHONASYNCIODEBUG=1 (lines 49–51). Third-party integration is checked too: tests/test_aiohttp.py exercises an aiohttp server on the loop, and the suite’s own scheduling behavior is continuously compared against the reference implementation shipping inside CPython. For contributors, a debug Makefile target rebuilds with UVLOOP_DEBUG and Cython tracing directives (lines 37–42) — the accepted way to see inside code that otherwise compiles away your Python.

Honest Limits

Windows users are excluded outright — setup.py raises at import time on win32 (lines 7–8) — a permanent architectural stance, not a TODO. The deprecation clock is ticking too: install() and EventLoopPolicy will vanish in Python 3.16, so new code should call uvloop.run() directly. The famous “2-4x faster” figure is the project’s own README benchmark on an echo server; real-world gains depend heavily on how much of your workload is I/O scheduling versus Python computation, so treat it as an upper bound. Finally, the design that makes uvloop fast makes it opaque: all .pyx files are textually fused into one compilation unit, so generated C interleaves everything, and the practical debugging path is the traced debug build rather than ordinary Python stepping. None of that changes the verdict that matters: as a case study in binding a C event loop to Python object semantics with minimal overhead, this tree rewards a slow, careful read.

Watch PyShine on YouTube

Contents