One framework for a whole async Python service.

One pyfly package brings typed dependency injection, repositories, CQRS, brokers with an optional outbox, workflows and sagas, JWT security, and feature flags.

  1. 01 Application composition
  2. 02 Domain and repositories
  3. 03 Commands and read models
  4. 04 Messaging and delivery
  5. 05 Business processes
  6. 06 Clients and resilience
  7. 07 Identity and policy
  8. 08 Operations and rollout
Python 3.12+ · Starlette or FastAPI · SQLAlchemy
Scroll to explore

Native stack and framework

What pyfly adds to FastAPI and SQLAlchemy.

FastAPI and SQLAlchemy still handle HTTP and data. pyfly’s application context starts your components in dependency order and stops them on shutdown.

Application composition

Lifecycle beans start by phase, then creation order, after the beans they depend on.

With FastAPI and SQLAlchemy alone, your team builds
An application-wide model from FastAPI dependencies, lifespan hooks, configuration, and optional integrations.
pyfly provides
Component discovery, conditional assembly, typed configuration, and ordered startup and shutdown in the application’s async context.
How it works

ApplicationContext evaluates profiles and conditions, registers your beans before the framework’s defaults, and then starts lifecycle infrastructure.

Declare your own bean to replace a default.

See the implementation

Domain and repositories

Aggregates hold the business rules and record events, and repositories derive queries from method names or @query.

With FastAPI and SQLAlchemy alone, your team builds
Domain and event contracts, plus repository and query conventions around SQLAlchemy sessions.
pyfly provides
Domain aggregates and generated repository queries on shared persistence and unit-of-work conventions.
How it works

AggregateRoot records domain events, and RepositoryBeanPostProcessor compiles derived and annotated queries when it builds a repository.

Aggregates store current state. Add event sourcing to keep the history.

See the implementation

Commands and read models

Handlers keep to business logic, and the bus supplies validation, authorization, correlation, and metrics.

With FastAPI and SQLAlchemy alone, your team builds
Validation, authorization, caching, event publication, and any event-sourced read models, called from each handler.
pyfly provides
A CQRS pipeline that applies those policies, plus optional event stores, snapshots, and projections.
How it works

CQRS configuration connects validation, authorization, correlation, metrics, event publication, and query caching. ProjectionRunner applies stored events in checkpoint batches.

Event stores default to memory. The SQLAlchemy stores persist events.

See the implementation

Messaging and delivery

Business code publishes through EventPublisher to whichever broker is configured.

With FastAPI and SQLAlchemy alone, your team builds
Broker SDK integrations, listener lifecycles, event envelopes, retries, and delivery operations.
pyfly provides
A publish and listen model with selectable brokers, outbox adapters, relays, and failure handling.
How it works

EdaAutoConfiguration binds EventPublisher to Kafka, RabbitMQ, Redis Streams, a database or PostgreSQL bus, or memory. Outbox relays handle retries and dead letters.

To commit an event with its write, use the database or PostgreSQL outbox on the write’s datasource.

See the implementation

Business processes

Your steps hold the business work while the engines handle compensation and recovery.

With FastAPI and SQLAlchemy alone, your team builds
Workflow or saga tooling of your choice, wired to execution state, step dependencies, and compensation.
pyfly provides
Workflow, saga, and TCC engines that share one execution store, in memory by default.
How it works

TransactionalEngineAutoConfiguration assembles the engines with compensation, persistence, recovery, health, and metrics. Shutdown drains running workflows.

Keep saga and TCC state across restarts with a Redis or SQLAlchemy execution store.

See the implementation

Clients and resilience

Downstream calls reuse named retry and circuit-breaker policies across integrations.

With FastAPI and SQLAlchemy alone, your team builds
HTTP client wrappers with timeout, retry, and circuit-breaker policies.
pyfly provides
Declarative service clients that apply the configured policies and follow the component lifecycle.
How it works

@service_client methods get retry and circuit-breaker wrappers at startup, and retries run outside the transaction, each in a fresh unit of work.

Retry only safe or idempotent calls, or add a compensating safeguard.

See the implementation

Identity and policy

CQRS authorization and feature flags both see the request’s user and tenant.

With FastAPI and SQLAlchemy alone, your team builds
Code that joins security dependencies and identity SDKs to handler permissions and tenant conventions.
pyfly provides
JWT and OIDC adapters, principal mapping, and CQRS authorization, sharing their identity with feature flags.
How it works

Security configuration validates JWT and OIDC tokens, and CQRS authorization calls your hooks. Feature flags read the same identity and tenant.

Your team configures the identity provider, the permission rules, and tenant-header trust.

See the implementation

Operations and rollout

Operators get health endpoints. Flag evaluations are counted and can publish exposure events.

With FastAPI and SQLAlchemy alone, your team builds
Telemetry, health checks, management endpoints, and feature-flag SDK setup.
pyfly provides
Actuator health endpoints, Prometheus and OpenTelemetry integrations, and OpenFeature flags.
How it works

Actuator serves health and optional Prometheus endpoints. OpenFeature hooks count flag evaluations and can publish exposure events.

pyfly leaves third-party clients uninstrumented. Restrict management endpoints to your operators.

See the implementation
Already in the native stack
FastAPI routes and validates requests, serves OpenAPI, and injects dependencies. SQLAlchemy runs async sessions and transactions, and an outbox library can add event delivery.
Your team still owns
Domain rules, authorization policies, schemas and migrations, event payloads, database configuration, consumer idempotency, and running the service.

Request path

A pyfly command’s path, from the bus to your read models.

pyfly’s command bus surrounds your handler: checks run before it, and cache updates and events follow its commit.

From a business command to current read models

  1. ApplicationContext resolves the handler and the collaborators it declares.
  2. The command bus validates the command and calls its authorize() hook.
  3. The handler works through a repository inside the unit of work.
  4. The commit invalidates cached queries and publishes the events you configured.
  5. Event-store or messaging consumers update your projections and integrations.
  6. The bus records metrics, and a CQRS health indicator reports to /actuator/health.

Event sourcing is optional, and persistent delivery needs its storage and messaging configured.

Capabilities

Pick the modules your service needs.

pyfly / Conceptual architectureTyped dependency injection composes the controllers, the template engine, the repositories, the handlers, and the sagas.

Amber: Firefly modulesIvory lines: APIsAmber lines: events

Typed dependency injection

Declare application services and let pyfly resolve constructor dependencies from type hints. Named beans, qualifiers, and ordered collections make multiple implementations explicit.

See the source

Async HTTP controllers

Map async controller methods to HTTP routes, with their services injected. The web layer can also expose OpenAPI.

See the source

Server-rendered HTML and forms

Render Jinja templates and bind typed forms with escaping, validation, upload limits, and CSRF checks, in the same application as your APIs.

See the source

Repositories and transactions

Repositories run on SQLAlchemy, and @transactional marks each async transaction boundary. You choose its propagation and rollback rules per operation.

See the source

Commands, queries, and handlers

Thin controllers send commands and queries to their own handlers. The command bus validates each command, calls its authorize() hook, publishes its events, and records metrics.

See the source

Sagas with compensation

A saga runs a multi-step operation and compensates when a step fails. Hooks let your application store its state and react to its events.

See the source

Native Agentic module

The optional pyfly.agentic module adds typed agents, tools, memory, retrieval, pipelines, and workflows.

See the source

Code

The query handler that loads a Lumen wallet.

GetWalletHandler receives its repository through the constructor, loads a wallet by id, and returns it as a WalletDto, or None when the wallet doesn’t exist.

Follow a wallet from request to balance

  1. Receive the request

    WalletController validates the request body, sends an OpenWallet command, and returns the response.

  2. Apply the business operation

    OpenWalletHandler creates the wallet and saves it through the repository, inside a transaction that rolls back on failure.

  3. Read the balance

    The query bus routes GetBalance to its handler. The sample’s tests open a wallet, deposit, and withdraw.

get_wallet_handler.py
from lumen.core.mappers.wallet_mapper import entity_to_dto
from lumen.core.services.wallets.get_wallet_query import GetWallet
from lumen.interfaces.dtos.v1.wallet_dto import WalletDto
from lumen.models.repositories.wallet_repository import WalletRepository
from pyfly.container import service
from pyfly.cqrs import QueryHandler, query_handler


@query_handler
@service
class GetWalletHandler(QueryHandler[GetWallet, WalletDto | None]):
    def __init__(self, repository: WalletRepository) -> None:
        super().__init__()
        self._repository = repository

    async def do_handle(self, query: GetWallet) -> WalletDto | None:  # type: ignore[override]
        entity = await self._repository.find_by_id(query.wallet_id)
        return entity_to_dto(entity) if entity is not None else None

A command handler inside one transaction

OpenWalletHandler saves a wallet and publishes its events inside its @transactional unit. With the database or PostgreSQL outbox on the same datasource, the events commit with the wallet. Lumen’s default publisher is in memory.

open_wallet_handler.py
    @transactional()
    async def do_handle(self, command: OpenWallet) -> str:  # type: ignore[override]
        wallet_id = f"wlt-{uuid4()}"
        wallet = Wallet.open(
            wallet_id=wallet_id,
            owner_id=command.owner_id,
            currency=command.currency,
        )
        await self._repository.upsert(to_entity(wallet))

        await publish_domain_events(self._events, wallet.clear_events())
        return wallet_id

Releases and setup

Get pyfly from its GitHub release.

Choose the web and data extras your service uses, plus a database driver. The outbox also needs its framework tables, consumer groups, and relay.

pyfly v26.10.11 is published on GitHub Releases. Its CI passed on Python 3.12 and 3.13, with native Agentic, browser, and installed-package checks.

Delivery is at least once, so consumers must tolerate redelivery. Workflow signals and timers are process-local: a wait that must survive a restart needs an external durable runtime.

Front cover of pyfly by example

pyfly by example

Building connected business systems with async Python

The book builds the Lumen wallet and ledger service through dependency injection, HTTP APIs, persistence, CQRS, events, and orchestration. An appendix covers server-rendered HTML and forms. Three chapters add native agents, knowledge, workflows, and operations.

Read the manuscript

v26.10.11 edition · 21 chapters · Six parts

Next step

Run the Lumen wallet’s tests, then read its handlers.