All jobs

Migrate a SQLModel and FastAPI App to Async Sessions

Yes. The agent moves the engine, session dependency, routes and CRUD helpers to AsyncSession, keeps Alembic synchronous and reworks the tests to match.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent maps everything that holds a session before it changes one. In an app like fastapi/full-stack-fastapi-template, backend/app/core/db.py builds the engine with create_engine(str(settings.DATABASE_URL), pool_pre_ping=True), get_db in app/api/deps.py yields a Session from it, and SessionDep carries that into every route in app/api/routes and into get_current_user. app/crud.py takes a session as an argument, app/initial_data.py opens one to seed the first superuser, and the tests open their own in tests/conftest.py. All route functions are plain def, which FastAPI runs in a thread pool. The migration is therefore every session.exec, session.get, commit, refresh and delete in those files, and the agent lists them first so that the diff can be checked against the list.

The driver turns out to need no change, which the agent confirms from the files. pyproject.toml depends on psycopg[binary], and the _use_psycopg_driver validator in app/core/config.py rewrites the URL to postgresql+psycopg://. Psycopg 3 has an async mode behind that same URL, so create_async_engine accepts it and no second driver is added. The engine becomes async, get_db becomes an async generator yielding AsyncSession from sqlmodel.ext.asyncio.session, which keeps SQLModel's typed exec, and each database call gains an await. session.add stays as it is; it does no I/O. Alembic is left alone on purpose: app/alembic/env.py builds its own synchronous engine with engine_from_config from the same settings, and migrations gain nothing from an event loop.

Three things then behave differently, and the agent handles each one explicitly. Attributes expire on commit, and under an async session touching an expired attribute or an unloaded relationship raises instead of quietly querying, so it creates sessions with expire_on_commit=False and loads User.items with an explicit option wherever code reads it. Password hashing is the second. crud.authenticate and create_user call verify_password and get_password_hash, which are deliberately slow; in a def route they ran on a worker thread, and in an async def route they would stall every other request, so the agent sends them to a thread with run_in_threadpool. The third is the scripts: initial_data.py, run by scripts/prestart.sh after alembic upgrade head, becomes an asyncio.run around an async init_db.

Tests take the most care. The session-scoped db fixture and the helpers under tests/utils call crud directly with a synchronous session, and the route tests use TestClient, which runs the application on an event loop of its own. Connections in an async engine's pool belong to the loop that opened them, so sharing one engine between the tests' loop and the client's is the classic source of errors here. The agent moves the route tests to httpx.AsyncClient over an ASGI transport so that everything runs on one loop, using the anyio pytest plugin that is already in uv.lock, and keeps the fixture's cleanup of Item and User. It installs PostgreSQL from system packages, since the sandbox has no Docker for the db service in compose.yml, then runs what .github/workflows/test-backend.yml runs: uv run bash scripts/prestart.sh, uv run bash scripts/tests-start.sh, and scripts/lint.sh for mypy in strict mode, ty and ruff.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Migrate this FastAPI and SQLModel backend from synchronous sessions to AsyncSession. Read backend/pyproject.toml, uv.lock, app/core/config.py, app/core/db.py, app/api/deps.py, every file in app/api/routes, app/crud.py, app/initial_data.py, app/alembic/env.py, the scripts directory, every test and the backend test workflow first. List every place a session is created or used; the pull request must account for each one. Check whether the installed database driver already supports async with the URL the settings produce before adding any dependency. Make the engine, the session dependency, the routes, the CRUD helpers and the seed script async, using SQLModel's AsyncSession so exec stays typed. Keep Alembic's env.py synchronous. Find every attribute or relationship read after a commit or outside the query that loaded it and make it safe under async, and say how. Keep password hashing and any other CPU-heavy call off the event loop. Do not change routes' paths, response models or status codes. Rework the tests so the application and the test code use the engine on one event loop, with a test plugin that is already installed if there is one, and keep every existing test. Install PostgreSQL from system packages and say which version, run the prestart script, the test script with coverage and the lint script exactly as CI does, and fix what they report. Open a pull request with the list of session uses and what each became, the output of the three scripts, and anything that now behaves differently for callers.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

A pull request that touches most of backend/app and backend/tests and changes no API contract. The description begins with the inventory: each place a session was created or used, by file and function, and what it became. A reviewer reads down it looking for a blocking call left inside an async def, which is the mistake this migration invites, and the list makes that a matter of minutes.

Three short sections follow, one for each behaviour that changed underneath: how expired attributes and the items relationship are handled, where hashing now runs, and how the tests share a loop with the application. Then the output of the prestart, test and lint scripts from the sandbox, with the PostgreSQL version named because compose.yml pins postgres:18 and the system package may differ. Coverage is reported as the script prints it, against the 90 percent floor the workflow enforces.

The decision left to the reviewer is whether the migration is wanted everywhere. Async sessions pay off when routes wait on other network calls or hold many slow queries open; for short queries behind a thread pool the gain is small. The description says which routes in this codebase fall into which group, so the team can merge all of it or ask for a narrower change.

Run it on every backend still on sync sessions

This is a one-off per service, decided in a planning meeting and then postponed because it touches everything. A developer sends this body to POST /o/{org}/sessions from a terminal or an editor's MCP client and keeps working on their own branch. A request_id, a UUID generated once for the job, lets them retry the call safely: the same id and body return the run that already started.

The run can be steered after it starts. If the first result converts more than the team wants, a follow-up to POST /o/{org}/sessions/{id}/messages such as a request to leave the admin routes synchronous wakes the same sandbox, with the repository and the database still in place, and the pull request is updated.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

This migration compiles long before it works. Missing awaits, a lazy load after commit and a pool shared across event loops all pass the type checker in some form and fail only when requests run against a real database. The agent has PostgreSQL in its own sandbox, applies the migrations, runs the whole suite and the strict lint script, and the output of each is kept in the transcript at GET /o/{org}/sessions/{id}/messages.

It is also a wide, mechanical diff that goes stale quickly on a busy repository. A run produces it in one sitting from the current main branch. The developer who asked reviews an inventory and three explanations instead of spending days converting functions between other tasks while the branch drifts.

Frequently asked questions

Do I need asyncpg for this?

Not when the project already uses psycopg 3. Its SQLAlchemy dialect serves both modes from the postgresql+psycopg:// URL, and create_async_engine picks the async one. The agent adds a driver only if the installed one cannot do it, and says which in the description.

Why keep Alembic synchronous?

Migrations run one statement after another from a command, so an event loop adds nothing. The existing env.py creates its own engine from the settings and never shares the application's. Leaving it untouched also means the migration history and the commands in the README stay exactly as they are.

Will the endpoints get faster?

Individual queries do not. What changes is how many requests can wait on the database at once without each holding a thread. The agent makes no speed claims; if you want numbers, ask for a load test in the same run and it reports what it measures before and after.

What is the error about a missing greenlet?

It is what SQLAlchemy raises when synchronous-style I/O is attempted under an async session, most often a lazy relationship load or a read of an attribute that expired at commit. Turning off expiry on commit and loading relationships in the query removes the two usual causes. The agent adds a test that loads a relationship through the async session so the case stays covered.

More SQLModel jobs

More jobs like this: Hand off a long task

Keep reading