Robyn icon indicating copy to clipboard operation
Robyn copied to clipboard

Example app uses synchronous DB access in async route handlers

Open phdowling opened this issue 9 months ago • 0 comments

Just dropping in since I saw this shared on hackernews a little while ago and spotted something I've seen other web frameworks do in their example code in the past that I wondered about.

In the example app here https://robyn.tech/documentation/en/example_app/modeling_routes#crime-data-model-and-database-connection, there is some example code that looks like this:

@app.post("/crimes")
async def add_crime(request):
    with SessionLocal() as db:
        crime = request.json()
        insertion = crud.create_crime(db, crime)  # this is the potentially problematic line

    if insertion is None:
        raise Exception("Crime not added")

    return {
        "description": "Crime added successfully",
        "status_code": 200,
    }

where the crud implementation is obviously using synchronous SQLAlchemy code. SQLAlchemy supports asyncio, and that's for a good reason: code like this will unnecessarily block the entire event loop while the database is being accessed, asynchronous DB access would be much better here. Technically, this isn't a bug, but unless I'm missing some background magic here, it's definitely not advisable and would probably kill performance for even simple CRUD apps.

To compare: in FastAPI, this would be worked around by simply not declaring the route handers async, as FastAPI will just run the handler in a background threadpool in that case, so my question is: does robyn have some equivalent magic that runs every async handler in a threadpool as well?

Feel free to close if this is intended code and robyn has some hidden mechanism for handling this gracefully, but as someone just checking out the framework it struck me as a potential problem.

phdowling avatar Mar 17 '25 15:03 phdowling