Engine Architecture
The Engine class is the core of Protean's async message processing system. It
manages subscriptions, coordinates message handling, and provides graceful
lifecycle management.
Responsibilities
The Engine is responsible for:
- Registering handler subscriptions: Creating subscriptions for event handlers, command handlers, and projectors
- Managing broker subscriptions: Connecting subscribers for external messages to the configured message broker
- Running outbox processors: Publishing messages from the transactional outbox
- Coordinating lifecycle: Starting, running, and gracefully shutting down all components
- Emitting trace events: Publishing structured
MessageTraceevents at each stage of message processing for real-time observability
Engine Initialization
When you create an Engine instance, it automatically discovers and registers all handlers from your domain:
from protean.server import Engine
def create_engine(domain):
# Create an engine for your domain
return Engine(domain)
def create_test_engine(domain):
# Or with options
return Engine(
domain,
test_mode=True, # Exit once queued messages are processed
debug=False, # Set True for verbose logging
)
Subscription Registration
The Engine associates subscriptions with each handler during initialization. The Engine's subscription factory picks the subscription type from the configuration hierarchy.
Handler Subscriptions
For each event handler and projector, the Engine creates one subscription per handler, inferring the stream category and resolving configuration:
- Infers the stream category from handler metadata or associated aggregate
- Resolves subscription configuration using the priority hierarchy
- Initializes the right Subscription Type, either
a
StreamSubscriptionor anEventStoreSubscription, for the handler.
@domain.aggregate
class Order:
order_id: Identifier(identifier=True)
total: Float(required=True)
@domain.event(part_of=Order)
class OrderPlaced:
order_id: Identifier(required=True)
total: Float(required=True)
placed_orders = []
@domain.event_handler(part_of=Order)
class OrderEventHandler:
@handle(OrderPlaced)
def record(self, event: OrderPlaced) -> None:
placed_orders.append(event.order_id)
def register_order_handler(engine):
# Example: How the engine registers an event handler
handler_cls = OrderEventHandler
stream_category = engine._infer_stream_category(handler_cls) # "shop::order"
subscription = engine.subscription_factory.create_subscription(
handler=handler_cls,
stream_category=stream_category,
)
return stream_category, subscription
Command dispatch
When multiple command handlers belong to the same aggregate (and therefore the
same stream category), the Engine consolidates them into a single subscription
using a CommandDispatcher. Instead of creating N separate subscriptions that
would compete for the same messages, the dispatcher reads each command once and
routes it to the correct handler based on the command type:
@domain.aggregate
class User:
user_id: Identifier(identifier=True)
email: String(required=True)
active: Boolean(default=True)
@domain.command(part_of=User)
class RegisterUser:
user_id: Identifier(identifier=True)
email: String(required=True)
@domain.command(part_of=User)
class DeactivateUser:
user_id: Identifier(identifier=True)
# Two command handlers for the same aggregate
@domain.command_handler(part_of=User)
class RegisterUserHandler:
@handle(RegisterUser)
def register(self, command):
user = User(user_id=command.user_id, email=command.email)
current_domain.repository_for(User).add(user)
@domain.command_handler(part_of=User)
class DeactivateUserHandler:
@handle(DeactivateUser)
def deactivate(self, command):
repo = current_domain.repository_for(User)
user = repo.get(command.user_id)
user.active = False
repo.add(user)
# The engine creates ONE subscription keyed as "commands:{stream_category}"
# that routes RegisterUser → RegisterUserHandler
# and DeactivateUser → DeactivateUserHandler
The CommandDispatcher caches the deserialized domain object between handler
resolution and execution to avoid double deserialization.
Broker Subscriptions
For external message subscribers, the Engine creates BrokerSubscription
instances that connect to the configured message broker:
received = []
@domain.subscriber(broker="default", stream="external_events")
class ExternalEventSubscriber:
def __call__(self, payload: dict) -> None:
received.append(payload)
Outbox Processors
When the outbox is enabled (via default_subscription_type = "stream"), the
Engine creates an OutboxProcessor for each managed database provider holding
an aggregate. Each OutboxProcessor publishes messages to the configured
broker. A provider configured with managed = false gets no processor:
# Configuration in domain.toml
[server]
default_subscription_type = "stream" # Enables outbox
[outbox]
broker = "default"
messages_per_tick = 10
tick_interval = 1
External Outbox Processors
When external_brokers is configured, the Engine creates additional
OutboxProcessor instances, one per external broker per managed database provider
that an aggregate is stored in. Each external processor reads only the outbox
rows tagged with its target broker. It publishes those rows with a stripped
metadata envelope suitable for external consumers:
[outbox]
broker = "default"
external_brokers = ["partner_events"] # Adds external processors
With one database provider, this [outbox] configuration creates
two processors:
outbox-processor-default-to-default: Internal eventsoutbox-processor-default-to-partner_events-external: Published events to external broker
External processors emit outbox.external_published and
outbox.external_failed trace events (distinct from internal
outbox.published / outbox.failed). They skip priority lane routing, since
lanes are an internal concern.
See Dispatching Published Events to External Brokers for the full setup guide.
Configuration Hierarchy
When registering subscriptions, the Engine consults a hierarchy of configuration sources to determine the appropriate subscription type and options for each handler. The resolution process typically follows this order of precedence:
- Handler-level configuration: Explicit parameters set on the handler, such as stream name, broker, or processing options.
- Domain element metadata: Values inferred from associated aggregate, event, or command definitions.
- Profile or role defaults: Settings derived from the active configuration profile (e.g., "production", "projection") or handler role (such as projector vs. handler).
- Domain/global configuration: Defaults specified in the domain configuration files (
domain.tomlor equivalent).
This means that explicit intent at the handler level takes priority, but system-wide defaults provide sensible behavior when specifics are not set.
For example, if a handler specifies a custom stream name, the Engine uses it. Otherwise, the Engine infers the stream category from the handler’s associated aggregate, or falls back to profile or domain defaults.
Tracing
The Engine initializes a TraceEmitter at startup. The TraceEmitter
publishes structured MessageTrace events as messages move through the
pipeline. Trace events are emitted at three points during handle_message:
handler.started: Before the handler processes the messagehandler.completed: After successful processing (includesduration_ms)handler.failed: When the handler raises an exception (includeserror)
Additional trace events are emitted by StreamSubscription (message.acked,
message.nacked, message.dlq) and OutboxProcessor (outbox.published,
outbox.failed).
Dual-channel output
The TraceEmitter writes to two Redis channels:
- Pub/Sub (
protean:trace), Real-time fan-out for SSE clients. The emitter checks subscriber count and skips when nobody is listening. - Stream (
protean:traces), Time-bounded history for the Observatory dashboard and REST API. Old entries are automatically trimmed based on the configured retention period.
Trace retention
The Engine reads trace_retention_days from the domain's [observatory]
configuration (default: 7 days). When set to 0, Stream persistence is
disabled and only Pub/Sub broadcasting is available. The value goes through
Python's int(): 3.9 becomes 3 days, and a negative number also disables
persistence. If [observatory] is missing or not a table, or int() cannot
convert the value (such as "abc" or inf), the Engine falls back to the
7-day default.
The emitter adds no overhead when no monitoring tools are subscribed and persistence is disabled. For the full design, the Observatory monitoring server, and trace API endpoints, see Observability.
Context Propagation
When the Engine processes a message, it restores the cross-cutting context that was present when the message was originally created. This is critical for multi-tenant applications, user-scoped auditing, and any scenario where async handlers need ambient context from the original request.
How it works
- During the original request, enrichers
inject values from
g(e.g.,g.tenant_id,g.user_id) into the message'smetadata.extensions. - The message is persisted to the event store with its extensions intact.
- When the Engine picks up the message for async processing, it reads
metadata.extensionsand passes them as keyword arguments todomain_context():
# fragment
# Simplified from engine.py: what the Engine does for each message
extensions = message.metadata.extensions or {}
with self.domain.domain_context(**extensions):
g.message_in_context = message
# Handler runs here — g.tenant_id, g.user_id, etc. are available
This means any key injected by an enricher is automatically available as an
attribute on g inside the handler. No manual extraction is needed.
g.message_in_context
In addition to restoring enricher-injected values, the Engine sets
g.message_in_context to the current message being processed. Handlers can
use this to access the full message metadata:
@domain.event_enricher
def add_tenant(event, aggregate):
return {"tenant_id": g.get("tenant_id")}
seen_tenants = []
@domain.event_handler(part_of=Order)
class TenantAuditHandler:
@handle(OrderPlaced)
def audit(self, event: OrderPlaced) -> None:
# Access the full extensions dict
tenant_id = g.message_in_context.metadata.extensions.get("tenant_id")
# Or use the restored g attribute directly (simpler)
seen_tenants.append((tenant_id, g.tenant_id))
After the handler completes (or fails), the domain context is torn down and g
is cleaned up. Extensions do not leak between messages.
For a complete worked example of context propagation in a multi-tenant application, see Multi-Tenancy in Event-Driven Systems.
Shutdown sequence
The Engine owns the lifecycle of every infrastructure adapter it
opens. When it receives SIGINT, SIGTERM, or SIGHUP, it runs a deliberate
four-step sequence that preserves three invariants:
- Load balancers pull the pod out of rotation first: Readiness
probes flip to
503before handlers stop, so new traffic stops arriving before in-flight work is disturbed. - In-flight handlers finish or are bounded: Each handler gets up to 10 seconds to complete, after which stragglers are cancelled. This bounds shutdown time without sacrificing successful commits that are already underway.
- Resources close in reverse-initialisation order: Dependents close before their dependencies, so a handler mid-commit never finds its repository's connection pool already closed.
This sequence gives two guarantees:
/readyzfails before any handler is disturbed: The health server stops in step 3; subscriptions stop in step 4; in-flight handlers drain in step 5. A load balancer polling/readyzevery 5 seconds pulls the pod out of rotation within those 5 seconds. Requests already in flight complete on the old pod.Domain.close()is safe to call from application code: Tests and tooling that create domains on demand can invokedomain.close()directly. Each adapter'sclose()is wrapped intry/exceptinside the Domain so a misbehaving adapter cannot prevent the rest from closing. Custom adapters inherit a no-opclose(); override it when the adapter holds sockets, file handles, or background threads.
For the terminationGracePeriodSeconds you need in Kubernetes and for the full
shutdown reference, see Server Hardening
reference and Harden
the Server.
These pages also explain what Domain.close() does per adapter, when SIGHUP
vs SIGTERM matter, and how to disable the health server. The design rationale
(why subscriptions stop first, why 10 seconds, why per-adapter error isolation)
is captured in
ADR-0011.
Running the Engine
For comprehensive information on how to start, configure, and operate the engine, including:
- CLI commands and options
- Test mode for deterministic testing
- Debug mode for troubleshooting
- Programmatic usage
- Production deployment strategies
- Signal handling and graceful shutdown
- Monitoring, health checks, and observability
See the Running the Server guide.
Where to go next
- Subscriptions: Learn how handlers connect to message sources and react to events.
- Subscription Types: Compare StreamSubscription and EventStoreSubscription, and choose the right one for your workload.
- Configuration: Look up the settings for engine profiles, subscriptions, and runtime options.
- Outbox Pattern: Understand reliable message publishing and transactional outbox processing.
- Observability: Real-time tracing, the Observatory server, SSE streaming, and Prometheus metrics.
- Running the Server: Explore how to deploy, operate, and monitor the server in different environments.