What is the MissingGreenlet error in async SQLAlchemy?
MissingGreenlet is the exception SQLAlchemy raises when ORM code tries to perform database I/O at a point where the async layer cannot run it. The error text usually reads: "greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?"
The mechanism
AsyncSession is a thin wrapper around a regular synchronous Session. When you await session.execute(...), SQLAlchemy runs the synchronous ORM code inside a greenlet. Inside that greenlet, each blocking driver call is bridged to an await on the async driver. That bridge exists only for the duration of the awaited call.
Plain attribute access, such as user.posts, is not awaited. If the relationship was never loaded, the default lazy loader tries to emit a SELECT right there. The same thing happens when a column has expired, for example after commit() with the default expire_on_commit=True. With no greenlet available to switch into, SQLAlchemy cannot perform the I/O. It raises MissingGreenlet rather than blocking the event loop or running a query you did not ask for.
A minimal reproduction
Define a User model with a posts relationship that uses the default lazy loading. Fetch a user with user = await session.get(User, 1), then read user.posts. The first query loaded only the users row, so the attribute access needs a second query and fails.
Why it matters
Read the error as a diagnostic. It shows exactly where your code depended on implicit I/O. That habit is common in sync ORM code, which is why the error appears often when engineers port it to async or build new FastAPI services on AsyncSession.
import asyncio
from sqlalchemy import ForeignKey
from sqlalchemy.exc import MissingGreenlet
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
# No loader option: the default lazy="select" emits a SELECT on first access
posts: Mapped[list["Post"]] = relationship()
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
async def main() -> None:
engine = create_async_engine("sqlite+aiosqlite:///./demo.db")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
async with AsyncSession(engine) as session:
session.add_all([User(id=1), Post(id=1, user_id=1)])
await session.commit()
async with AsyncSession(engine) as session:
user = await session.get(User, 1) # awaited: loads only the users row
try:
print(user.posts) # not awaited: lazy load needs I/O with no greenlet
except MissingGreenlet as exc:
print(f"MissingGreenlet: {exc}")
await engine.dispose()
asyncio.run(main())
A minimal reproduction in which session.get() loads only the users row, so reading the lazily loaded user.posts relationship outside an awaited call raises MissingGreenlet instead of running a hidden query.
How do you recognize the common triggers of a lazy loading error?
Three patterns cause most of these failures. Each one hides a database round trip behind ordinary attribute access.
| Trigger | What happens | Why it fails under AsyncSession |
|---|---|---|
| Relationship not in the query | order.items is read, but the select() never loaded items |
The default lazy="select" strategy tries to emit a SELECT synchronously on first access |
Access after commit() |
user.email is read after await session.commit() |
With expire_on_commit=True (the default), every loaded attribute is expired, so the next read triggers a refresh query |
| Response serialization | Pydantic walks user.orders while building the response |
Serialization often runs after the dependency has closed the session, so the load has no session and no awaitable context |
The third trigger is the hardest to spot. Your endpoint code never mentions the relationship. The response model's field list does the access for you.
Reading the traceback
Read the traceback from the bottom up. The MissingGreenlet frame sits under SQLAlchemy's internal greenlet bridge. Above it you will see ORM attribute machinery and loader strategy frames. Keep going up past every frame inside the SQLAlchemy package. The first frame in your own code, or in Pydantic's validation layer, is the attribute access that started the load. That line tells you which relationship or column you need to load explicitly.
Where loader options fall short
selectinload and similar options only control relationship loading. Implicit I/O can still happen in three places:
- Deferred columns: columns marked
deferred()load on first access unless you undefer them. - Hybrid properties: a hybrid that reads a relationship triggers a lazy load at the instance level.
- Event hooks: listeners that read related state can load data where you don't expect it.
from fastapi import Depends, FastAPI
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import selectinload
from app.models import Order # Order.items = relationship() with default lazy="select"
from app.schemas import OrderOut # Pydantic model: status: str, items: list[ItemOut]
engine = create_async_engine("postgresql+asyncpg://app:change-me@localhost:5432/shop")
# Trigger 2: with the default expire_on_commit=True, commit() expires every
# loaded attribute, so reading order.status afterward emits a refresh SELECT.
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
app = FastAPI()
async def get_session():
async with SessionLocal() as session:
yield session
@app.post("/orders/{order_id}/ship", response_model=OrderOut)
async def ship_order(order_id: int, session: AsyncSession = Depends(get_session)):
# Trigger 1: select(Order) alone leaves Order.items unloaded, so the
# first read of order.items would lazy-load and raise MissingGreenlet.
stmt = (
select(Order)
.where(Order.id == order_id)
.options(selectinload(Order.items)) # load items inside an awaited query
)
order = (await session.execute(stmt)).scalar_one()
order.status = "shipped"
await session.commit()
# Trigger 3: OrderOut reads order.status and order.items after this
# function returns. Both are already in memory (no expiry, eager load),
# so serialization does not need the session or an awaitable context.
return order
A FastAPI endpoint that avoids all three triggers: selectinload covers the relationship the query would otherwise skip, expire_on_commit=False keeps attributes readable after commit, and both together ensure response serialization walks only loaded data.
How does request-scoped session lifetime work in FastAPI?
A request should follow a fixed sequence, and each step depends on the one before it:
- The dependency opens the
AsyncSession. Ayielddependency creates the session from anasync_sessionmakerand hands it to the endpoint. The session belongs to this request and nothing else. - The endpoint queries with explicit loader options. Every relationship the response needs is named up front, for example with
selectinload, so all I/O happens inside awaited calls. - Writes are committed or rolled back. The commit is awaited in the endpoint or the dependency. Any exception triggers a rollback.
- ORM objects become a response model while the session is still open. The endpoint builds the Pydantic model itself instead of returning ORM instances for FastAPI to serialize later.
- The session closes when the dependency's cleanup code runs.
This ordering prevents serialization-time I/O because, by step 4, every attribute the model reads is already in memory. If you return ORM objects and let FastAPI serialize them, the serializer touches attributes outside any await. A missing relationship then becomes a synchronous load attempt, which raises MissingGreenlet. The same failure happens after a commit if expire_on_commit is left enabled, because expired attributes need a refresh. Converting to the response model in the endpoint makes this boundary explicit.
The cost is that the connection stays checked out while the response is built.
Illustrative estimate (assumed numbers, not a benchmark): maximum throughput ≈ pool size ÷ connection hold time. With a pool of 10 and a 50 ms hold, that gives 10 ÷ 0.05 = 200 requests/s. If response building adds 25 ms, the result is 10 ÷ 0.075 ≈ 133 requests/s. With a small pool, keep the conversion step cheap and avoid any non-database awaits while the session is open.
HTTP request
|
v
+--------------------------------------------------------------+
| get_session() dependency |
| 1. async with async_sessionmaker() as session: yield |
+--------------------------------------------------------------+
| session (owned by this request only)
v
+--------------------------------------------------------------+
| endpoint |
| 2. await session.execute(select(...) |
| .options(selectinload(...))) --> all I/O awaited |
| 3. await session.commit() | on exception: rollback() |
| 4. build Pydantic model from loaded attributes |
| (session still open, no lazy load needed) |
+--------------------------------------------------------------+
| response model (plain data, no ORM objects)
v
+--------------------------------------------------------------+
| dependency cleanup |
| 5. session closes, connection returns to pool |
+--------------------------------------------------------------+
|
v
FastAPI serializes model --> no DB access, no MissingGreenlet
|<--------- connection checked out: steps 2 through 5 -------->|
hold time grows with step 4; throughput ~ pool size / hold time
Order of operations in one FastAPI request: all database I/O and the ORM-to-model conversion happen while the AsyncSession is open, so serialization after the session closes reads only in-memory data, at the cost of holding a pooled connection through step 4.
How do you implement explicit loading with AsyncSession in FastAPI?
Start with the session factory. Build it with async_sessionmaker(engine, expire_on_commit=False). By default, a commit expires every loaded attribute, so the next read triggers a refresh. In async code that refresh is implicit I/O, which raises MissingGreenlet. Turning expiry off keeps attributes readable after commit.
The FastAPI dependency opens a session from that factory and yields it to the handler. After the handler returns, the dependency commits. If the handler raises, it rolls back and re-raises. Commit and rollback both live in one place, so handlers never manage transactions themselves.
In each query, state what the response needs:
- Collections: use
selectinload. It issues one extraSELECT ... WHERE id IN (...)per relationship and does not multiply parent rows. - Many-to-one and scalar relationships: use
joinedload. A single LEFT OUTER JOIN adds columns without adding rows. - Nested relationships: chain the options, as in
selectinload(User.orders).selectinload(Order.items). joinedloadon a collection: call.unique()on the result before taking scalars. The join returns one row per child, so parents repeat until you deduplicate them.
After an insert or update, use await session.refresh(obj, attribute_names=[...]) when you need server-generated values such as defaults or timestamps, or a relationship you haven't loaded. Name the attributes explicitly so the refresh does only that work.
Convert ORM objects to Pydantic models with from_attributes enabled, and do it inside the session scope. Every attribute access then happens while a connection is still available.
expire_on_commit=False has a cost. Objects keep whatever values they held at commit, even if another transaction changes those rows later. Nothing refreshes them automatically, so if a code path needs current data, add a refresh there on purpose.
from fastapi import Depends, FastAPI
from pydantic import BaseModel, ConfigDict
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import joinedload, selectinload
from app.models import Order, User # declarative models defined elsewhere
engine = create_async_engine("postgresql+asyncpg://app:change-me@localhost/appdb")
# No expiry on commit, so reading attributes afterwards does not trigger implicit I/O.
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
app = FastAPI()
async def get_session():
async with SessionLocal() as session:
try:
yield session
await session.commit() # one transaction boundary per request
except Exception:
await session.rollback()
raise
class UserOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
@app.get("/users/{user_id}", response_model=UserOut)
async def read_user(user_id: int, session: AsyncSession = Depends(get_session)):
stmt = select(User).where(User.id == user_id).options(
joinedload(User.profile), # many-to-one: a single LEFT OUTER JOIN
selectinload(User.orders).selectinload(Order.items), # nested collections
)
# If you use joinedload on a collection, call .unique() before .scalars().
user = (await session.execute(stmt)).scalars().one()
return UserOut.model_validate(user) # serialize while the session is open
@app.post("/users", response_model=UserOut)
async def create_user(name: str, session: AsyncSession = Depends(get_session)):
user = User(name=name)
session.add(user)
await session.flush() # emit the INSERT so server-generated values exist
await session.refresh(user, attribute_names=["created_at", "orders"]) # load only what is needed
return UserOut.model_validate(user)
Shows an async FastAPI setup with expire_on_commit=False, a commit/rollback dependency, explicit eager loading, targeted refresh after a write, and Pydantic conversion inside the session scope.
selectinload vs joinedload vs raiseload: which loader strategy should you use?
Each strategy makes a different trade-off between round trips, result size, and how loudly it fails.
| Strategy | Extra queries | Row multiplication | Best fit | Failure mode |
|---|---|---|---|---|
selectinload |
One SELECT ... IN per relationship, per level |
None | One-to-many and many-to-many collections | Deep or wide option chains add round trips and can over-fetch |
joinedload |
None (same statement) | Yes, for collections | Many-to-one and one-to-one | Large collections bloat rows; results need unique() |
raiseload |
None, because it blocks the load | None | Guarding every relationship you did not load explicitly | Raises immediately on access |
selectinload is the safe default for collections. Parent rows come back once, and a second statement fetches children by primary key. The cost grows with the option tree. Each nested relationship adds another round trip, and loading relationships the response never uses wastes I/O.
joinedload works best for scalar references, where the join adds columns but not rows. On a collection, each parent row repeats once per child. You must call unique() to deduplicate the results. For large one-to-many relationships, transferring and deduplicating those repeated rows can be slower than a separate selectinload query.
raiseload turns an accidental lazy load into an immediate error at the line that caused it, instead of a MissingGreenlet error later in serialization. Setting lazy='raise' on the model enforces this everywhere. It can also break existing code paths and admin scripts that relied on lazy loading. A per-query raiseload('*') lets you adopt the pattern one endpoint at a time.
Any choice couples query code to the response shape. When the API schema adds or drops a nested field, the loader options must change with it.
When should you avoid workarounds like AsyncAttrs and run_sync?
Two escape hatches make the error go away without touching the query: the AsyncAttrs mixin and session.run_sync(). Both are legitimate, but they solve a different problem than explicit loading does.
AsyncAttrs adds an awaitable_attrs accessor to your models. Writing await user.awaitable_attrs.orders performs the lazy load as a proper awaitable, so no greenlet error is raised. The hidden cost appears when this sits inside a loop over a result set. Fifty users produce fifty round trips. The await keyword makes each call look like deliberate, reviewed I/O, so the N+1 pattern reads as intentional code rather than a bug.
session.run_sync(fn) passes a synchronous Session to fn and runs it in a context where implicit lazy loading works again. It is useful for wrapping legacy synchronous helpers you cannot rewrite yet. The cost is that every attribute access inside fn may issue a query. From the caller's side, all of that I/O collapses into a single await, which is harder to spot than lazy loads in plain sync code.
| Approach | Acceptable for | Hidden cost |
|---|---|---|
awaitable_attrs |
One-off access to a single object's relationship | N+1 queries when used in loops |
run_sync |
Legacy sync code paths during migration | Unbounded queries hidden behind one await |
| Explicit loader options | Default for request handlers | Couples queries to the response shape |
Treat the first two as exceptions and mark each use with a comment. That way the raiseload tests in the next section can still flag new N+1 patterns instead of having them silently absorbed by these workarounds.
How can raiseload integration tests save engineering time?
Give every endpoint one integration test that runs against a real database with raiseload("*") forced onto every ORM query. A test fixture can register a do_orm_execute listener on the session class behind your AsyncSession and append raiseload("*") to each SELECT. Production code stays untouched. Explicit options such as selectinload(Order.items) are more specific than the wildcard and take precedence over it. Any relationship you forgot to load raises InvalidRequestError immediately instead of attempting I/O.
The test itself follows a simple pattern:
- Seed rows that include every related object the response schema serializes.
- Override the session dependency through
app.dependency_overridesso the endpoint uses the instrumented session. - Call the route with an
httpx.AsyncClientoverASGITransport. - Assert a 200 and the expected nested fields.
Empty relationships hide bugs, so seed real children. Because raiseload blocks lazy loads that would have succeeded in sync code, it also catches N+1 regressions that never produce MissingGreenlet.
This has a real cost. Every query needs explicit options, and every change to a response schema means updating both the loader options and the seed data.
Illustrative estimate (assumed numbers, not a benchmark)
- Assumed inputs: 30 endpoints, 20 minutes to write each test, 6 schema changes per quarter at 15 minutes each, and 2 avoided production incidents per quarter at 6 hours of debugging each.
- Upfront cost = endpoints × write time = 30 × 20 min = 10 h, paid once.
- Quarterly upkeep = changes × fix time = 6 × 15 min = 1.5 h.
- Quarterly savings = incidents × debug time = 2 × 6 h = 12 h.
With these assumptions, the tests pay for themselves within the first quarter. Plug in your own numbers to check whether that holds for your team.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to sqlalchemy async lazy loading error, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.