Event Loop Abstraction
Relevant source files
The following files were used as context for generating this wiki page:
Uvicorn provides an event loop abstraction layer that allows the server to utilize different asynchronous I/O implementations. This system enables Uvicorn to automatically select the most performant loop available (such as uvloop) or fall back to the standard library asyncio implementation.
The abstraction is primarily managed through the Config class, which handles loop selection, and a set of loop factory functions that initialize the environment for the chosen loop type.
Sources: uvicorn/config.py:75-81, uvicorn/loops/auto.py
Loop Selection Logic
The selection of the event loop is determined by the loop parameter in the Uvicorn configuration. Users can explicitly request a specific implementation or rely on the "auto" behavior.
Supported Loop Types
| Loop Type | Factory Function | Description |
|---|---|---|
none | None | No loop factory provided. |
auto | auto_loop_factory | Automatically selects uvloop if available, else asyncio. |
asyncio | asyncio_loop_factory | Forces the use of the standard library asyncio loop. |
uvloop | uvloop_loop_factory | Forces the use of the high-performance uvloop implementation. |
Sources: uvicorn/config.py:75-81, uvicorn/loops/auto.py:4-11
Automatic Selection (Auto Loop)
When loop="auto" is configured, Uvicorn attempts to import uvloop. If successful, it uses the uvloop_loop_factory. If the import fails (common on Windows or if the package is missing), it falls back to asyncio_loop_factory.
Sources: uvicorn/loops/auto.py:4-11
Diagram shows the decision logic for selecting an event loop factory based on configuration.
Sources: uvicorn/config.py:657-666, uvicorn/loops/auto.py:4-11
Implementation Details
The Config Interface
The Config class is responsible for loading the requested loop factory and providing it to the server runner. It uses the get_loop_factory() method to resolve the loop implementation.
get_loop_factory(): This method looks up the factory string in theLOOP_FACTORIESmapping. If the configured loop is a custom string (e.g.,"my_module:my_factory"), it attempts to import it dynamically.- Custom Loops: Uvicorn supports importable custom loop setup functions. If the provided
loopstring is not in the predefined keys, Uvicorn usesimport_from_stringto load it.
Sources: uvicorn/config.py:657-670, tests/test_config.py:465-475
Loop Factories
Each loop implementation provides a factory function that returns a new asyncio.AbstractEventLoop instance.
asyncio_loop_factory: Configures the standardasyncioloop. On Windows, it specifically sets theWindowsSelectorEventLoopPolicyif multiple workers are used to avoid compatibility issues.uvloop_loop_factory: Installsuvloopas the global event loop policy and returns a new loop instance. This implementation is typically unavailable on Windows.
Sources: uvicorn/loops/asyncio.py, uvicorn/loops/uvloop.py, tests/test_config.py:402-405
Protocol Integration
Individual protocols, such as HttpToolsProtocol or H11Protocol, retrieve the active event loop during initialization. They typically use asyncio.get_event_loop() or receive a loop instance passed from the server.
Sources: uvicorn/protocols/http/httptools_impl.py:60-61, uvicorn/protocols/http/h11_impl.py:53-54
Configuration Summary
The following table outlines the configuration options relevant to the event loop abstraction.
| Option | Type | Default | Description |
|---|---|---|---|
loop | LoopFactoryType | str | "auto" | The event loop implementation to use. |
workers | int | 1 | Number of worker processes. Influences loop policy on Windows. |
reload | bool | False | Enables hot-reloading. Influences whether use_subprocess is active. |
Sources: uvicorn/config.py:205-230, uvicorn/config.py:669
Usage Example: Custom Loop
Uvicorn allows developers to provide their own loop factory via an import string.
# In tests/custom_loop_utils.py
class CustomLoop(asyncio.SelectorEventLoop):
pass
def custom_loop_factory():
return CustomLoop()
# Config usage
config = Config(app=app, loop="tests.custom_loop_utils:custom_loop_factory")
Sources: tests/test_config.py:465-475
Conclusion
The Event Loop Abstraction in Uvicorn ensures high performance by defaulting to uvloop where possible while maintaining broad compatibility through a fallback to standard asyncio. By decoupling the loop instantiation from the server logic via factories, Uvicorn remains flexible enough to support custom asynchronous environments and specific OS-level requirements (like Windows selector policies).