Sub topic 7
Subscribing with an Apex trigger
An Apex trigger on a platform event is the most common way to react to events inside Salesforce. This chapter assumes you can write basic Apex triggers, know what a custom object and its fields are, and understand governor limits and transactions. It also assumes you have already defined an event such as Order_Shipped__e and can publish it.
How an event trigger differs from an object trigger
A platform event trigger looks like a normal trigger, but it behaves differently in four ways:
- It supports only
after insert. Events cannot be updated or deleted, so no other contexts exist. - It runs asynchronously, in its own transaction, as a system process. It does not run inside the publisher's transaction.
- It runs as the Automated Process user, not as the user who published the event. Do not rely on
UserInfo.getUserId()to identify the publisher. Trigger.newholds the delivered events. Salesforce can batch many events into one trigger run, so write the trigger in bulk.
The following diagram shows the path of one event.
A bulk-safe subscriber
This trigger creates one follow-up task for each delivered event. It collects the tasks in a list and inserts them once, so it uses one DML statement however many events arrive.
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
List<Task> tasks = new List<Task>();
for (Order_Shipped__e evt : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
));
}
insert tasks;
}Read the field values straight from each event in Trigger.new. Event fields use the same __c names you gave them in the event definition.
Things to remember
- Keep the trigger small. It shares the normal governor limits for a single Apex transaction, and a long run delays later events on the same trigger.
- Do not query for the event record. Platform events are not stored like other records, so SOQL and SOSL do not support them.
- Each subscriber is independent. If two triggers (or a trigger and a flow) subscribe to the same event, each one receives every event, and a failure in one does not stop the other.
- A trigger that fails with an unhandled exception does not roll back the publisher. The publisher's transaction has already finished.
Common errors
| Symptom | Likely cause |
|---|---|
| Trigger does not compile with `before insert` | Event triggers allow only `after insert`. |
| Trigger never fires | The event was not published, or publishing returned a failed `SaveResult`. Check `isSuccess()`. |
| Records show Automated Process as the creator | Expected. Event triggers run as that user by default. |
| `Too many DML statements` or `Too many SOQL queries` | DML or SOQL inside the `for` loop. Move it outside and use collections. |
| Trigger stops partway and events seem lost | An unhandled exception ended the run. Handle failures with resume checkpoints, covered in a later chapter. |
Checking that the trigger works
- Publish an event from Apex or the REST API.
- Open Setup, then Apex Jobs or the debug logs, and set up a trace flag for the Automated Process user.
- Look for the trigger's log entries and confirm that the Task records exist.
Exercise
Why does a platform event trigger support only after insert, and why should its loop avoid DML statements inside the loop?
Show answer
Events are immutable records that are only created, so insert is the only operation that occurs, and the trigger can act only after the event is delivered. The trigger may receive many events in one batch in Trigger.new, so DML inside the loop could exceed the DML statement limit. Collect the records in a list and run one DML statement after the loop.
Exercise
A publisher calls EventBus.publish and then immediately queries for the Task that the subscriber trigger should create. The query returns nothing. Why?
Show answer
The trigger runs asynchronously in its own transaction after the event is delivered, so it has not run yet when the publisher's query executes. The publisher cannot rely on the trigger's results within the same transaction.