Sub topic 7
Subscribing with an Apex Trigger
This chapter covers how an Apex trigger subscribes to a platform event, how that trigger runs, and the mistakes that cause trouble in practice. It assumes you can write basic Apex triggers and DML, know how custom objects and fields work, and understand governor limits and transactions. You should also have defined a platform event such as Order_Shipped__e and know how to publish it. Those topics come from earlier chapters.
How a trigger subscribes
An Apex trigger on a platform event object is a subscriber. When the event bus delivers a published event, Salesforce runs the trigger. You don't register a subscription anywhere else. The trigger is the subscription.
A platform event trigger has these properties:
- It runs only on
after insert. Events can't be updated or deleted, so there are no other contexts. Salesforce rejects any other trigger event on a platform event. Trigger.newholds the delivered events. Each one is an instance of your event type, such asOrder_Shipped__e.- It runs asynchronously, in its own transaction. This transaction is separate from the one that published the event.
- It runs as the Automated Process user, not as the user who published the event.
This is the basic subscriber:
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;
}The trigger loops over every event in Trigger.new, builds one Task per event, and inserts them all with a single DML statement. This is the standard bulk pattern. Don't put DML or SOQL inside the loop.
The separate transaction
Because the trigger runs in its own transaction, three things follow.
- The publisher can't roll back the subscriber's work. Once an event is published and delivered, the records the trigger created are committed on their own. If the publisher's transaction later fails, the subscriber's records stay. Whether the event is published at all in that case depends on the event's publish behavior, covered in an earlier chapter.
- The subscriber can't roll back the publisher's work. If the trigger throws an unhandled exception, the publisher's records are unaffected.
- Governor limits are fresh. The trigger gets its own set of limits, not the publisher's remaining budget. Event trigger transactions use the asynchronous limits, not the synchronous ones.
This isolation is the reason to use events at all. It also means you can't assume the subscriber has seen everything the publisher did. Records the publisher saved are visible if its transaction committed. Records that the publisher's transaction rolled back are not.
Batches and ordering
The trigger doesn't receive one event per run. Salesforce delivers events in batches, and the default batch size for a platform event trigger is 2,000. A single trigger run can therefore see many events, and you must write it in bulk.
Events arrive in the order they were published, and each carries a ReplayId. Within one trigger run, Trigger.new is in that order. Treat the order as a convenience, not a guarantee that you can use for business logic across batches. If two events must be applied in a strict sequence, put a sequence field or timestamp in the payload and check it.
You can change the batch size by configuring the trigger. Use a smaller size when each event is expensive to process, for example when it makes a callout or touches many records. A smaller batch lowers the chance of hitting a limit, but it increases the number of trigger runs.
What you can and can't do in the trigger
Event triggers are ordinary Apex, with a few points to keep in mind.
- DML and SOQL work as in any trigger, within the asynchronous limits.
- Callouts are not allowed directly from the trigger. Call a
@future(callout=true)method or enqueue aQueueablethat implementsDatabase.AllowsCallouts. - Publishing other events is allowed. A subscriber can publish a follow-up event, which lets you chain steps. Watch for loops where event A causes event B, which causes event A.
- Field access on the event uses the custom fields you defined, such as
evt.Order_Number__c. System fields includeReplayId,CreatedDate, andCreatedById.
Because the trigger runs as the Automated Process user, UserInfo.getUserId() returns that user, not the publisher. If you need to know who published, read CreatedById from the event. Sharing and field-level security are not enforced for the Automated Process user in the way they would be for a normal user, so apply your own checks if the logic needs them.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| `Too many SOQL queries` or `Too many DML statements` | Query or DML placed inside the `for` loop over `Trigger.new` | Collect data first, then run one query or one DML after the loop |
| Trigger fails to save | Used `before insert`, `after update`, or another context | Use only `after insert` |
| Callout error | Callout made directly in the trigger | Move the callout to a `Queueable` with `Database.AllowsCallouts` |
| Duplicate records after a retry | The trigger reprocesses events it already handled | Make the work idempotent, or use resume checkpoints |
| Subscriber appears to do nothing | Unhandled exception in the trigger, or the trigger was suspended after repeated failures | Check the debug logs for the Automated Process user and the trigger's state in Setup |
| Wrong user in audit fields | Records are owned by the Automated Process user | Set `OwnerId` explicitly, or use `CreatedById` from the event |
Debugging a platform event trigger
Debug logs for event triggers are tied to the Automated Process user, not your own user. To see them, add a trace flag for that user in Setup and then publish an event. System.debug statements in the trigger then appear in that log.
In a developer sandbox, a useful habit is to publish a single event and watch the log before testing with larger volumes. Then publish a larger batch and check that the trigger still performs one query and one DML statement per run.
Unhandled exceptions in an event trigger don't surface to the publisher. The publisher already finished. The failure shows up only in the log and in the trigger's state. This is why logging and error handling in the subscriber matter more than they do in a synchronous trigger.
Failure and retry
When a trigger fails, you have a choice about what happens next.
- Do nothing. An unhandled exception ends that run. The events in that batch are not redelivered to this trigger, and the work is lost unless something else recovers it.
- Retry the batch. Throw
EventBus.RetryableException. Salesforce runs the trigger again with the same events, up to a limit of nine retries. After that, the trigger moves on and the batch is dropped. Use this only for temporary conditions, such as a record lock or a service that is briefly down. - Retry from a checkpoint. Call
EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId)after each event you process successfully. When you then throwEventBus.RetryableException, the retry starts from the event after the checkpoint instead of from the start of the batch.
The next example sets a checkpoint after each event:
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
for (Order_Shipped__e evt : Trigger.new) {
try {
// Process one event here.
} catch (Exception e) {
throw new EventBus.RetryableException('Retrying event: ' + e.getMessage());
}
// Record progress so a retry resumes after this event.
EventBus.TriggerContext.currentContext().setResumeCheckpoint(evt.ReplayId);
}
}A later chapter on resume checkpoints covers this in detail. For now, remember two cautions. First, a retry reruns the trigger, so any work done before the exception that was not rolled back may happen twice. Second, DML you ran before the exception is rolled back when the exception is thrown, but callouts and published events are not.
Design guidance
- Keep the trigger thin. Put the logic in a handler class. This makes it testable and reusable, as with any trigger.
- Make processing idempotent. Retries, and the chance of replay, mean an event can be handled more than once. Use an external ID or a lookup on the event's key field to avoid creating duplicates.
- Handle one bad event without losing the batch. If one event has bad data, decide whether to skip it and log it or fail the whole batch. Throwing a non-retryable exception drops the entire batch.
- Don't depend on the publisher's session. The trigger can't read the publisher's user, session, or in-memory state. Put everything the subscriber needs in the event fields.
- Limit what the event carries. Send identifiers and the facts needed to act, and let the subscriber query the current record. A large payload copies stale data into the event.
Summary
A platform event trigger is an after insert trigger that Salesforce runs asynchronously, in its own transaction, as the Automated Process user, on batches of up to 2,000 events. Write it in bulk, keep callouts out of it, make its work safe to repeat, and use EventBus.RetryableException with resume checkpoints for temporary failures.
Exercise
A platform event trigger loops over Trigger.new and runs a SOQL query for each event. It works in a test with one event, but fails in production with "Too many SOQL queries". Why does it fail, and how do you fix it?
Show answer
Salesforce delivers events in batches, so Trigger.new can hold hundreds or thousands of events, and a query inside the loop runs once per event. Collect the keys from all events first, run one query before or after the loop (for example into a Map), and use the map inside the loop.
Exercise
An event trigger throws EventBus.RetryableException after it has processed 40 of 100 events. How can you make the retry start at event 41 instead of event 1?
Show answer
Call EventBus.TriggerContext.currentContext().setResumeCheckpoint(evt.ReplayId) after each event is processed successfully. When the exception is thrown, the retry resumes from the event after the last checkpoint.