Skip to content

Async API

Date: 2026-08-27

Status

Accepted

Context

Applications built on async frameworks (FastAPI, aiohttp, async workers) need an event store that does not block the event loop. We want to add async support without breaking or degrading the existing synchronous API, which remains fully supported.

Decision

Parallel async classes. Every component gets an async counterpart with the Async prefix: AsyncEventStore, AsyncBackend, AsyncOutbox, AsyncSubscriptionBuilder, AsyncStorageStrategy, etc. Synchronous classes are untouched. We deliberately rejected a-prefixed methods on shared classes to keep contracts explicit and make accidental sync/async mixing impossible.

Public layout mirrors the sync one. Implementation lives in the private event_sourcery._event_store._async subpackage; public proxy imports live in event_sourcery.async_ (following the packaging ADR). Root event_sourcery exports the four main symbols, same as sync: AsyncEventStore, AsyncBackend, AsyncOutbox, AsyncTransactionalBackend.

Asyncio-only. The public async contract targets asyncio. No trio/anyio support is promised.

Deliberate API deviations from sync:

  • position is a coroutine method — await store.position() — because fetching the position performs I/O in real backends. Same applies to AsyncStorageStrategy.current_position.
  • Subscriptions return AsyncIterator; outbox entries are async context managers; outbox publishers are async callables.
  • In-transaction listeners remain synchronous even on async backends. They are dispatched inside the append transaction, where bridging to async callables would either block the loop or break ordering guarantees.
  • KurrentDB outbox creates its persistent subscription lazily (sync variant creates it eagerly in with_outbox(), which cannot await). Because the subscription is anchored at creation time (from_end=True), the async backend ensures creation before the first append that uses the outbox — creating it only on the first outbox run would permanently skip events appended earlier.
  • SQLAlchemy async strategies avoid ORM relationship arms (stream.events.extend(...), stream.snapshots.append(...)) and lazy attribute access: both trigger lazy loads, which are synchronous I/O and raise MissingGreenlet under asyncio. Instead, foreign keys are assigned directly (entry._db_stream_id = stream.id, producing identical INSERT statements) and query results eager-load streams with selectinload. For the same reason, the stream row found by _ensure_stream is passed to insert_events directly instead of being looked up again in session.info["strong_set"] — after a commit, the session expires ORM instances and reading attributes of an expired instance would refresh them lazily.
  • A single AsyncSession cannot interleave concurrent operations. Async SQLAlchemy usage follows the same rule as the sync one: one session (and thus one configured backend) per concurrent unit of work.
  • The async SQLAlchemy backend ships as a new sqlalchemy-async extra (SQLAlchemy[asyncio]). Async drivers (asyncpg, aiosqlite) are not installed by the library — the same policy as the sync variant, which installs no database drivers either.

Testing strategy. The shared test suite is not duplicated: async backends are added as fixtures next to their sync counterparts, and a sync facade (tests/adapter.py) drains coroutines on a dedicated event loop, so every existing BDD-style test exercises both APIs. A small set of true-async tests verifies concurrency semantics directly. Coverage gate stays at 100%.

Consequences

  • Sync and async APIs evolve in parallel; every new feature must land in both.
  • Docs show sync and async snippets side by side (tabs); docs tests use the in-memory backend only, so no docker services are needed.
  • Async variants of SQLAlchemy and KurrentDB backends follow in subsequent milestones; Django async is currently out of scope.

Amendment 2026-08-27: SQLAlchemy backend milestone

The SQLAlchemy milestone validated the decisions above against a real relational backend. Consequences specific to it:

  • The mirrored test suite runs against sqlalchemy_async_sqlite and sqlalchemy_async_postgres fixtures through the sync facade. Test transactions are never committed, so fixture teardown closes all tracked sessions before dropping tables (mirroring the sync suite's close_all_sessions()) — otherwise DROP TABLE deadlocks against locks held by open transactions.
  • In-transaction listeners fired inside the append transaction work unchanged: the async dispatcher awaits deserialization before invoking synchronous listeners.

Amendment 2026-08-28: parity wrap-up

Milestone 4 closed the remaining gaps, with two notable designs:

  • Async encryption pipeline. AsyncEncryption / AsyncEncryptionKeyStorageStrategy mirror their sync counterparts; AsyncSerde exclusively awaits an AsyncEncryption. AsyncBackend.with_encryption accepts only async key storage. The async in-transaction dispatcher awaits deserialization, then invokes synchronous listeners. Sync backends retain their separate synchronous pipeline.
  • In-transaction dispatcher only deserializes on matching listeners. Dispatcher resolves event types lazily via EventRegistry, which keeps the (possibly stubbed) serde untouched when no listener is registered.
  • AsyncRepository, AsyncProjector, AsyncCursorsDao, AsyncReadModel, AsyncSqlAlchemyCursorsDao complete the feature parity.

Parity audit (sync → async)

Sync Async (or documented exclusion)
Backend / TransactionalBackend AsyncBackend / AsyncTransactionalBackend
EventStore AsyncEventStore
Outbox (run) AsyncOutbox (run)
StorageStrategy AsyncStorageStrategy
SubscriptionStrategy AsyncSubscriptionStrategy
OutboxStorageStrategy AsyncOutboxStorageStrategy
PositionPhase / FilterPhase / BuildPhase async counterparts
SubscriptionBuilder AsyncSubscriptionBuilder
NoKeyStorageStrategy AsyncNoKeyStorageStrategy
Encryption AsyncEncryption (shred via ashred)
EncryptionKeyStorageStrategy AsyncEncryptionKeyStorageStrategy
Repository AsyncRepository
CursorsDao AsyncCursorsDao
Projector AsyncProjector
ReadModel (callable) AsyncReadModel (async callable)
SqlAlchemyCursorsDao AsyncSqlAlchemyCursorsDao
InMemoryBackend / InMemoryKeyStorage Async* counterparts
In-transaction listeners remain sync (ADR §2.4), dispatched under lazy resolution