protean projection
The protean projection command group manages projections, read-optimized views built from
domain events. It provides a rebuild command that reconstructs projections by
replaying events from the event store, and a status command that reports how far
behind each projection is.
Projection rebuilding is essential when:
- Fixing a projector bug: A bug caused incorrect data in a projection; rebuild replays all events through the corrected projector.
- Adding a new projection: A new projection is added to an existing system and needs to be populated from historical events.
- Schema changes: The projection's schema changed (new fields, renamed columns) and data must be regenerated.
- Data corruption recovery: Projection data was corrupted or accidentally deleted.
All commands accept a --domain option to specify the domain module path
(defaults to the current directory).
Warning
Stop the Protean server before rebuilding projections. Concurrent event processing during a rebuild can cause data inconsistencies because the rebuild truncates projection data before replaying events.
Commands
| Command | Description |
|---|---|
protean projection rebuild |
Rebuild projections by replaying events |
protean projection status |
Report per-projection staleness, lag, and row count |
protean projection rebuild
Rebuilds projections by truncating existing data and replaying all events from the event store through the associated projectors. Upcasters are applied automatically during replay.
Rebuild a specific projection
protean projection rebuild --domain=my_domain --projection=Balances
Rebuilds a single projection by name. The command:
- Finds all projectors that target the named projection
- Truncates existing projection data (database rows or cache entries)
- Reads all events from each projector's stream categories
- Replays events in global order through the projector handlers
Rebuild all projections
protean projection rebuild --domain=my_domain
Without --projection, rebuilds every projection registered in the domain.
Each projection is rebuilt independently.
Options
| Option | Description | Default |
|---|---|---|
--domain |
Domain module path | . (current directory) |
--projection |
Projection class name (e.g. Balances) |
All projections |
--batch-size |
Number of events to read per batch | 500 |
Output
# Single projection:
Rebuilt projection 'Balances': 42 events processed through 1 projector(s) across 2 category/categories.
# Single projection with skipped events:
Rebuilt projection 'Balances': 40 events processed through 1 projector(s) across 2 category/categories.
(2 events skipped)
# All projections:
Balances: 42 events processed
UserDirectory: 18 events processed
Rebuilt 2 projection(s), 60 total events processed.
The rebuild marks an event as "skipped" when it cannot resolve the event to a domain object. Such an event is typically of a deprecated type that was removed from the codebase without an upcaster chain. Skipped events are logged as warnings but do not cause the rebuild to fail.
Error handling
| Condition | Behavior |
|---|---|
| Invalid domain path | Aborts with "Error loading Protean domain" |
| Projection not found in registry | Aborts with "Projection 'X' not found" |
| No projectors for projection | Aborts with error message |
| No projections in domain | Prints "No projections found in domain." |
| Unresolvable event type | Logs warning, skips event, continues |
protean projection status
Reports how far behind each projection is and how large it is, from the last processed position of each projector that feeds it. Useful for spotting read models that have stalled. Does not require the server to be running.
protean projection status --domain=my_domain
For each projection the report shows:
- Staleness: Seconds since the projection last advanced.
0when caught up, blank when the projector has never run or its position is unknown. - Lag: Events behind the stream head, taken from the worst (most behind) of its feeding projectors.
- Last updated: When the projection last advanced.
- Rows: Number of records currently in the projection store.
- Status:
ok(caught up),lagging(behind), orunknown.
A projection fed by several projectors reports the worst staleness and lag across all of them.
Note
Time-based staleness comes from each projector's position-write timestamp, so it is reported for event-store-backed projectors. Stream-backed (Redis) projectors show lag and status, but their staleness is blank.
JSON output
protean projection status --domain=my_domain --json
The output is the shared result envelope, with the
per-projection list under data.projections. Each entry carries
projection_name, projectors, last_updated, staleness_seconds, lag,
row_count, and status:
{
"version": "0.1.0",
"status": "pass",
"data": {
"projections": [
{
"projection_name": "Balances",
"projectors": ["BalancesProjector"],
"last_updated": "2026-06-27T12:00:00+00:00",
"staleness_seconds": 90.0,
"lag": 5,
"row_count": 3,
"status": "lagging"
}
]
},
"diagnostics": []
}
stdout carries exactly this one object; logs go to stderr, so a | jq pipe
stays parseable.
Options
| Option | Description | Default |
|---|---|---|
--domain |
Domain module path | . (current directory) |
--json |
Output raw JSON instead of a table | false |
For continuous monitoring, scrape the protean_projection_staleness_seconds
metric instead; see Server Observability.
Domain discovery
The protean projection commands use the same domain discovery mechanism as
protean server. The --domain option accepts:
- A Python module path:
my_package.domain - A file path:
src/my_domain.py - A module with instance name:
my_domain:custom_domain .(default): Searches the current directory
See Domain Discovery for the full resolution logic.
Programmatic API
The same functionality is available as Domain methods for use in scripts or
the protean shell:
The domain this example uses
from protean import Domain, current_domain
from protean.core.projector import on
from protean.fields import Float, Identifier, String
domain = Domain(name="Banking")
@domain.event(part_of="Account")
class AccountOpened:
account_id: Identifier(required=True)
holder: String(required=True)
@domain.event(part_of="Account")
class MoneyDeposited:
account_id: Identifier(required=True)
amount: Float(required=True)
@domain.aggregate
class Account:
account_id: Identifier(identifier=True)
holder: String(required=True)
@classmethod
def open(cls, account_id: str, holder: str) -> "Account":
account = cls(account_id=account_id, holder=holder)
account.raise_(AccountOpened(account_id=account_id, holder=holder))
return account
def deposit(self, amount: float) -> None:
self.raise_(MoneyDeposited(account_id=self.account_id, amount=amount))
@domain.projection
class Balances:
account_id: Identifier(identifier=True)
holder: String()
balance: Float(default=0.0)
@domain.projector(projector_for=Balances, aggregates=[Account])
class BalancesProjector:
@on(AccountOpened)
def opened(self, event: AccountOpened) -> None:
current_domain.repository_for(Balances).add(
Balances(account_id=event.account_id, holder=event.holder)
)
@on(MoneyDeposited)
def deposited(self, event: MoneyDeposited) -> None:
repo = current_domain.repository_for(Balances)
balances = repo.get(event.account_id)
balances.balance += event.amount
repo.add(balances)
domain.init(traverse=False)
with domain.domain_context():
alice = Account.open("acc-1", holder="Alice")
alice.deposit(100.0)
alice.deposit(50.0)
domain.repository_for(Account).add(alice)
domain.repository_for(Account).add(Account.open("acc-2", holder="Bob"))
from protean.utils.projection_rebuilder import RebuildResult
with domain.domain_context():
# Rebuild a single projection
result = domain.rebuild_projection(Balances)
assert result.success
print(f"{result.events_dispatched} events replayed")
# Rebuild a single projection with custom batch size
batched = domain.rebuild_projection(Balances, batch_size=1000)
assert batched.success
# Rebuild all projections
results: dict[str, RebuildResult] = domain.rebuild_all_projections()
for name, result in results.items():
print(f"{name}: {result.events_dispatched} events")
domain.rebuild_projection(projection_cls, batch_size=500)
Rebuild a single projection. Returns a RebuildResult:
| Field | Type | Description |
|---|---|---|
projection_name |
str |
Name of the projection class |
projectors_processed |
int |
Number of projectors that were run |
categories_processed |
int |
Total stream categories read across all projectors |
events_dispatched |
int |
Events successfully processed |
events_skipped |
int |
Events that could not be resolved or failed |
errors |
list[str] |
Error messages (empty on success) |
success |
bool |
True when errors is empty |
domain.rebuild_all_projections(batch_size=500)
Rebuild every projection in the domain. Returns a
dict[str, RebuildResult] mapping projection class names to their results.
How it works
The rebuild process has three phases:
1. Discover projectors
The domain registry is queried for all projectors that target the given
projection (via domain.projectors_for(projection_cls)). If no projectors
are found, the rebuild fails immediately with an error.
2. Truncate projection data
Existing projection data is cleared:
- Database-backed projections (the default): All rows are deleted via
the DAO's
delete_all()method. When a projector of the projection is registered withidempotent=True, its delivery markers are deleted in the same unit of work as the rows. Without this, the replay would find a marker for every event, skip it as a redelivery, and leave the projection empty. The replay writes fresh markers. On a relational or in-memory provider, a failed marker delete rolls back the row delete. Elasticsearch has no transactions, so there a failed marker delete leaves the rows deleted and the markers in place. - Cache-backed projections: The entries matching the pattern
cache.pattern_for(projection)returns, such asorder_summary:::*, are removed viaremove_by_key_pattern(). This needs a cache that supportsCacheCapabilities.PATTERN_MATCH. On a cache without it, the rebuild raisesNotSupportedErrorbefore it replays any event. Without--projection, the command first checks the cache of every cache-backed projection that has a projector, and raises before it truncates any projection.
3. Replay events
For each projector, events are read from all of its stream categories and
merged in global position order. The merge keeps the cross-aggregate order
correct. For example, if a Registered event from the user category was
stored before a Transacted event from the transaction category, the
projector always processes the Registered event first.
Each event is dispatched through the projector's _handle() method, which:
- Converts the stored
Messageto a domain event object (applying upcasters automatically) - Looks up the
@onhandler for the event type - Executes the handler within a
UnitOfWork. For an idempotent projector on a database-backed projection, it writes a new delivery marker in the sameUnitOfWork. A cache-backed projection has no marker store, so no marker is written for it. - Events with no matching
@onhandler are silently skipped (no error)
If an event type cannot be resolved (deprecated event without an upcaster
chain), a ConfigurationError is caught, a warning is logged, and the event is
skipped. Other exceptions during handler execution are also caught, logged, and
skipped. The rebuild continues with the remaining events.
The rebuild is idempotent: running it again truncates and replays from scratch. No checkpointing or partial state is maintained.