Skip to content
Latchkey

FastAPI async SQLAlchemy "asyncpg" driver mismatch in CI

Async SQLAlchemy needs an async DBAPI. If the URL names a sync driver (or none) while you call create_async_engine, or if asyncpg is not installed, the engine cannot connect and the error names the driver problem.

What this error means

Startup or a DB test fails with "sqlalchemy.exc.InvalidRequestError: The asyncio extension requires an async driver" or "ModuleNotFoundError: No module named 'asyncpg'".

python
sqlalchemy.exc.InvalidRequestError: The asyncio extension requires an async driver
to be used. The loaded 'psycopg2' is not async.

Common causes

A sync driver in an async URL

The URL uses postgresql:// (defaulting to a sync driver) with create_async_engine, which requires an async DBAPI like asyncpg.

asyncpg is not installed in CI

The async driver is not a declared dependency, so importing the engine fails on a clean runner.

How to fix it

Use the asyncpg dialect and install it

  1. Install asyncpg in the environment.
  2. Use the postgresql+asyncpg:// URL scheme for the async engine.
  3. Keep sync tools (like Alembic) on their own sync URL if needed.
Terminal
python -m pip install asyncpg
# async engine URL
postgresql+asyncpg://postgres:postgres@localhost:5432/test

Create the async engine correctly

Build the engine with the async factory and the async driver URL.

app/db.py
from sqlalchemy.ext.asyncio import create_async_engine

engine = create_async_engine(settings.database_url, echo=False)

How to prevent it

  • Match the driver in the URL scheme to sync vs async engine use.
  • Declare asyncpg as a dependency when using async SQLAlchemy.
  • Keep migration (sync) and app (async) URLs distinct where drivers differ.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →