Calling External Systems from Handlers
The Problem
A handler reacts to OrderPlaced by confirming the order and posting to a
partner's webhook. The code reads naturally:
# fragment
@handle(OrderPlaced)
def confirm_and_notify(self, event):
repo = current_domain.repository_for(Order)
order = repo.get(event.order_id) # transaction opens here
order.confirm()
repo.add(order)
httpx.post(PARTNER_URL, json={"order_id": event.order_id}) # holds locks
The @handle decorator wraps every handler method in a Unit of Work, and since
ADR-0027 that Unit of Work
is one real database transaction. The transaction opens at the first repository
access and stays open until the method returns. So the httpx.post runs inside
the transaction. While the call waits on the partner, it holds the row locks
and the pooled connection acquired by repo.get and repo.add.
Two things go wrong from there. A slow partner holds locks for the length of the call, and under load the connection pool drains while every handler waits on the network. And version-conflict (OCC) retry re-runs the whole method body, so a retry re-posts to the partner. The webhook fires twice for one order.
The Pattern
A handler method either persists or talks to the outside world, and never does both.
Split the work into two methods:
- A persisting method loads the aggregate, mutates it, persists it, and raises an event. It makes no external call.
- A calling method makes the external call and reaches no repository. With no repository access it runs no transaction and holds no connection, so the call costs only wall-clock time.
The examples below use this Order aggregate and a post_to_partner function
that sends one payload to the partner's webhook:
from datetime import UTC, datetime
import httpx
from protean import Domain, current_domain, handle
from protean.fields import DateTime, Identifier, String
domain = Domain(name="Orders")
PARTNER_URL = "https://partner.example.com/webhooks/orders"
def post_to_partner(payload: dict) -> None:
httpx.post(PARTNER_URL, json=payload).raise_for_status()
@domain.event(part_of="Order")
class OrderPlaced:
order_id: Identifier(required=True)
@domain.event(part_of="Order")
class OrderConfirmed:
order_id: Identifier(required=True)
confirmed_at: DateTime(required=True)
@domain.aggregate
class Order:
order_id: Identifier(identifier=True)
status: String(default="PLACED")
fulfilment_status: String(default="PENDING")
confirmed_at: DateTime()
@classmethod
def place(cls, order_id):
order = cls(order_id=order_id)
order.raise_(OrderPlaced(order_id=order_id))
return order
def start_fulfilment(self):
self.fulfilment_status = "STARTED"
def confirm(self):
self.status = "CONFIRMED"
self.confirmed_at = datetime.now(UTC)
self.raise_(
OrderConfirmed(order_id=self.order_id, confirmed_at=self.confirmed_at)
)
When the two reactions are independent, they can sit in one handler class as sibling methods and run in any order:
@domain.event_handler(part_of=Order)
class OrderReactions:
@handle(OrderPlaced)
def start_fulfilment(self, event):
repo = current_domain.repository_for(Order)
order = repo.get(event.order_id)
order.start_fulfilment()
repo.add(order)
@handle(OrderPlaced)
def notify_partner(self, event):
# No repository access, so this method runs no transaction.
post_to_partner({"order_id": event.order_id})
When the call has to follow the write, or needs a value the write produces, the persisting method raises an event and the calling method handles that event:
@domain.event_handler(part_of=Order)
class OrderConfirmation:
@handle(OrderPlaced)
def confirm(self, event):
repo = current_domain.repository_for(Order)
order = repo.get(event.order_id)
order.confirm() # raises OrderConfirmed
repo.add(order)
@domain.event_handler(part_of=Order)
class PartnerNotifier:
@handle(OrderConfirmed)
def notify_partner(self, event):
# A datetime is not JSON, so the timestamp goes out as an ISO 8601 string.
post_to_partner(
{
"order_id": event.order_id,
"confirmed_at": event.confirmed_at.isoformat(),
}
)
OrderConfirmed goes to the outbox
inside the confirming transaction and is published once that transaction commits,
so notify_partner runs after the write is durable. The value it needs travels
on the event. confirmed_at is a datetime, which is not JSON, so
notify_partner sends it as an ISO 8601 string.
With sync event processing, notify_partner runs in the caller's thread right
after the confirming commit. If the partner call fails, the caller gets a
TransactionError, and the confirmed order stays saved.
How Protean Supports This
The Unit of Work is lazy. A handler method that reaches no repository runs no transaction and holds no pooled connection, so the "no persistence means no transaction" half of the rule is a guarantee you can rely on. See When the transaction actually opens.
The outbox delivers the value to the calling method. The event the persisting method raises is written to the outbox in that transaction and published after it commits, so the call runs after the write is durable and the outbox retries delivery on its own.
Sibling methods are independent. Several methods on one handler class react to the same event, each in its own Unit of Work and in no guaranteed order, and one that fails does not stop the others. See Event Handlers.
A check flags the shape. protean check reports
HANDLER_PERSISTS_AND_CALLS_OUT
when a method calls out after a repository access, the point at which the
transaction is already open. It is advisory, because a handler that needs the
call's result sometimes has to do both.
Applying the Pattern
Syncing many facets from one external snapshot
The costly shape is a multi-facet sync: one external fetch produces a snapshot,
several facets apply it to the same aggregate, and some facets depend on what an
earlier facet wrote. A billing provider sync is a good example. One Subscriber
aggregate holds contact details, a plan, and the feature flags the plan unlocks,
and all three come from the provider. A ProfileSnapshot holds one fetched
copy of the provider's data. The two aggregates look like this:
FLAGS_FOR_TIER = {
"free": [],
"pro": ["exports"],
"team": ["exports", "sso"],
}
@domain.event(part_of="Subscriber")
class SubscriberSyncRequested:
subscriber_id: Identifier(required=True)
@domain.event(part_of="ProfileSnapshot")
class ProfileSnapshotStored:
snapshot_id: Identifier(required=True)
subscriber_id: Identifier(required=True)
@domain.aggregate
class ProfileSnapshot:
snapshot_id: Auto(identifier=True)
subscriber_id: Identifier(required=True)
email: String(required=True)
name: String(required=True)
tier: String(required=True)
seats: Integer(required=True)
@classmethod
def from_payload(cls, subscriber_id, payload):
return cls(
subscriber_id=subscriber_id,
email=payload["email"],
name=payload["name"],
tier=payload["plan"]["tier"],
seats=payload["plan"]["seats"],
)
def store(self):
self.raise_(
ProfileSnapshotStored(
snapshot_id=self.snapshot_id, subscriber_id=self.subscriber_id
)
)
@domain.aggregate
class Subscriber:
subscriber_id: Identifier(identifier=True)
email: String()
name: String()
tier: String(default="free")
seats: Integer(default=1)
flags: List(content_type=String)
applied_snapshot_ids: List(content_type=String)
def request_sync(self):
self.raise_(SubscriberSyncRequested(subscriber_id=self.subscriber_id))
def update_contact(self, email, name):
self.email = email
self.name = name
def change_plan(self, tier, seats):
self.tier = tier
self.seats = seats
def set_flags_for_tier(self):
self.flags = list(FLAGS_FOR_TIER[self.tier])
def record_snapshot(self, snapshot_id):
self.applied_snapshot_ids = [*self.applied_snapshot_ids, snapshot_id]
Fetch once, persist the snapshot, raise one event. One handler fetches the snapshot from the provider, then persists it. The fetch comes before any repository access, so it runs before the transaction opens.
BILLING_URL = "https://billing.example.com"
@domain.event_handler(part_of=Subscriber)
class ProfileFetch:
@handle(SubscriberSyncRequested)
def fetch_snapshot(self, event):
# The fetch comes before any repository access, so no transaction is open.
payload = httpx.get(f"{BILLING_URL}/subscribers/{event.subscriber_id}").json()
repo = current_domain.repository_for(ProfileSnapshot)
snapshot = ProfileSnapshot.from_payload(event.subscriber_id, payload)
snapshot.store() # raises ProfileSnapshotStored
repo.add(snapshot)
Because the fetch comes before the persist, the call holds no lock.
protean check does not flag the fetch, because the check fires only on a call
made after a repository access. A retry re-runs the fetch, a safe repeat for
a read.
ProfileFetch is part of Subscriber, yet it adds a ProfileSnapshot. It
creates a new record and changes no existing one, so no other writer competes
for it. To change an existing aggregate of another kind, issue a command to it,
as the next step does.
Persisting the snapshot and giving it an identity keeps the payload out of the event. The step that applies the facets then loads the snapshot by id rather than carrying it on the event or fetching it again. A fat event would put the whole payload into the event store forever, and a re-fetch per facet turns one call into several.
Apply every facet in one command. ProfileSnapshotStored belongs to
ProfileSnapshot, so the event handler is part of ProfileSnapshot. The
handler issues one ApplyProfileSnapshot command, which is part of
Subscriber, and Subscriber's command handler applies every facet:
@domain.command(part_of=Subscriber)
class ApplyProfileSnapshot:
subscriber_id: Identifier(identifier=True)
snapshot_id: Identifier(required=True)
@domain.event_handler(part_of=ProfileSnapshot)
class ProfileSnapshotHandler:
@handle(ProfileSnapshotStored)
def apply_to_subscriber(self, event: ProfileSnapshotStored):
current_domain.process(
ApplyProfileSnapshot(
subscriber_id=event.subscriber_id, snapshot_id=event.snapshot_id
)
)
@domain.command_handler(part_of=Subscriber)
class SubscriberCommandHandler:
@handle(ApplyProfileSnapshot)
def apply_snapshot(self, command: ApplyProfileSnapshot):
repo = current_domain.repository_for(Subscriber)
subscriber = repo.get(command.subscriber_id)
if command.snapshot_id in subscriber.applied_snapshot_ids:
return # This snapshot was already applied
snapshot = current_domain.repository_for(ProfileSnapshot).get(
command.snapshot_id
)
subscriber.update_contact(snapshot.email, snapshot.name)
subscriber.change_plan(snapshot.tier, snapshot.seats) # sets the tier
subscriber.set_flags_for_tier() # reads the tier
subscriber.record_snapshot(command.snapshot_id)
repo.add(subscriber)
The facets run in one method, in the order the code gives: contact, then plan,
then flags. The feature flags depend on the plan tier, so
set_flags_for_tier() reads the tier that change_plan() has just set. The
order is ordinary code, which is where an ordering dependency belongs. All three
facets and the snapshot id go into Subscriber in one write.
Events are delivered at least once, so the same ProfileSnapshotStored can
arrive twice. Subscriber records the ids of the snapshots it has applied, and
the command handler returns without changes when it sees one again. The id is
saved in the same write as the facets. A retry after that write commits does
nothing, and a retry after a failed write applies the snapshot again in full.
The command handler expects the Subscriber to exist already. If it does not,
repo.get raises ObjectNotFoundError, and the command fails and is retried
like any other failed message.
subscriber_id is the command's identifier, so every ApplyProfileSnapshot for
one subscriber goes to the same command stream. That choice of stream does not
make the snapshots apply in order. Several workers can handle commands for the
same subscriber at once, and after a version conflict the retried command can
apply an older snapshot over a newer one. If the order matters, store the
provider's sequence number or timestamp on Subscriber and skip a snapshot that
is older than the last one applied.
Recording the result of a call
A notification dispatcher sends a message through a channel, then records
whether the send worked on the Notification. The record step needs the send's
result, so the call has to come first. The aggregate and the command that
records the result look like this:
@domain.event(part_of="Notification")
class NotificationDispatchStarted:
notification_id: Identifier(required=True)
recipient: String(required=True)
body: String(required=True)
@domain.command(part_of="Notification")
class RecordDispatchResult:
notification_id: Identifier(identifier=True)
status: String(required=True)
@domain.aggregate
class Notification:
notification_id: Identifier(identifier=True)
recipient: String(required=True)
body: String(required=True)
status: String(default="PENDING")
def start_dispatch(self):
self.status = "DISPATCHING"
self.raise_(
NotificationDispatchStarted(
notification_id=self.notification_id,
recipient=self.recipient,
body=self.body,
)
)
def record_result(self, status):
self.status = status
@domain.command_handler(part_of=Notification)
class NotificationCommandHandler:
@handle(RecordDispatchResult)
def record_result(self, command):
repo = current_domain.repository_for(Notification)
notification = repo.get(command.notification_id)
notification.record_result(command.status)
repo.add(notification)
The sending method makes the call and reaches no repository. It hands the write
to the RecordDispatchResult command with asynchronous=True:
@domain.event_handler(part_of=Notification)
class NotificationDispatcher:
@handle(NotificationDispatchStarted)
def send(self, event):
# The channel call reaches no repository.
outcome = channel.send(event.recipient, event.body)
current_domain.process(
RecordDispatchResult(
notification_id=event.notification_id,
status="SENT" if outcome.ok else "FAILED",
),
asynchronous=True,
)
The domain uses sync command processing. The @handle decorator opens a Unit
of Work around send, so domain.process stores the command with that Unit of
Work and returns None. The command runs after the Unit of Work commits, in its
own Unit of Work with its own version retry. After a version conflict on the
Notification, Protean retries only the record step, so the channel
sends once.
When the record step fails for good, the commit raises TransactionError with
the failure as its cause, or with an ExceptionGroup as its cause when more
than one command or event handler failed. It never raises a version conflict,
so the caller's own version retry does not send again. The same deferral
applies inside a @use_case method, a with UnitOfWork(): block and an
explicit UnitOfWork.start(). Outside any Unit of Work,
domain.process(command, asynchronous=True) handles the command at once and
returns its result. See ADR-0031
for the reasons.
A process that stops after the commit and before the command runs leaves the
command stored and not handled, the same risk that events handled in sync mode
carry. And if your domain lists TransactionError among the exceptions it
retries as transient, that retry runs the whole method again and sends a second
message. Leave TransactionError off that list.
Under event_processing = "async", the TransactionError from a failed record
step also reaches the engine. The engine delivers the NotificationDispatchStarted
event again, up to its retry limit, and each delivery sends another message.
Pass the channel an idempotency key, such as the notification's id, so the
channel drops the repeats.
When the two genuinely cannot be split
Sometimes the write needs the call's result, so the two cannot go in separate methods. An address validation service returns a normalized address, and the aggregate stores what the service returned:
VALIDATOR_URL = "https://address-validator.example.com/normalize"
@domain.event(part_of="Customer")
class AddressSubmitted:
customer_id: Identifier(required=True)
raw_address: String(required=True)
@domain.aggregate
class Customer:
customer_id: Identifier(identifier=True)
address: String()
def submit_address(self, raw_address):
self.raise_(
AddressSubmitted(customer_id=self.customer_id, raw_address=raw_address)
)
def set_address(self, normalized):
self.address = normalized
@domain.event_handler(part_of=Customer)
class CustomerAddressHandler:
@handle(AddressSubmitted)
def normalize_and_store(self, event):
# The call comes first, so the transaction opens at repo.get, after it returns.
result = httpx.post(VALIDATOR_URL, json={"address": event.raw_address}).json()
repo = current_domain.repository_for(Customer)
customer = repo.get(event.customer_id)
customer.set_address(result["normalized"])
repo.add(customer)
Call first, then persist. Because the Unit of Work is lazy, the transaction opens
at repo.get, after the call has already returned, so the call holds no lock. The
risk that remains is that OCC or transient retry re-runs the whole method and
re-issues the call. Pass the remote system's idempotency key so the repeat is
harmless. Protean builds no mechanism for this; the idempotency key is what makes
the retry safe.
Sometimes the call itself needs a value that you can only read from the
aggregate first (a stored token, the current balance). Then the call has to run
between the read and the write, inside the transaction that the read opened.
protean check reports that method as HANDLER_PERSISTS_AND_CALLS_OUT. Keep the
call short, pass the idempotency key, and silence the check on that handler
with suppress_checks.
Anti-Patterns
One method that persists then calls out
This is the confirm_and_notify method from The Problem: the
external call sits inside the transaction the write opened, so it holds locks and
a connection while it waits on the partner, and an OCC retry re-posts. Split it
into confirm and notify_partner, and chain the call to OrderConfirmed when
it must follow the write.
One command per facet
It can look tidier to give each facet its own command: UpdateContact,
ChangePlan and SetFlags, all issued by the same event handler. With async
command processing, each command is delivered and processed on its own, in its
own transaction. When ChangePlan fails and waits for a retry, SetFlags still
runs, reads the old tier, and sets the wrong flags. Each command also loads
Subscriber and writes a new version of it, so one sync costs three writes
instead of one.
Keep facets that depend on each other in one command and one command handler method, where their order is the order of the code.
A fat event or a re-fetch per facet
Passing the fetched snapshot on the event makes the event large and writes the payload into the event store permanently. Re-fetching the snapshot for each facet turns one external call into one per facet. Persist the snapshot once, give it an identity, and load it by id.
When Not to Use / Trade-offs
The one-method form covered in When the two genuinely cannot be split is the exception: when the write needs the call's result, the split cannot help, so reach for the remote system's idempotency key.
Splitting persistence from external calls means more handler methods, and the value one method needs from another travels on an event. That is the cost of not holding a transaction open while an external call runs.
Summary
| Situation | What to write |
|---|---|
| Persist and call out, independent | Two sibling methods on one class |
| Call must follow the write, or needs its value | Persisting method raises an event; calling method handles it |
| Many facets of one aggregate from one snapshot | Fetch and persist the snapshot once, raise one event, and have its handler issue one command that applies every facet |
| A facet depends on what an earlier facet wrote | Apply both in the same method, in order |
| The write needs the call's result | One method, plus the remote system's idempotency key |
| Facets that touch different aggregates | One event handler on the event's aggregate issues one command per target aggregate |
| Facets that all mutate one aggregate | One command to that aggregate, never one command per facet |
Related reading
Guides:
- Unit of Work: When the transaction opens, and why a call-only method holds no connection.
- Event Handlers: Defining handlers, sibling independence, and subscriptions.
Reference:
- HANDLER_PERSISTS_AND_CALLS_OUT: The advisory check for a call that follows a repository access.
Explanation:
- ADR-0031: The decision and what was rejected along the way.
- Outbox: How an event published after commit delivers the value to the next handler.
Patterns:
- One Aggregate Per Transaction: The sibling rule for cross-aggregate writes.
- Idempotent Event Handlers: Making a duplicated delivery harmless.