Sub topic 8
Subscribing with a platform event-triggered flow
This chapter assumes you can build a basic record-triggered flow in Flow Builder. It also assumes you have defined the Order_Shipped__e event from earlier chapters, with the fields Order_Number__c and Status__c. You should know that event delivery is asynchronous.
A platform event-triggered flow is a subscriber that needs no code. When an event arrives on the event bus, Salesforce starts the flow and passes the event to it. The flow can then create or update records, call actions, or send notifications.
How the flow fits into the event model
A flow subscriber sits in the same place as an Apex trigger. The publisher puts an event on the bus, and the bus delivers it to every subscriber. The publisher does not know the flow exists.
Three consequences follow from this model:
- The flow runs in its own transaction, not the publisher's. If the flow fails, the publisher's transaction is not rolled back.
- Delivery happens after publishing, so a flow cannot return a value to the publisher.
- The flow receives a copy of the event. Changing
$Recorddoes not alter the event on the bus.
Creating the flow
- In Setup, open Flows and choose New Flow.
- Select Platform Event-Triggered Flow and choose Create.
- On the Start element, set Platform Event to
Order Shipped(Order_Shipped__e). - Add elements for the work you want done.
- Save and activate the flow.
The flow starts for every event of that type. If you only care about some events, add entry conditions to the Start element, such as Status__c equals Shipped. Events that fail the condition are skipped without starting an interview. An interview is one running instance of a flow.
Reading the event with $Record
The Start element exposes the event as the {!$Record} global variable. You read its fields with the same dot notation you use in record-triggered flows:
{!$Record.Order_Number__c}is the order number text.{!$Record.Status__c}is the status text.{!$Record.ReplayId}is the position of the event in the stream.{!$Record.CreatedDate}is the time the event was published.
To follow up on a shipped order, add a Create Records element that makes a Task. Set its Subject to a formula such as "Follow up on order " & {!$Record.Order_Number__c} and its Status to Not Started. This is the same outcome as the Apex trigger from the earlier chapter, built without code.
What runs, and as whom
Salesforce delivers events to the flow in batches and runs one interview per event. The interviews in a batch are bulkified, so a Create Records element in the flow does not issue one DML statement per event. The flow runs outside the publisher's transaction, so it gets its own set of governor limits. The interviews within a batch share those limits.
By default the flow runs as the Automated Process user, a system user, and not as the person who published the event. This matters in three places:
- The
CreatedByfield of records the flow creates shows the Automated Process user unless you set an owner explicitly. - Sharing and field-level security follow the running user, so records the flow reads may differ from what the original publisher could see.
- If you need the original actor, add a field such as
Published_By__cto the event and fill it in at publish time. Do not rely on$Userin the flow.
An administrator can choose a different running user for platform event-triggered flows, using the run-as setting for the flow. Check your org's Process Automation settings before you assume the default.
Handling failures
A flow subscriber does not offer the resume checkpoint and EventBus.RetryableException mechanism that an Apex trigger offers. If an element fails, the interview for that event ends with an error. The platform does not run the interview again on its own. Plan for failure inside the flow:
- Add a fault path to each element that can fail, such as Create Records, Update Records, and Action elements.
- On the fault path, record the problem. Typical choices are creating a custom
Integration_Error__crecord, sending an email alert, or posting to Chat. - Include
{!$Record.ReplayId}and{!$Flow.FaultMessage}in what you record, so you can find the event later. - Decide whether you can safely run the work again. If a flow created a Task and then failed on a later element, the Task is committed unless the failure happens inside the same transaction and rolls it back.
Common causes of failure are validation rules on the target records, required fields the flow forgot to fill, and record locks. If you need automatic retry with progress tracking, an Apex trigger is the better subscriber. Chapter 11 covers that approach.
Testing a flow subscriber
You cannot call a flow subscriber directly from a test. You test it by publishing an event and checking its effects. Events published during a test are held until Test.stopTest(), which delivers them to subscribers, including flows. After that call you can query the results.
@IsTest
private class OrderShippedFlowTest {
@IsTest
static void flowCreatesTaskWhenEventIsDelivered() {
Test.startTest();
Database.SaveResult sr = EventBus.publish(
new Order_Shipped__e(Order_Number__c = '00012345', Status__c = 'Shipped')
);
Test.stopTest();
System.assert(sr.isSuccess(), 'The event should be published');
List<Task> tasks = [
SELECT Id, Status
FROM Task
WHERE Subject = 'Follow up on order 00012345'
];
System.assertEquals(1, tasks.size(), 'The flow should create one Task');
System.assertEquals('Not Started', tasks[0].Status);
}
}This test assumes your flow is active and creates a Task with that subject. If the test finds no Task, check these in order:
- The flow version is activated, not just saved.
- The entry condition matches the event values the test publishes.
- The Create Records element has no required field left blank. Look for the error in the flow's failed interview emails or in debug logs.
- The test published the event between
startTestandstopTest.
Flow or trigger?
Both subscribe to the same events. The table compares them on the points that usually decide the choice.
| Concern | Platform event-triggered flow | Apex trigger |
|---|---|---|
| Skill needed | Admin or low-code builder | Developer |
| Retry on failure | None built in; use fault paths | `EventBus.RetryableException` and resume checkpoints |
| Complex logic | Limited to flow elements and invocable actions | Full Apex |
| Filtering | Entry conditions on the Start element | Code in the trigger |
| Running user | Automated Process by default | Automated Process by default |
| Testing | Publish an event in an Apex test and check the results | Same approach, and you can also unit test helper classes |
If you use both on the same event, they run independently and in no guaranteed order. Do not make one depend on the other's output.
Common mistakes
- Expecting the flow to run synchronously with the publisher. It runs after the publish, in a separate transaction, so the publisher cannot read its results immediately.
- Leaving the flow in Draft. Only an activated version receives events.
- Forgetting that the flow runs as the Automated Process user, then being surprised by record ownership and sharing.
- Omitting fault paths, so failures leave no trace.
- Using
$Recordfields that are not on the event. Add the field to the event definition first.
Exercise
A platform event-triggered flow creates a Task for each Order_Shipped__e event. An Apex test publishes an event and then immediately queries for the Task, but finds none. The flow is active. What is the likely problem, and how do you fix it?
Show answer
The test does not give the platform a chance to deliver the event. Published events are delivered to subscribers, including flows, when Test.stopTest() runs. Wrap the EventBus.publish call between Test.startTest() and Test.stopTest(), and run the query after stopTest().
Exercise
Name two reasons you might choose an Apex trigger over a platform event-triggered flow as the subscriber, and one thing you must add to the flow to detect failures.
Show answer
Two reasons are automatic retry with EventBus.RetryableException and resume checkpoints, and logic too complex for flow elements. To detect failures in the flow, add fault paths to the elements that can fail, and have those paths record the error, for example with the ReplayId and $Flow.FaultMessage.