Skip to content

How Do I...?

A task-oriented index into the Protean documentation. Find the guide you need by what you're trying to accomplish.

Get Started

I want to... Guide
See Protean working in under 20 lines Hello, Protean!
Build a full domain in 5 minutes Quickstart
Follow a guided tutorial from scratch Tutorial

Model My Domain

I want to... Guide
Define a root entity with business logic Aggregates
Add a child object with identity to an aggregate Entities
Create an immutable descriptive value (Money, Email, Address) Value Objects
Create a copy of a value object with some fields changed Replacing Fields
Auto-generate a value object from an entity's fields Projecting Entities into Value Objects
Convert a value object back into an entity instance Constructing from Value Objects
Choose between an entity and a value object Choosing Element Types
Connect entities with relationships Relationships
Add typed attributes to domain objects Fields
Choose between field definition styles Defining Fields
Define a domain event Events
Understand field arguments and options Arguments
Use simple scalar fields (String, Integer...) Simple Fields
Use container fields (List, Dict, Nested) Container Fields
Use association fields (HasOne, HasMany, Reference) Association Fields

Add Business Rules

I want to... Guide
Understand how Protean keeps domain objects always valid The Always-Valid Domain
Validate field values Validations
Enforce business invariants Invariants
Change aggregate state safely Aggregate Mutation
Enforce allowed state transitions on a field Status Transitions
Raise domain events from an aggregate Raising Events
Trace the full causal chain of commands and events Message Tracing
Inject tenant, user, or request context into every event and command Message Enrichment
Implement multi-tenancy in an event-driven system Multi-Tenancy
Isolate data by tenant with row-level filtering Multi-Tenancy
Coordinate logic across multiple aggregates Domain Services
Handle domain exceptions in endpoints and handlers Error Handling
Model an aggregate's lifecycle as a state machine Aggregate State Machines

Handle Requests and Change State

I want to... Guide Pathway
Handle a user request synchronously Application Services DDD
Define a command representing user intent Commands CQRS, ES
Process a command and update an aggregate Command Handlers CQRS, ES
Choose between an application service and a command handler Application Service vs Command Handler All
Save an aggregate to the database Persist Aggregates All
Load an aggregate by ID or query Retrieve Aggregates All
Load an aggregate at a specific version or time Temporal Queries ES
Expose historical state for audit or compliance Temporal Queries Pattern ES
Define a custom repository with domain queries Repositories All
Query aggregates with complex filters Retrieve Aggregates All
Paginate query results Retrieve Aggregates All
Use Q objects for AND/OR/NOT queries Retrieve Aggregates All
Perform bulk updates or deletes Retrieve Aggregates All
Manage transactions Unit of Work All
Override the database schema for an aggregate Custom Database Models All
Configure an event store for event sourcing Event Store Setup ES
Optimize aggregate loading with snapshots Snapshots ES
Handle version conflicts (optimistic concurrency) Optimistic Concurrency as a Design Tool All
Prevent race conditions in concurrent event handlers Designing for Concurrent Event Processing All
Configure or disable version conflict auto-retry Error Handling All

React to State Changes

I want to... Guide
Run side effects when an event fires Event Handlers
Coordinate a multi-step process across aggregates Process Managers
Correlate events to a running process Process Managers
Design a PM for production (idempotency, compensation, timeouts) Coordinating Long-Running Processes
Build a read-optimized view from events Projections
Decide how many projections to create and what each should contain Projection Granularity
Handle the delay between writing and reading in CQRS Eventual Consistency in UIs
Define an event handler that maintains a projection Projectors
Process a query and return results Query Handlers
Dispatch a named read intent Query Handlers
Treat projection rebuilds as a deployment operation Projection Rebuilds as Deployment
Rebuild a projection from historical events protean projection rebuild
Listen to messages from an external broker Subscribers
Use fact events for cross-context integration Fact Events as Integration Contracts
Publish events to external brokers for other bounded contexts External Event Dispatch
Follow the causal chain of a business operation Message Tracing
Traverse causation chains programmatically Message Tracing
Serialize events to CloudEvents v1.0 for external systems CloudEvents Interoperability
Consume CloudEvents from external systems CloudEvents Interoperability

Set Up and Configure

I want to... Guide
Register domain elements Register Elements
Initialize and activate a domain Initialize Domain
Configure for production with environment overlays Configure for Production
Configure databases, brokers, and caches Configuration
Understand identity and ID generation Identity
Understand stream categories Stream Categories
Activate a domain for use Activate Domain
Understand element decorators Element Decorators
Decide when to compose vs. initialize When to Compose
Understand the object model and Meta options Object Model

Integrate with FastAPI

I want to... Guide
Push domain context per HTTP request FastAPI Integration
Map URL prefixes to different domains FastAPI Integration
Map Protean exceptions to HTTP error responses FastAPI Integration
Use a custom resolver for domain routing FastAPI Integration

Run in Production

I want to... Guide
Process events and commands asynchronously Server
Understand subscriptions and event processing Subscriptions
Use the outbox pattern for reliable messaging Outbox
Dispatch published events to external brokers External Event Dispatch
Understand how correlation IDs propagate end-to-end Correlation and Causation IDs
Inject correlation IDs into logs automatically Correlation and Causation IDs
Pass a correlation ID from an API gateway Correlation and Causation IDs
Preserve correlation chains across services Correlation and Causation IDs
Set up structured logging Running the Server
Add request-scoped context to logs Running the Server
Minimize logging noise in tests Running the Server
Monitor message flow in real time Observability
Expose Prometheus metrics for the message pipeline Observability
Stream trace events via SSE Observability
Add distributed tracing with OpenTelemetry OpenTelemetry Integration
Send spans and metrics to Jaeger, Datadog, or Grafana OpenTelemetry Integration
Instrument FastAPI endpoints with OTel OpenTelemetry Integration
Run the async background server protean server
Use the CLI for development and operations CLI
Understand the server engine architecture Engine
Learn about subscription types Subscription Types
Configure subscriptions Server Configuration
Run multiple workers with the supervisor Supervisor
Use priority lanes for event processing Priority Lanes
Use priority lanes for background workloads Using Priority Lanes
Run a bulk migration with priority lanes Running Data Migrations with Priority Lanes
Classify and handle errors in async handlers Classify Async Processing Errors
Handle message processing failures Error Handling
Inspect and replay dead letter queue messages Error Handling
Configure retry and DLQ settings Error Handling

Check Compatibility

I want to... Guide
Detect breaking changes in my domain model Compatibility Checking
Configure compatibility check strictness Compatibility Checking
Set up pre-commit hooks for IR checks Compatibility Checking
Auto-fix stale IR during commit Compatibility Checking
Check multiple domains with one hook entry Compatibility Checking
Add IR compatibility checks to CI Compatibility Checking

Use the CLI

I want to... Guide
Scaffold a new Protean project protean new
Understand domain and element discovery protean discovery
Open an interactive shell protean shell
Run the async background server protean server
Run the observability dashboard protean observatory
Manage database schemas protean db
Create and manage snapshots protean snapshot
Rebuild projections from events protean projection
Inspect events in the event store protean events
Generate JSON Schemas for domain elements Schema Generation
View the event history of an aggregate protean events history
Follow a causal chain by correlation ID protean events trace

Evolve and Maintain

I want to... Guide
Transform old event schemas during replay Event Upcasting
Add type checking to my domain code Type Checking

Organize My Project

I want to... Guide
Structure my project folders by domain concept Organize by Domain Concept
Scaffold a new project with the right structure protean new

Choose an Architecture

I want to... Guide
Understand the three architectural pathways Choose a Path
Use pure DDD with application services DDD Pathway
Separate reads and writes with CQRS CQRS Pathway
Use event sourcing for full audit trails Event Sourcing Pathway
Decide between CQRS and Event Sourcing Architecture Decision

Test My Code

I want to... Guide
Test domain model logic Domain Model Tests
Test application workflows (BDD-style) Application Tests
Test event-sourced aggregates with a fluent DSL Event Sourcing Tests
Test with real databases and brokers Integration Tests
Set up test fixtures and patterns Fixtures and Patterns
Set up databases for integration tests Database Setup/Teardown
Test a full event-driven flow end-to-end Test Event-Driven Flows

Use Specific Technologies

I want to... Guide
Use PostgreSQL PostgreSQL Adapter
Use Elasticsearch Elasticsearch Adapter
Use Redis as a message broker Redis Broker
Use the in-memory database Memory Adapter
Use SQLite SQLite Adapter
Use Redis as a cache Redis Cache
Use Message DB as an event store Message DB
Build a custom database adapter Custom Databases
Build a custom broker adapter Custom Brokers
Check what capabilities a database supports Database Capabilities
Test a custom adapter for conformance Conformance Testing

Look Up API Details

I want to... Guide
Look up the exact signature of a base class Python API Reference
Browse Domain class methods and options Domain API
See all field types and their parameters Fields API

Understand Internals

I want to... Guide
Generate the IR for my domain Inspecting the IR
Understand the IR format and compatibility IR Specification
Understand how the field system works Field System
Learn why three field definition styles exist Field System
Understand how the query system works internally Query System
Understand causation chain traversal internals Event Sourcing Internals