Skip to content

Contents

A complete listing of every page in the Protean documentation. Use your browser's search (Ctrl+F / Cmd+F) to find any topic.


Getting Started

  • Installation: Set up Python and install Protean.
  • Hello, Protean!: Define, save, and load your first aggregate in under 20 lines.
  • Quickstart: Build a domain in 5 minutes with in-memory adapters.

Tutorial: Building Bookshelf

A guided, hands-on tutorial building a complete online bookstore.

Part I: Building the Domain

Part II: Making It Real

Part III: Growing the System

Part IV: Production Operations

Part V: System Mastery


Guides

Comprehensive reference organized by topic. Each guide goes deep on a specific area.

  • Guide Overview: How the guides are organized and where to start.
  • How Do I...?: Task-oriented index: find the right guide by what you're trying to do.

Choose a Path

Set Up the Domain

Define Domain Elements

  • Defining Concepts: Foundational domain concepts using DDD tactical patterns.
  • Aggregates: Model domain concepts with unique identity.
  • Entities: Objects with identity that compose aggregates.
  • Value Objects: Immutable descriptive objects identified by their attributes.
  • Fields: Declare attributes on domain elements: types, required flags, defaults, constraints, validators.
  • Declaring Indexes: Declare composite, unique, partial, and covering indexes on aggregates and entities.
  • Identity: Configure identity generation: UUIDs, integers, user-supplied keys, or a custom function.
  • Expressing Relationships: Model associations between domain elements.
  • Events: Model past changes as discrete, meaningful facts.
  • Choosing Element Types: Checklists and decision flows for choosing element types.

Field & Identity Reference

Add Rules and Behavior

  • Domain Behavior: Enforcing business rules through validations, invariants, and methods.
  • Validations: Field-level validation using types, options, and custom validators.
  • Invariants: Business rules that must always hold true within an aggregate.
  • Mutating Aggregates: Modify state through named methods reflecting actions and events.
  • Status Transitions: Enforce lifecycle state machines with the Status field.
  • Raising Events: Notify other parts of the system through domain events.
  • Message Tracing: Track the full causal chain of commands and events with correlation and causation IDs, and traverse causation chains programmatically.
  • Correlation and Causation IDs: Complete guide to correlation and causation ID propagation across HTTP headers, OTEL spans, Observatory traces, structured logging, and cross-service boundaries.
  • Explore Your Domain in the Observatory: Use the Observatory's Domain Visualizer (topology, event flows, process managers) and Timeline (event browser, correlation chains, traces) to navigate a running domain.
  • Domain Services: Complex domain logic that spans multiple aggregates.
  • Error Handling: Raise, propagate, and handle domain exceptions.

Change State

  • Changing State: Mechanisms for state changes: services, commands, and handlers.
  • Application Services: Bridge between the API layer and the domain model.
  • Commands: Data transfer objects expressing intention to change state.
  • Command Handlers: Process commands and execute domain logic.
  • Repositories: Define custom repositories, the DAO layer, and database-specific persistence.
  • Persist Aggregates: Save aggregates using a repository's add method.
  • Retrieve Aggregates: QuerySets, filtering, Q objects, bulk operations, and result navigation.
  • Temporal Queries: Reconstitute event-sourced aggregates at a specific version or point in time.
  • Unit of Work: Automatic transaction management for aggregate changes.
  • Custom Database Models: Override auto-generated storage schemas with adapter-specific tuning.
  • Event Store Setup: Choose, configure, and operate an event store.
  • Snapshots: Optimize event-sourced aggregate loading with periodic checkpoints.

React to Changes

  • Consuming State Changes: React to state changes through handlers, projections, and subscribers.
  • Event Handlers: Consume events to sync state or trigger side effects.
  • Process Managers: Coordinate multi-step processes across aggregates with stateful, event-sourced coordination.
  • Projections: Create read-optimized views built from events.
  • Projectors: Define event handlers that maintain projections.
  • Query Handlers: Process queries and return results from projections.
  • Subscribers: Consume messages from external brokers.
  • CloudEvents Interoperability: Serialize events to CloudEvents v1.0 for external systems, and consume CloudEvents from external sources.
  • Stream Categories: How messages are organized and routed.
  • Event Upcasting: Transforming old event schemas to match the current version during replay.
  • Evolving Events Over Time: The full event-evolution workflow: add fields, rename with renamed_from, deprecate/supersede, upcast, and check compatibility.

Run in Production

  • Configuration: Configure Protean through domain.toml and environment variables.
  • FastAPI Integration: Domain context middleware, exception handlers, and best practices for using Protean with FastAPI.
  • HTTP wide events: One wide event per HTTP request via DomainContextMiddleware, correlation with domain-layer wide events, [logging.http] configuration.

Observability

  • Logging: Configure structured logging, enrich wide events with business context, tail sampling, security events, disable auto-configuration.
  • Logging Reference: Every [logging] key, every framework logger, every structured event and its fields.
  • Logging Concepts: Wide events, query-oriented field design, the two-layer HTTP + domain split, tail sampling, high-cardinality backends, redaction as a pipeline stage.

Server

  • Server Overview: Asynchronous message processing engine for events, commands, and external messages.
  • Engine Architecture: Core async processing, managing subscriptions and lifecycle.
  • Subscriptions: Connect handlers to message sources.
  • Subscription Types: Stream and EventStore subscriptions for different use cases.
  • Subscription Configuration: Flexible configuration with priority hierarchy.
  • Outbox Pattern: Reliable message delivery via same-transaction storage.
  • Observability: Real-time tracing, the Observatory monitoring server, SSE streaming, and Prometheus metrics.
  • OpenTelemetry Integration: Distributed tracing, metrics, APM setup, and TraceParent propagation with OpenTelemetry.
  • Running the Server: Start, configure, and operate the Protean server.
  • Harden the Server: Raise pool limits, enable K8s health probes, run DLQ maintenance, pick subscription profiles, emit OTEL metrics, and shut down gracefully.
  • Tuning Subscriptions: Pick a profile, override one setting, cap stream growth, use the circuit breaker, process events for one entity in order, and check consumer lag.
  • Server Hardening Reference: Every option, default, metric, and profile shipped by the hardening epic.
  • Error Handling: Retry logic, dead letter queues, and recovery mechanisms for message processing failures.
  • Dead Letter Queues: Discover, inspect, replay, and purge messages that failed after retries were exhausted.
  • Using the Outbox: Reliably publish domain events via the outbox pattern; configuration, retries, cleanup.
  • Dispatching Published Events to External Brokers: Configure external brokers to deliver published events to other bounded contexts.

CLI

  • CLI Overview: The protean command-line interface for scaffolding and management.
  • protean check: Validate a domain and report architecture fitness diagnostics as rich, JSON, SARIF, or GitHub annotations.
  • protean upgrade-check: Read-only diagnostic that reports the 0.16 upgrade actions for a domain (elements, config, infra) and generates the outbox migration SQL.
  • Domain Discovery: Use --domain to load and initialize domains.
  • protean new: Initialize new projects.
  • protean shell: Interactive shell with the domain pre-loaded.
  • protean server: Run the async background message processing server.
  • protean docs: Live preview server for documentation.
  • protean test: Run Protean's framework test suite (development only).
  • protean ir show: Display the domain's IR as JSON or a human-readable summary.
  • protean schema: Generate and inspect JSON Schema files for data-carrying domain elements.
  • protean snapshot: Create snapshots for event-sourced aggregates.
  • protean projection: Rebuild projections by replaying events from the event store.
  • protean events: Inspect the event store: read streams, view stats, search events, trace aggregate history, and follow causal chains as a tree or flat table.
  • Type Checking: Static type checking with the Protean mypy plugin.
  • Architecture Fitness Functions: Enforce DDD architectural decisions on every commit with protean check.
  • Fitness Function Catalog: Every diagnostic rule, its rationale, and its fix.
  • Init & Runtime Diagnostics: The coded exceptions raised at init and by runtime accessors, each with its rationale and fix.

Test Your Application


Python API Reference

Auto-generated documentation from source code docstrings.


Core Concepts

Architectural theory and the building blocks of domain-driven systems.

Foundations

  • Ubiquitous Language: The shared vocabulary between domain experts and developers.
  • Bounded Contexts: Boundaries within which a domain model is defined and applicable.
  • Analysis Model: Bridging the gap between domain understanding and software implementation.
  • Identity: The property that distinguishes one domain object from all others.
  • Invariants: Business rules that must always hold true within a domain concept.
  • Changing State: Principles governing how state transitions occur in DDD.
  • Streams: The primary unit of organization in evented systems.

Architecture Patterns

Building Blocks

  • Domain Elements Overview: Tactical patterns organized into four layers.
  • Aggregates: Clusters of objects treated as a single unit for data changes.
  • Entities: Mutable objects with distinct identity.
  • Value Objects: Immutable elements distinguished by properties.
  • Domain Services: Domain logic that doesn't fit within aggregates.
  • Events: Immutable facts indicating state changes.
  • Commands: Intentions to change system state.
  • Command Handlers: Process commands and execute domain logic.
  • Event Handlers: React to events with side effects and state synchronization.
  • Application Services: Coordinate use cases at the boundary between external world and domain.
  • Repositories: Collection-oriented persistence abstraction for aggregates.
  • Subscribers: Consume messages from external brokers.
  • Projections: Read-optimized denormalized views.
  • Projectors: Specialized event handlers that maintain projections.
  • Queries: Immutable, validated read intents targeting a projection.
  • Query Handlers: Process queries and return read-side results from projections.
  • Process Managers: Stateful coordinators for multi-step processes across aggregates.

Adapters

Plug-in infrastructure that keeps your domain code free of technology dependencies.

Database

  • Database Providers: Overview of supported database adapters, capabilities, and provider registry.
  • Memory: Default in-memory provider for development and testing.
  • SQLite: File-based relational provider using SQLAlchemy.
  • PostgreSQL: SQLAlchemy-based adapter for PostgreSQL.
  • MSSQL: SQLAlchemy and pyodbc adapter for Microsoft SQL Server.
  • Elasticsearch: Document store adapter for search and analytics.
  • Custom Database Adapters: Build your own database adapter with entry-point registration.

Brokers

  • Broker Overview: Unified interface for message broker implementations.
  • Inline Broker: Synchronous in-memory broker for development and testing.
  • Redis Streams: Durable ordered messaging with consumer groups.
  • Broker Partitioning Contract: The port contract an adapter implements to support sequential_by: partition discovery, fenced ownership leases, and stream trimming.
  • Redis PubSub: Redis Lists-based queuing with consumer groups.
  • Custom Brokers: Build your own broker adapter.

Caches

  • Cache Overview: Cache port interface, available providers, and configuration.
  • Redis Cache: Persistent distributed cache with TTL support.

Event Stores


Patterns & Recipes

In-depth guides for recurring patterns in domain-driven applications. These span multiple domain elements and represent good practices that Protean supports but does not enforce.

Aggregate Design

Event-Driven Patterns

Architecture & Quality

Identity & Communication

Testing & Infrastructure

Operations


Internals

Design reasoning and internal architecture for contributors and advanced users.

  • Internals Overview: What this section covers.
  • Field System: How FieldSpec translates domain vocabulary to Pydantic, and why three definition styles are supported.
  • Shadow Fields: How ValueObject and Reference fields are flattened into database columns via shadow fields.
  • Query System: How the Repository → DAO → QuerySet → Provider chain works, Q object expression trees, lookup resolution, and lazy evaluation.
  • Event Sourcing: How raise_() invokes @apply handlers, aggregate reconstitution, version tracking, causation chain traversal algorithms, and projection rebuilding.
  • Event Upcasting: How old event payloads are transparently transformed to the current schema during deserialization.
  • IR Specification: The portable JSON schema capturing domain model topology.

Migration

  • Compatibility Reference: Breaking change rules, three-tier taxonomy, deprecation lifecycle, and config.toml reference.
  • Migrating to 0.18: Upgrade guide for the 0.18 release. Covers the right-sized dependency surface: the web/observatory stack, the shell, and the scaffolder move behind install extras.
  • Migrating to 0.17: Upgrade guide for the 0.17 API-consolidation release. Covers the event_sourced option rename, the internalized is_fact_event option, and the email subsystem deprecation.
  • Migrating to 0.16: Upgrade guide for the 0.16 stability release. Covers the outbox column-bounds structural change and its per-backend ALTER TABLE recipes.
  • Migrating to 0.15: Upgrade guide for the Pydantic v2 foundation release. Covers breaking changes, field style migration, and new features.

Reference

  • Glossary: Definitions of key terms.
  • Philosophy & Design Principles: The convictions that guide Protean's design.
  • The Always-Valid Domain: How four validation layers guarantee domain objects are never invalid.
  • Applicability Charter: What Protean is a good fit for, and the shapes of systems it is not, with the reason in each case.
  • Consistency & Delivery Guarantees: Per-port, per-adapter ordering, delivery, consistency, and isolation, the contract conformance and property tests cite.
  • Versioning Policy: What a version number promises: code that runs warning-free on 1.N runs unmodified on 1.N+1.
  • Stable Surface: Which imports, options, config keys, and commands the compatibility contract covers, tier by tier.
  • Why Protean?: Four capabilities that set Protean apart: domain compiler, always-valid domain, progressive architecture, infrastructure portability.

Testing


Community

  • Community: Get help and connect with other Protean users.
  • Development Setup: Set up Protean locally for contributing.
  • Testing Protean: Test strategy, fixtures, and running the suite.
  • Mutation Testing: Find under-asserted code paths with make mutation and close them with new tests.
  • Building Adapters: Overview of creating custom adapters for databases, brokers, event stores, and caches with links to per-port guides.