Temporal Queries
ES
Event sourcing preserves the complete history of every aggregate as a sequence of domain events. Temporal queries let you reconstitute an aggregate at any historical point without any extra infrastructure. They answer questions such as "what was the state of this order yesterday?" or "what did the account look like at version 5?"
The examples on this page use this event-sourced Order. The order
order-123 has seven events, and cutoff is a moment between the fourth and
the fifth:
from datetime import UTC, datetime
from protean import Domain, UnitOfWork, apply
from protean.fields import Identifier, Integer, String
domain = Domain(name="Shop")
@domain.event(part_of="Order")
class OrderPlaced:
order_id: Identifier(required=True)
customer: String(required=True)
@domain.event(part_of="Order")
class ItemAdded:
order_id: Identifier(required=True)
product: String(required=True)
quantity: Integer(required=True)
@domain.aggregate(event_sourced=True)
class Order:
order_id: Identifier(identifier=True)
customer: String(required=True)
item_count: Integer(default=0)
@classmethod
def place(cls, order_id: str, customer: str) -> "Order":
order = cls(order_id=order_id, customer=customer)
order.raise_(OrderPlaced(order_id=order_id, customer=customer))
return order
def add_item(self, product: str, quantity: int) -> None:
self.raise_(
ItemAdded(order_id=self.order_id, product=product, quantity=quantity)
)
@apply
def placed(self, event: OrderPlaced) -> None:
self.order_id = event.order_id
self.customer = event.customer
self.item_count = 0
@apply
def item_added(self, event: ItemAdded) -> None:
self.item_count += event.quantity
domain.init(traverse=False)
with domain.domain_context():
repo = domain.repository_for(Order)
# Versions 0 to 3: the order is placed and three items are added
order = Order.place("order-123", customer="Alice")
for product in ("pen", "ink", "paper"):
order.add_item(product, quantity=1)
repo.add(order)
cutoff = datetime.now(UTC)
# Versions 4 to 6: three more items, written after `cutoff`
order = repo.get("order-123")
for product in ("stapler", "tape", "glue"):
order.add_item(product, quantity=2)
repo.add(order)
By version
Pass at_version to get() to reconstitute an aggregate at a specific event
version. Versions are 0-indexed: version 0 is the state after the first event,
version 1 after the second, and so on.
with domain.domain_context():
repo = domain.repository_for(Order)
# State after the 6th event (version 5)
order_v5 = repo.get("order-123", at_version=5)
assert order_v5._version == 5
Use at_version to compare state before and after a particular event, or to
debug unexpected state transitions.
By timestamp
Pass as_of to get() to reconstitute an aggregate as it existed at a
particular moment in time. Only events written on or before the given
datetime are replayed.
with domain.domain_context():
repo = domain.repository_for(Order)
# The order as it stood at `cutoff`, before the last three items.
# `cutoff` can be any datetime, for example
# datetime(2026, 2, 20, 12, 0, 0, tzinfo=UTC) for noon on February 20.
order_then = repo.get("order-123", as_of=cutoff)
Note
The as_of parameter uses the event's write timestamp. The moment the
event was persisted to the event store, not any business-level timestamp
embedded in the event payload.
Read-only aggregates
Temporal aggregates are read-only. Calling raise_() on them raises
IncorrectUsageError:
# fragment
order_v5 = repo.get("order-123", at_version=5)
order_v5.raise_(SomeEvent(...)) # Raises IncorrectUsageError
You can check whether an aggregate was loaded temporally via the
_is_temporal attribute:
assert order_v5._is_temporal is True
The read-only guard on temporal aggregates prevents accidental writes to
historical state. If you need to modify an aggregate, load it at its current
version with a plain get().
Mutual exclusivity
at_version and as_of cannot be used together. Passing both raises
IncorrectUsageError:
# fragment
# This raises IncorrectUsageError
repo.get("order-123", at_version=5, as_of=cutoff)
Interaction with snapshots
Protean's snapshot mechanism optimizes aggregate loading by caching state at periodic intervals (see Event Sourcing Internals).
Temporal queries use a snapshot only when it gives the correct historical state:
at_versionuses existing snapshots when the snapshot version is at or before the requested version. If the snapshot is newer than the requested version, it is skipped and events are replayed from the beginning.as_ofalways skips snapshots and replays from the first event, because a snapshot's creation time does not correspond to any particular aggregate state timestamp.
Identity map bypass
Temporal queries always bypass the Unit of Work's identity map. The identity map holds the aggregate when the current transaction loaded or saved it earlier. A temporal query still replays events from the event store, so the historical state is accurate:
with domain.domain_context():
repo = domain.repository_for(Order)
with UnitOfWork():
current = repo.get("order-123")
current.add_item("pencil", quantity=1) # Mutated in memory
repo.add(current) # Tracked in the identity map until commit
assert repo.get("order-123") is current # Served from the identity map
historical = repo.get("order-123", at_version=0) # Fresh from events
assert historical._version == 0 # Not affected by in-memory mutation
Error handling
| Scenario | Exception |
|---|---|
| Aggregate does not exist | ObjectNotFoundError |
at_version higher than latest version |
ObjectNotFoundError (message includes the latest available version) |
as_of before the first event |
ObjectNotFoundError |
Both at_version and as_of provided |
IncorrectUsageError |
raise_() on a temporal aggregate |
IncorrectUsageError |
To get None instead of ObjectNotFoundError, call
get_or_none()
with the same arguments.
See also
Related guides:
- Event Upcasting: Transform historical event schemas during replay.
- Retrieve Aggregates: Standard aggregate querying with QuerySets.