Concurrency Utilities
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides a set of concurrency utilities designed to bridge the gap between synchronous Python code and asynchronous ASGI environments. These utilities ensure that blocking operations, such as file I/O or synchronous endpoint handlers, do not block the main event loop, maintaining the high performance and responsiveness of the application.
The core of these utilities revolves around offloading synchronous tasks to thread pools and managing asynchronous iteration for streaming data. This architecture allows developers to write standard synchronous functions while benefiting from an asynchronous execution model.
Core Utility Functions
Starlette implements several key functions to handle different concurrency scenarios, primarily utilizing anyio for cross-backend compatibility (e.g., asyncio and trio).
run_in_threadpool
This function takes a synchronous callable and executes it within a separate thread using anyio.to_thread.run_sync. It is extensively used throughout the framework to handle synchronous endpoints and middleware logic without stalling the event loop.
Sources: starlette/concurrency.py:27-30, starlette/endpoints.py:38
iterate_in_threadpool
This utility transforms a standard synchronous Iterable into an AsyncIterator. It wraps the iteration process so that each next() call is executed in a thread pool. This is crucial for StreamingResponse objects that consume synchronous generators.
Sources: starlette/concurrency.py:33-42, starlette/responses.py:248
Concurrency Logic Flow
The following diagram illustrates how Starlette handles synchronous handlers within an asynchronous lifecycle:
The framework dynamically detects if a callable is asynchronous and routes execution accordingly to maintain non-blocking behavior.
Sources: starlette/routing.py:44-55, starlette/endpoints.py:34-39
Implementation in Endpoints and Routing
The concurrency utilities are integrated into the fundamental building blocks of Starlette's request handling.
HTTP Endpoints
The HTTPEndpoint class uses is_async_callable to determine the execution path for request handlers. If a method (like get or post) is synchronous, it is wrapped in run_in_threadpool.
Sources: starlette/endpoints.py:34-39
Request-Response Mapping
The request_response utility function serves as a wrapper to convert a standard function into an ASGI-compatible application. It utilizes functools.partial(run_in_threadpool, func) to ensure synchronous functions are executed safely.
Sources: starlette/routing.py:44-55
| Component | Concurrency Method | Purpose |
|---|---|---|
HTTPEndpoint | run_in_threadpool | Offloads sync methods (GET, POST, etc.) |
StreamingResponse | iterate_in_threadpool | Converts sync iterables to async |
ServerErrorMiddleware | run_in_threadpool | Executes sync custom error handlers |
FileResponse | anyio.to_thread.run_sync | Performs blocking os.stat calls |
| Sources: starlette/endpoints.py:38, starlette/responses.py:248, starlette/middleware/errors.py:164, starlette/responses.py:309 |
Threaded I/O and Background Tasks
Starlette leverages thread pools for blocking filesystem operations to ensure the ASGI server remains responsive.
File Handling
The FileResponse class performs metadata retrieval (via os.stat) using anyio.to_thread.run_sync. This prevents the event loop from waiting on disk I/O when determining file size or modification times.
Sources: starlette/responses.py:309-311
Background Task Execution
While BackgroundTask objects are initiated within the async flow, they can encompass both async and sync logic, allowing long-running operations to persist after the initial HTTP response has been sent to the client.
Sources: starlette/responses.py:221-222, starlette/responses.py:284-285
This sequence ensures that even basic filesystem checks do not degrade server performance under high concurrency.
Sources: starlette/responses.py:309-317
Summary of Concurrency Utilities
Starlette's concurrency module provides a standardized way to handle the mix of synchronous and asynchronous code inherent in Python web development. By using anyio as an abstraction layer, the framework ensures compatibility across multiple async libraries while providing simple patterns (run_in_threadpool, iterate_in_threadpool) for developers to maintain non-blocking applications.
Sources: starlette/concurrency.py:1-42