Newer Version Available
Subscribe to Platform Event Notifications with Apex Triggers
To subscribe to event notifications, write an after insert trigger on the event object type. The after insert trigger event corresponds to the time after a platform event is published. After an event message is published, the after insert trigger is fired.
Example
This example shows a trigger for the Low Ink event. It iterates through each event and checks the Printer_Model__c field value. The trigger inspects each received notification and gets the printer model from the notification. If the printer model matches a certain value, other business logic is executed. For example, the trigger creates a case to order a new cartridge for this printer model.
An Apex trigger processes platform event notifications sequentially in the order they’re received. The order of events is based on the event replay ID. An Apex trigger can receive a batch of events at once. The order of events is preserved within each batch. The events in a batch can originate from one or more publishers.
Unlike triggers on standard or custom objects, triggers on platform events don’t execute in the same Apex transaction as the one that published the event. The trigger runs asynchronously in its own process under the Automated Process entity. As a result, there might be a delay between when an event is published and when the trigger processes the event. Also, debug logs corresponding to the trigger execution are created by Automated Process. System fields, such as CreatedById and LastModifiedById, reference the Automated Process entity.
Event triggers have many of the same limitations of custom and standard object triggers. For example, with some exceptions, you generally can’t make Apex callouts from triggers. For more information, see Implementation Considerations for triggers in the Apex Developer Guide.
Platform Event Triggers and Apex Governor Limits
Platform event triggers are subject to Apex governor limits.
- Synchronous Governor Limits
- When governor limits are different for synchronous and asynchronous Apex, the synchronous limits apply to platform event triggers. Asynchronous limits are for long-lived processes, such as Batch Apex and future methods. Synchronous limits are for short-lived processes that execute quickly. Although platform event triggers run asynchronously, they’re short-lived processes that execute in batches rather quickly.
- Reset Limits
- Because a platform event trigger runs in a separate transaction from the one that fired it, governor limits are reset, and the trigger gets its own set of limits.