Source: https://fireflyframework.org/frameworks/python/
Language: en

pyfly, the Python framework by Firefly

# 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.

[Read the documentation](https://fireflyframework.github.io/fireflyframework-pyfly/docs/) [View the source](https://github.com/fireflyframework/fireflyframework-pyfly)

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

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.

[User configuration, defaults, startup and post-processors](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/context/application_context.py#L418-L445)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/context/application_context.py#L307-L333)

### 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.

[Derived queries, unit participation and exception translation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/data/relational/sqlalchemy/post_processor.py#L65-L81)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/domain/aggregate_root.py#L14-L35)

### 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.

[Event, snapshot and checkpoint stores with EDA publication](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/eventsourcing/auto_configuration.py#L83-L149)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/cqrs/config/auto_configuration.py#L83-L165)

### 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.

[Delivery claims, retries, dead letters and lifecycle](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/eda/outbox.py#L29-L87)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/eda/auto_configuration.py#L14-L45)

### 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.

[Workflow composition, lifecycle drain, saga recovery and health](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/transactional/auto_configuration.py#L435-L482)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/transactional/auto_configuration.py#L149-L173)

### 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.

[Retry and transaction composition](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/data/transaction/decorator.py#L40-L47)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/client/declarative.py#L28-L56)

### 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.

[Security/tenant context and metrics/exposure hooks](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/feature_flags/auto_configuration.py#L199-L229)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/security/auto_configuration.py#L359-L421)

### 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.

[Framework OpenFeature client, hooks and binding](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/feature_flags/auto_configuration.py#L219-L268)

[See the implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/actuator/auto_configuration.py#L32-L58)

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.

[Bus/cache/EDA composition](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/cqrs/config/auto_configuration.py#L122-L165) [Projection application with checkpoint batches](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/eventsourcing/projection.py#L236-L276)

Capabilities

## Pick the modules your service needs.

pyfly / Conceptual architecture

Typed dependency injection composes the controllers, the template engine, the repositories, the handlers, and the sagas.

1. [01Typed dependency injection](https://fireflyframework.org/frameworks/python/#python-capability-0)
2. [02Async HTTP controllers](https://fireflyframework.org/frameworks/python/#python-capability-1)
3. [03Server-rendered HTML and forms](https://fireflyframework.org/frameworks/python/#python-capability-2)
4. [04Repositories and transactions](https://fireflyframework.org/frameworks/python/#python-capability-3)
5. [05Commands, queries, and handlers](https://fireflyframework.org/frameworks/python/#python-capability-4)
6. [06Sagas with compensation](https://fireflyframework.org/frameworks/python/#python-capability-5)

Amber: Firefly modules · Ivory lines: APIs · Amber 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](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/container/container.py#L807-L860)

### Async HTTP controllers

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

[See the source](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/web/adapters/starlette/controller.py#L95-L133)

### 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](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/web/templating/adapters/jinja.py#L37-L73)

### 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](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/data/transaction/decorator.py#L64-L90)

### 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](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/cqrs/command/bus.py#L152-L197)

### 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](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/transactional/saga/engine/saga_engine.py#L110-L192)

### Native Agentic module

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

[See the source](https://github.com/fireflyframework/fireflyframework-pyfly/blob/46919f58cca4f17521213248ae7f01f8a89953d1/docs/modules/agentic/native-runtime.md)

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

```python
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
```

[View the full file](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/samples/lumen/src/lumen/core/services/wallets/get_wallet_handler.py#L13-L30)

### 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

```python
    @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
```

[View the full file](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/samples/lumen/src/lumen/core/services/wallets/open_wallet_handler.py#L50-L61)

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.

[Read the documentation](https://fireflyframework.github.io/fireflyframework-pyfly/docs/) [View the v26.10.11 release](https://github.com/fireflyframework/fireflyframework-pyfly/releases/tag/v26.10.11)

### The PyPI package named pyfly is another project

Install the artifacts attached to the GitHub release. A plain `pip install pyfly` fetches that other project.

[View the release](https://github.com/fireflyframework/fireflyframework-pyfly/releases/tag/v26.10.11)

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](https://github.com/fireflyframework/fireflyframework-pyfly/tree/46919f58cca4f17521213248ae7f01f8a89953d1/book/manuscript)
- [English PDF](https://github.com/fireflyframework/fireflyframework-pyfly/releases/download/v26.10.11/pyfly-by-example.pdf)
- [English EPUB](https://github.com/fireflyframework/fireflyframework-pyfly/releases/download/v26.10.11/pyfly-by-example.epub)
- [Spanish PDF](https://github.com/fireflyframework/fireflyframework-pyfly/releases/download/v26.10.11/pyfly-by-example-es.pdf)
- [Spanish EPUB](https://github.com/fireflyframework/fireflyframework-pyfly/releases/download/v26.10.11/pyfly-by-example-es.epub)

v26.10.11 edition · 21 chapters · Six parts

Related

## Samples and the native Agentic module.

### Lumen wallet service

The book’s sample application, with its domain, persistence, and application tests.

[View the source](https://github.com/fireflyframework/fireflyframework-pyfly/tree/bb65c1bdc43602979ce79d60621878010eea2a90/samples/lumen)

### Server-rendered web application

A catalog sample with HTML templates, forms, and model administration.

[View the source](https://github.com/fireflyframework/fireflyframework-pyfly/tree/bb65c1bdc43602979ce79d60621878010eea2a90/samples/webapp)

### pyfly agentic

pyfly’s optional AI module provides typed agents, tools, memory, retrieval, pipelines, and workflows.

[View the source](https://fireflyframework.org/agentic/)

### Agentic book chapters · EN / ES

Native Agentic chapters in English and Spanish.

[View the source](https://github.com/fireflyframework/fireflyframework-pyfly/tree/46919f58cca4f17521213248ae7f01f8a89953d1/book)

Sources behind this page

- [Runtime and optional dependencies](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/pyproject.toml#L5-L55)
- [Controller integration tests](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/tests/web/test_app_controllers.py#L48-L85)
- [Typed forms and CSRF tests](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/tests/web/test_forms.py#L14-L79)
- [Lumen application-context test](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/samples/lumen/tests/test_app_context_integration.py#L35-L85)
- [Saga compensation tests](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/tests/transactional/saga/test_saga_engine.py#L242-L288)
- [Release commit CI](https://github.com/fireflyframework/fireflyframework-pyfly/actions/runs/40129668892)
- [Command pipeline implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/cqrs/command/bus.py#L152-L200)
- [Outbox transaction and delivery test](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/tests/integration/test_eda_outbox_matrix.py#L108-L134)
- [Database bus implementation](https://github.com/fireflyframework/fireflyframework-pyfly/blob/bb65c1bdc43602979ce79d60621878010eea2a90/src/pyfly/eda/adapters/database.py#L393-L427)
- [Native async transaction support](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.async_sessionmaker.begin)

Next step

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

[Read the documentation](https://fireflyframework.github.io/fireflyframework-pyfly/docs/) [Open the sample](https://github.com/fireflyframework/fireflyframework-pyfly/tree/46919f58cca4f17521213248ae7f01f8a89953d1/samples/lumen)
