flpit-stoop
A FastAPI-style web framework that runs on the flpit Task runtime and is served by Granian, using Kestrel's execution model: one process, no asyncio event loop in the request path.
A stoop is the falcon's high-speed dive. The name comes from the kestrel, a falcon, which is also where ASP.NET's Kestrel server got its name.
pip install flpit-stoop # or: uv add flpit-stoop
The distribution is flpit-stoop; the code lives in the flpit.stoop package next to flpit itself (from flpit.stoop import Stoop). It installs a stoop command (also available as flpit-stoop). Requires flpit ≥ 0.5.0: its package is extensible (pkgutil.extend_path), so flpit.stoop also imports from editable/dev installs, and it has the public ThreadPool.queue stoop dispatches with.
from dataclasses import dataclass
from flpit.stoop import Stoop, CancellationToken, Task
app = Stoop(title="Shop")
@dataclass
class Item:
item_id: int
name: str
@app.get("/items/{item_id:int}")
def get_item(item_id: int, verbose: bool = False) -> Item: # sync: runs on a pool worker
return Item(item_id, "widget")
@app.post("/items", status_code=201)
async def create(item: Item, token: CancellationToken) -> Item: # cancelled if the client leaves
await Task.delay(0.1, token=token)
return item
if __name__ == "__main__":
app.run(port=8000) # Swagger UI at /docs
uv run stoop run myapp:app --port 8000 # loop-free direct host (default)
uv run stoop run myapp:app --host-mode rsgi # Granian's standard embedded RSGI server
uv run granian --interface rsgi myapp:app # stock Granian CLI works too
How it runs
Granian (Rust / tokio) flpit Task runtime (Python thread pool)
────────────────────────────────── ─────────────────────────────────────────
accept · TLS · HTTP/1 + HTTP/2 · WS ──► schedule(watcher): match route
├─ sync route → plain pool work item
└─ async route → Task.run (one hop)
body bytes · disconnect · ws frames ──► FlpitLoop.call_soon* → TaskCompletionSource
response channel ◄── proto.response_*() straight from the worker
- Single process, threads only. Granian's
RSGIWorkerruns in multi-threaded runtime mode inside the current process (flpit.stoop.server.Server). Granian's processes, workers and asyncio loops are not used. - No event loop in between. Granian normally sends each request to an asyncio loop. stoop installs its own
CallbackScheduler, which posts the request straight onto the flpit pool. Granian's future-like objects (request body,client_disconnect(), WebSocketaccept/receive) complete throughFlpitLoop, a loop shim that completes flpitTaskCompletionSources. The awaiting coroutine then resumes on the pool. - Kestrel model. Granian's Rust threads do the I/O. Application code runs on a thread pool modelled on .NET's: coroutines resume on any worker, and blocking code may run on a worker (the pool injects more threads if workers block). On free-threaded Python (3.14t) the workers run in parallel.
- Synchronous fast path. A sync endpoint with no request body and no middleware is matched, bound, executed, serialised and written in one pool work item. No coroutine and no Task object is created for it.
- Responses are written from the worker. Granian's
response_*calls are thread-safe Rust calls, so sending a response needs no thread hop. - Everything per request is lazy. Query parsing, the body, the DI scope and the disconnect watch are only set up when something uses them.
The standard app.__rsgi__ interface is still available for portability. In that mode, request I/O is bridged to the asyncio loop thread and costs one loop→pool hop per request.
Features
| Routing | decorators per method, route groups (Router(prefix, tags, middleware, timeout)), ASP.NET-style constraints {id:int}, {id:uuid}, {path:path}. Static routes are matched with an O(1) dict lookup, dynamic ones with a segment trie |
| Parameters | inferred like FastAPI (path → query → body), or explicit with Path/Query/Header/Cookie/Body/FromServices (as defaults or in Annotated). Conversion uses msgspec. All errors are collected into one 400 response in ASP.NET Core's ValidationProblemDetails shape (errors: parameter name → messages). The individual errors stay available as RequestValidationError.details |
| JSON | Request bodies must be sent as application/json or a +json type (415 otherwise, as in ASP.NET Core: JSON read from text/plain would skip the browser's CORS preflight). flpit.json (JsonConvert) for dataclasses and list[dataclass], using the app's JsonSerializerOptions (camelCase by default). msgspec for everything else, including msgspec Structs. Encoders and decoders are compiled per route from the annotations |
| DI | ServiceCollection / ServiceProvider with singleton, scoped (per request) and transient lifetimes; keyed services; list[T]; optional services; validation at build time (missing services, cycles, captive dependencies); disposal in reverse order (sync and async); create_instance (ActivatorUtilities) |
| Proxying | decorate(IService, Wrapper): Scrutor-style decorators that implement the same interface and receive the previous implementation (they stack). intercept(IService, *interceptors): generated dispatch proxies (isinstance(proxy, IService) is true) for sync and async methods |
| Cancellation | token: CancellationToken parameter (or request.cancellation_token). The token is cancelled when the client disconnects (HttpContext.RequestAborted) or when the route timeout elapses. A timeout produces 504, a disconnect produces 499 |
| Middleware | async def mw(request, call_next). App middleware wraps routing, so it also sees 404/405 and CORS preflight requests. Group and route middleware wrap a single endpoint. Middleware classes get constructor injection. Built in: CORSMiddleware, ConcurrencyLimiter (flpit SemaphoreSlim, FIFO queue, 503), ServerTimingMiddleware |
| Slow-client protection | Request bodies must arrive at a minimum data rate: by default 1 KiB/s after a 10 s grace period. This catches stalled clients and clients trickling data just fast enough to dodge an idle timeout; both get 408 and the connection is closed. A shared once-a-second heartbeat (as in Kestrel) checks the deadlines, so a request pays only a set insert and removal while it waits for body data. Change it with Stoop(min_body_rate=MinDataRate(...)), per group or per route; None turns it off. Granian already limits header reading to 30 s |
| Forms and uploads | Form() fields and UploadFile parameters (single, optional or list[UploadFile]) from multipart/form-data or application/x-www-form-urlencoded bodies. await request.form() gives the raw FormData. Uploads are held in memory, bounded by the body size limit. A form has at most 1,000 fields and files (Starlette's limit; ASP.NET Core's FormOptions allow 1,024 values), and a text field at most 4 MiB (as FormOptions.ValueLengthLimit); beyond either, 413. OpenAPI describes them as form bodies |
| Body size limit | 30 MB by default. Change it with Stoop(max_body_size=...), per group with Router(max_body_size=...), or per route with @app.post(..., max_body_size=...). UNLIMITED turns it off. Requests with a larger Content-Length are rejected before any body is read; chunked bodies are counted while reading. Either case returns 413 |
| Results | return values, Response, JSONResponse, PlainTextResponse, HTMLResponse, RedirectResponse, FileResponse (served by Granian from disk), StreamingResponse (sync and async iterables, AsyncFlpIt queries), EventStreamResponse (server-sent events), Results.* helpers |
| Static files | app.static_files("/static", "wwwroot") (ASP.NET Core's UseStaticFiles), also on a Router, with route options. Granian sends the file from disk. Safe by default: nothing outside the directory (.., encoded or not, backslashes, drive letters, symlinks leading out), no dotfiles, no directory listings, and only web content types from a fixed table (no .py, .toml, backups). ETag/Last-Modified with 304, single byte ranges for media seeking |
| Errors | RFC 9457 problem details. HTTPException(status, detail, headers, **extensions). Exception handlers (sync or async) are looked up along the exception's MRO. debug=True adds tracebacks |
| WebSockets | @app.websocket("/ws/{room}") with the same parameter binding; accept, receive*, send_text/bytes/json, close, async for |
| Hosting | on_startup / on_shutdown; hosted services (BackgroundService.execute(stopping_token)); health checks (/healthz, run concurrently with Task.when_all-style tasks); graceful drain on stop |
| OpenAPI | /openapi.json (OpenAPI 3.1, with schemas generated from flpit's wire types so names follow the naming policy) and Swagger UI at /docs |
| Testing | flpit.stoop.testing.TestServer (ASP.NET Core's TestServer) drives the real dispatch code with no sockets: with TestServer(app) as server: client = server.create_client(). client.start(...) plus .disconnect() tests cancellation |
Dependency injection with decorators and proxies
services = ServiceCollection()
services.add_singleton(AuditLog)
services.add_singleton(TodoRepository, InMemoryTodoRepository)
services.decorate(TodoRepository, AuditingTodoRepository) # __init__(self, inner: TodoRepository, audit: AuditLog)
services.intercept(TodoRepository, TimingInterceptor) # interceptor types are built through DI too
services.add_scoped(UnitOfWork) # one per request, disposed after the response
app = Stoop(services=services)
@app.get("/todos")
def todos(repo: TodoRepository) -> list[Todo]: # registered types are injected automatically
return repo.all()
An interceptor is a callable (invocation) -> result, or an object with intercept(invocation). Call invocation.proceed() to continue the chain. For async methods, proceed() returns an awaitable and the interceptor can be async def.
asyncio clients: one per loop
Prefer a library's sync client (one shared httpx.Client). For libraries that only exist for asyncio, register the client per loop. asyncio clients belong to one event loop, and flpit's asyncio bridge runs several loops, so the container keeps one instance per loop:
from flpit.asyncio_bridge import PerLoop
from flpit.task import asyncio_task
services.add_per_loop(httpx.AsyncClient, factory=lambda: httpx.AsyncClient(timeout=10), warm=True)
services.add_singleton(GitHubApi)
class GitHubApi:
def __init__(self, clients: PerLoop[httpx.AsyncClient]) -> None: # not the client itself
self._clients = clients
@asyncio_task
async def repo(self, name: str, token: CancellationToken) -> dict: # a client disconnect cancels it
return (await self._clients.current.get(f"https://api.github.com/repos/{name}")).json()
- Captive check: a singleton, scoped or transient service that takes the client itself fails when the container is built. It would keep one loop's client; the error points to
PerLoop[...]. Per-loop services may take it directly. warm=True: creates the client on every loop before the loop takes work.- Closing: the clients close with their loop and when the app shuts down.
Loop[T]parameters:@asyncio_taskfunctions withclient: Loop[httpx.AsyncClient] = injectedreceive the same instances.- Thread-safe async clients: a client like pyreqwest's
Clientneeds none of this. Register it as a plain singleton.
Cooperative cancellation
@app.get("/report", timeout=5.0) # 504 after 5 s
async def report(token: CancellationToken):
async for row in rows(): # stops as soon as the client goes away
token.throw_if_cancellation_requested()
await Task.delay(0.01, token=token)
@app.get("/crunch")
def crunch(token: CancellationToken): # blocking code polls the token
while not token.is_cancellation_requested:
step()
The disconnect watch is only started when a handler asks for the token, so endpoints that never use it pay nothing.
See examples/todo_app.py for an app that uses all of the above.
Server options
from flpit.stoop.server import Server
with Server(app, host="0.0.0.0", port=8000,
runtime_threads=2, # tokio I/O threads
min_workers=16, max_workers=256, # flpit pool (Task.configure)
http="auto", websockets=True,
ssl_cert="cert.pem", ssl_key="key.pem") as server:
...
Server.start() returns once the server is listening. port=0 picks a free port. stop() stops accepting connections, drains requests that are in flight, then runs app shutdown.
STOOP_DISPATCH=task forces dispatch through the public Task.run only (see "Internals used" below).
Benchmarks
stoop vs. standard FastAPI
uv run --group bench python bench/compare_fastapi.py (options and setup in bench/README.md) compares stoop with the stack most FastAPI apps run on: fastapi[standard] served by uvicorn with uvloop and httptools, which is what fastapi run uses. All versions are the latest releases: FastAPI 0.165.0, uvicorn 0.54.0, uvloop 0.23.0, pydantic 2.14.4, starlette 1.10.0.
Both apps implement the same endpoints the idiomatic way for each framework (dataclasses for stoop, pydantic models for FastAPI; def endpoints for sync, async def for async). Access logs are off on both. Each cell is the median of 3 runs of 4 s with 32 keep-alive connections.
| req/s · Python 3.13 | plaintext | json | async | params |
|---|---|---|---|---|
| stoop (direct host) | 34,100 | 35,497 | 20,097 | 33,852 |
| FastAPI + uvicorn | 5,154 | 3,346 | 10,185 | 2,951 |
| FastAPI + uvicorn, 2 workers | 11,164 | 3,478 | 16,161 | 7,438 |
| stoop ÷ FastAPI (1 worker) | 6.6× | 10.6× | 2.0× | 11.5× |
| req/s · Python 3.14t (free-threaded) | plaintext | json | async | params |
|---|---|---|---|---|
| stoop (direct host) | 33,434 | 30,658 | 19,882 | 28,987 |
| FastAPI + uvicorn | 6,968 | 4,564 | 9,643 | 3,963 |
| FastAPI + uvicorn, 2 workers | 8,779 | 4,600 | 15,704 | 4,874 |
| stoop ÷ FastAPI (1 worker) | 4.8× | 6.7× | 2.1× | 7.3× |
The endpoints are: plaintext returns a fixed string, json returns one object, async is an async def that returns one object, and params is GET /items/{id}?q=&limit=, which binds a path parameter and query parameters into an object.
- The biggest gaps are on sync
defendpoints. FastAPI sends each one through anyio's thread pool and back to the event loop. stoop runs them in a single pool work item with no coroutine. - On
async defendpoints FastAPI is at its best, because the request stays on the event loop, and stoop is still about 2× faster.
With a native load generator. The tables above were measured with the Python load generator. A later run on the same 2-vCPU sandbox used oha (Python 3.14t, 64 connections, 3 s, 1 round), with the server pinned to one core and oha to the other:
| req/s · 1 server core | plaintext | json | async | params |
|---|---|---|---|---|
| flpit-stoop | 54,234 | 43,380 | 25,024 | 34,408 |
| FastAPI + uvicorn | 5,158 | 3,558 | 9,819 | 2,849 |
p99 latency was 2.5–4.9 ms for flpit-stoop and 10–45 ms for FastAPI. For real hardware see bench/README.md.
Caveats. These numbers come from a 2-vCPU sandbox. The Python load generator runs on the same CPUs and tops out at about 35k req/s, so it caps stoop's numbers. Without a network, an in-process microbenchmark of stoop's dispatcher alone reaches about 90–120k req/s. Treat the table as a relative comparison, and rerun it on your own hardware with a native load tool such as wrk or oha for absolute numbers.
Host modes
uv run --group bench python bench/run.py compares stoop's two hosts with FastAPI running on Granian. stoop's RSGI fallback mode sends each request through an asyncio loop first, so it reaches only about 10–11k req/s in this setup, compared with about 30–36k for the direct host.
Internals used, and known limitations
- Granian internals. The direct host uses
CallbackScheduler._schedule_fn,RSGIWorker(...)/serve_mtr,WorkerSignaland the duck-typed loop Granian callscall_soon*on. For that reason the Granian dependency is pinned to>=2.8.9,<2.9.app.__rsgi__uses only public RSGI. - flpit.json handles dataclasses only, and by default leaves out fields that equal their default value (
JsonDefaultHandling.exclude). Setjson_options=JsonSerializerOptions(default_handling=JsonDefaultHandling.include)to include them. - WebSocket close on the RSGI host. On the RSGI fallback host (
--host-mode rsgi), the server's WebSocket close frame isn't sent; the client finishes when its own close timeout expires. Plain Granian RSGI apps show the same with uvloop. The direct host isn't affected. - Endpoints whose annotations refer to classes defined inside a function, combined with
from __future__ import annotations, cannot be resolved. This is the same limitation FastAPI has. - asyncio libraries in handlers. The direct host runs no asyncio event loop, so asyncio-based libraries (asyncpg, httpx's async client, redis.asyncio, aiohttp, ...) can't be called directly in a handler ("no running event loop"). Call them through flpit's
@asyncio_task, with clients registered per loop: see asyncio clients: one per loop. Where a library has a sync client, prefer it: sync handlers run on pool workers, in parallel on free-threaded Python. - Sync endpoints run on pool workers. Long blocking calls make the pool inject threads, as in .NET.
Development
uv sync
uv run pytest # free-threaded 3.14t (project default)
UV_PROJECT_ENVIRONMENT=.venv-3.13 uv run --python 3.13 pytest # GIL build
uvx ruff check src tests bench
The 118 tests cover the DI container, routing, binding, the app pipeline, OpenAPI, the I/O bridges, the dispatcher, the CLI and the example app. They also include end-to-end socket tests that run against both hosts: keep-alive, large bodies, concurrency, streaming, disconnect-driven cancellation, WebSockets, and graceful drain.
Metadata
Release files for flpit-stoop 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| flpit_stoop-0.1.0.tar.gz | 79.8 kB | Without provenance | Details for flpit_stoop-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| flpit_stoop-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for flpit_stoop-0.1.0-py3-none-any.whl |
Total release size: 162.2 kB
Release files / flpit_stoop-0.1.0.tar.gz
| Download URL | flpit_stoop-0.1.0.tar.gz |
|---|---|
| Size | 79.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e07c69b8e5609bb31b09777b231477accd364edbf6cbf60cf2eb82f320ebb21a
|
|
BLAKE2b-256 checksum How to use checksums |
bd24d1e04b6a4c4a90dcb3fd52101b690180317bfbdb8da1f1f0bf1a70bd3548
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / flpit_stoop-0.1.0-py3-none-any.whl
| Download URL | flpit_stoop-0.1.0-py3-none-any.whl |
|---|---|
| Size | 82.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b5409b0143be9b8af71916451f95172c5f60aa909f4caee827e563f1e92df46b
|
|
BLAKE2b-256 checksum How to use checksums |
b21f327c6dd574ffecd8c3b8a7d83ff904d9960454e7584ed3ad52e153c531de
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for flpit-stoop 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.