Transactions¶
TransactionalBehavior is a pipeline behavior that wraps message handling in a unit-of-work
commit/rollback cycle. It commits on success and rolls back on any failure — including
failures during the commit itself.
IUnitOfWork Protocol¶
IUnitOfWork is a two-method protocol that lives at the top level (waku.uow), not inside
messaging — it's a general infrastructure concern usable by any layer.
from waku.uow import IUnitOfWork
class IUnitOfWork(Protocol):
async def commit(self) -> None: ...
async def rollback(self) -> None: ...
The protocol is defined by waku — you only need to provide an implementation. Any class that
satisfies it can serve as the unit of work for TransactionalBehavior.
SQLAlchemy Adapter¶
SqlAlchemyUnitOfWork wraps an AsyncSession and delegates commit() / rollback() to it:
Register it in your infrastructure module, mapping the implementation to IUnitOfWork:
SqlAlchemyUnitOfWork receives the AsyncSession via dependency injection, so make sure you
have a session provider registered in one of your modules.
TransactionalBehavior¶
TransactionalBehavior follows a strict commit/rollback sequence:
- Call
call_next()(the handler, plus any remaining behaviors). - On success:
uow.commit(). - On handler exception:
uow.rollback(), re-raise. - On commit exception:
uow.rollback(), re-raise.
Register it as a global pipeline behavior:
Warning
When registered globally, TransactionalBehavior applies to every message flowing
through the bus — including read-only queries. This means every query opens and commits
a transaction, even when there are no writes.
Tip
Use per-request behaviors if you only want transactions on write commands:
Wiring Example¶
A complete setup with SQLAlchemy session, unit of work, and TransactionalBehavior:
Custom UoW¶
Implement IUnitOfWork for any backend — the protocol requires only commit and rollback:
Register it the same way as the SQLAlchemy adapter:
Further reading¶
- Pipeline Behaviors — defining, registering, and ordering behaviors
- Routing & Endpoints — route messages to background endpoints
- Message Bus — setup, interfaces, and complete example