- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
The INSERT is in the database. The response never leaves the server. The line that raised is return {"total": order.total}, one line after await session.commit(), in a handler freshly ported from sync to async, and the exception is sqlalchemy.exc.MissingGreenlet.
Nothing in that line looks like I/O. It is an attribute read on an object you built three lines earlier. The error text, greenlet_spawn has not been called (source), points at a library most people never imported. The SQLAlchemy error reference is blunter: with the ORM, this error is "nearly always due to the use of lazy loading."
So the attribute read was a lazy load. Of a column you set yourself. The sync version of the same code runs that load without a word, which is why the fix belongs at the adapter boundary as well as in the session config.
Everything here targets SQLAlchemy 2.1 (2.1.9 is current as of this writing). The behaviour and the docs advice are the same on 2.0. I haven't pasted any run output below; the behaviour described comes from the SQLAlchemy docs linked at each step.
Commit expires everything you loaded
A Session keeps an identity map. The session basics docs describe it as a structure where only one object with a particular primary key exists per session. When you add OrderRow(customer="alice", total=4200) and flush, that Python object becomes the session's copy of that row.
Then you commit. The Session constructor has a flag, expire_on_commit, and its API docs say it defaults to True: "all instances will be fully expired after each commit()". Expired means the loaded attribute values are erased. The session basics docs put it as contents "erased to be re-loaded within the next transaction."
The reasoning is sound for a sync app. After commit, other transactions may have changed that row. Rather than hand you values that might be stale, the session forgets them and fetches fresh ones on the next read. The expiring docs say expired attributes "will be loaded from the database when they are next accessed."
That last clause is the whole bug. "When they are next accessed" means a plain order.total now runs a query.

Commit erases the loaded values. The next read has to go back to the database for them.
The reproducible script
Install the async extra. In 2.1, the asyncio docs note that greenlet is no longer installed by default, so you need pip install "sqlalchemy[asyncio]" aiosqlite. aiosqlite keeps the script self-contained, with no server to start.
# repro_async.py import asyncio from sqlalchemy import String from sqlalchemy.ext.asyncio import ( async_sessionmaker, create_async_engine, ) from sqlalchemy.orm import ( DeclarativeBase, Mapped, mapped_column, ) class Base(DeclarativeBase): pass class OrderRow(Base): __tablename__ = "orders" id: Mapped[int] = mapped_column(primary_key=True) customer: Mapped[str] = mapped_column(String(50)) total: Mapped[int] # cents async def main() -> None: engine = create_async_engine( "sqlite+aiosqlite:///orders.db", echo=True ) async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) sessions = async_sessionmaker(engine) async with sessions() as session: order = OrderRow(customer="alice", total=4200) session.add(order) await session.commit() print(order.total) # MissingGreenlet await engine.dispose() asyncio.run(main()) async_sessionmaker(engine) keeps the default, so commit expires order. The print line asks for total, the attribute is gone, and the ORM tries to load it.
Async differs here. SQLAlchemy's async layer runs the ORM's sync internals inside a greenlet that greenlet_spawn sets up, so that deep inside, the driver call can be awaited. An await session.commit() goes through that bridge. A bare attribute access does not: it is a normal Python __get__, called from your coroutine, with no await in front of it and no greenlet context around it. The lazy load reaches the async driver, finds no greenlet to switch through, and raises. The MissingGreenlet entry describes exactly that: a call to the async DBAPI "initiated outside the greenlet spawn context."
The async version is the honest one. It refuses to do hidden I/O and tells you so.
The sync version runs the same query and says nothing
Swap the engine and session for their sync twins:
# repro_sync.py (same Base and OrderRow) from sqlalchemy import create_engine from sqlalchemy.orm import Session engine = create_engine("sqlite:///orders.db", echo=True) Base.metadata.create_all(engine) with Session(engine) as session: order = OrderRow(customer="alice", total=4200) session.add(order) session.commit() print(order.total) # works, costs a query This prints 4200. It also, per the expiry docs above, goes back to the database: the session begins a new transaction and selects the row by its primary key to refill the expired columns. With echo=True on, that SELECT shows up in the log right after the COMMIT, and that log line is the only sign anything happened.
That quiet query has two costs that the async error spares you. First, a loop that commits and then reads each object pays one extra round trip per object. Second, move the read outside the with block and the session is closed by then. The object is detached with expired attributes, and you get the error that the SQLAlchemy docs describe as an object "de-associated with its Session" being "asked to lazy load data from the database." Same root cause, different symptom, found later.

Async raises at the read. Sync pays for the read with a query and keeps going.
What the docs tell you to do
The asyncio guide has a whole section titled "Preventing Implicit IO when Using AsyncSession." Its first answer for this exact case is the session factory:
sessions = async_sessionmaker( engine, expire_on_commit=False ) The guide's own example carries the comment "access attribute subsequent to commit; this is what expire_on_commit=False allows," and elsewhere states that expire_on_commit "should normally be set to False when using asyncio."
For the cases where you do want fresh values, the same page gives two awaitable ways to load the values. await session.refresh(order) reloads the object explicitly, and the docs say to prefer it over expiring. The AsyncAttrs mixin (added in 2.0.13) exposes any attribute as an awaitable through awaitable_attrs, as in the docs' await a1.awaitable_attrs.bs. For relationships, the guide adds selectinload() for eager loading and lazy="raise" so a relationship never emits SQL on its own.
Turning expiry off has a price. After commit, order.total is whatever your process last saw. If a trigger, a default computed in the database, or another writer changed the row, your object does not know. On backends without RETURNING, the same guide warns that server defaults such as generated timestamps "will not be available on newly flushed objects" unless you set eager_defaults.
All of that is correct and you should do it. It still leaves the ORM object travelling through your app with a live connection to a session's rules. Every place that touches it, a serializer, a template, a log line, a background task, is a place where an attribute read can turn into SQL or into an exception.
The design fix: nothing ORM leaves the adapter
The class of bug goes away when the ORM row never crosses the adapter boundary. The core of your app works with a plain domain object. The repository adapter is the only code that holds an OrderRow, and it converts the row before returning:
# app/domain.py from dataclasses import dataclass @dataclass(frozen=True) class Order: id: int customer: str total: int # cents # app/ports.py from typing import Protocol from app.domain import Order class Orders(Protocol): async def add( self, customer: str, total: int ) -> Order: ... async def get(self, order_id: int) -> Order | None: ... # app/adapters/sql_orders.py from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, ) from app.adapters.tables import OrderRow from app.domain import Order def _to_domain(row: OrderRow) -> Order: return Order(row.id, row.customer, row.total) class SqlOrders: def __init__( self, sessions: async_sessionmaker[AsyncSession] ) -> None: self._sessions = sessions async def add(self, customer: str, total: int) -> Order: async with self._sessions() as session: row = OrderRow(customer=customer, total=total) session.add(row) await session.flush() order = _to_domain(row) # before commit await session.commit() return order async def get(self, order_id: int) -> Order | None: async with self._sessions() as session: row = await session.get(OrderRow, order_id) return _to_domain(row) if row else None The flush() sends the INSERT and fills in row.id, and the other two columns are the values you just set. The mapping reads them while they are still loaded. Commit then expires row, which nobody holds anymore. What leaves the adapter is a frozen dataclass: reading order.total on it is a plain attribute read, in any context.
The bug can still be written: call _to_domain(row) after the commit and the adapter raises MissingGreenlet itself. The difference is where. It fails in one function, in one file, and an integration test of SqlOrders against a real database catches it the first time it runs. The endpoint, the FastAPI response model, the Pydantic serializer that builds a model "by getting attributes on the object," none of them ever see an ORM instance, so none of them can trigger a load.
The same boundary pays off in the tests that don't touch a database at all. A fake that satisfies the port is a dict:
# tests/fakes.py from app.domain import Order class InMemoryOrders: def __init__(self) -> None: self._rows: dict[int, Order] = {} async def add(self, customer: str, total: int) -> Order: order = Order(len(self._rows) + 1, customer, total) self._rows[order.id] = order return order async def get(self, order_id: int) -> Order | None: return self._rows.get(order_id) Your use-case tests run against InMemoryOrders with no engine, no greenlet and no event-loop fixture for a database. The one adapter test that needs SQLite or Postgres is the one that guards the mapping. One caveat for real apps: opening a session per call, as SqlOrders does, gives each call its own transaction. When a use case needs two writes to commit together, put a unit-of-work port in front of the session and keep the same rule: map before commit, return domain objects.
Next time MissingGreenlet shows up after a commit, check the session factory first, then look for the first place an OrderRow escaped its adapter. That is where the fix goes.
If this was useful
The fix in this post is one instance of the idea Hexagonal Architecture in Python is built on: keep SQLAlchemy behind an adapter so the core of the app, and its tests, never depend on how a session behaves. The book builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice) and then measures them, so you can see where the repository boundary sits in each. Every listing runs from the free companion repo if you'd like to read the adapters before you buy anything.


