Subscribe to Platform Event Notifications with Apex Triggers

Use Apex triggers to subscribe to events. You can receive event notifications in triggers regardless of how they were published—through Apex or APIs. Triggers provide an autosubscription mechanism. No need to explicitly create and listen to a channel in Apex.

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.

// Trigger for catching Low_Ink events.
trigger LowInkTrigger on Low_Ink__e (after insert) {    
    // List to hold all cases to be created.
    List<Case> cases = new List<Case>();
    
    // Get user Id for case owner. Replace username value with a valid value.
    User adminUser = [SELECT Id FROM User WHERE Username='admin@acme.org'];
       
    // Iterate through each notification.
    for (Low_Ink__e event : Trigger.New) {
        System.debug('Printer model: ' + event.Printer_Model__c);
        if (event.Printer_Model__c == 'MN-123') {
            // Create Case to order new printer cartridge.
            Case cs = new Case();
            cs.Priority = 'Medium';
            cs.Subject = 'Order new ink cartridge for SN ' + event.Serial_Number__c;
            // Optional: Set case owner ID so it is not Automated Process.
            // This step is not needed if the running user is overridden 
            // or if using assignment rules.
            cs.OwnerId = adminUser.Id;
            cases.add(cs);
        }
    }
    
    // Insert all cases in the list.
    if (cases.size() > 0) {
        insert cases;
    }
}

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 maximum batch size in a platform event trigger is 2,000 event messages. 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. As a result, there can be a delay between when an event is published and when the trigger processes the event.

The trigger runs under the Automated Process entity or the user you select in the trigger configuration. If no user is configured, debug logs corresponding to the trigger execution are created by Automated Process. System fields, such as CreatedById and LastModifiedById, reference the Automated Process entity. You can override the trigger's default running user so that the user for debug logs and records is set to the selected user. For more information, see Configure the User and Batch Size for Your Platform Event Trigger with PlatformEventSubscriberConfig.

The OwnerId field of records saved in the trigger is set to the trigger's running user. By default, it’s Automated Process. For more information on how to change the OwnerId, see Considerations for Publishing and Subscribing to Platform Events with Apex and APIs.

Note

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 Uncaught Exceptions

If an uncaught exception occurs during trigger execution, the trigger stops executing and doesn't process the remaining event messages in the current batch. Uncaught exceptions are exceptions that the trigger doesn't handle in a catch block or limit exceptions. As long as the trigger hasn’t exceeded the Apex execution-time limit, the DML operations that were carried out before the uncaught exception are committed and aren't rolled back. Committing the DML transactions enables you to use the setResumeCheckpoint() method to continue trigger execution from where it left off. With this method, the trigger resumes and picks up the unprocessed event messages from the previous batch. For more information, see Resume a Platform Event Trigger After an Uncaught Exception.

DML transactions are rolled back only when:

  • The trigger throws the EventBus.RetryableException.
  • The trigger exceeds the Apex execution-time limit of 10 minutes. See Maximum execution time for each Apex transaction in Execution Governors and Limits 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.