Newer Version Available
Resume a Platform Event Trigger After an Uncaught Exception
By processing fewer event messages, your trigger is less likely to hit Apex governor limits. The maximum batch size of a platform event trigger is 2,000, while the maximum of an Apex object trigger is 200. Therefore, platform event triggers are more likely to reach limits and can benefit from this feature.
To set a checkpoint for trigger resumption, set the replay ID of the last successfully processed event message using this method call.
When the trigger stops its flow of execution, either intentionally or because of an unhandled exception, such as a limit exception, it fires again with a new batch (the sObject list in Trigger.New). The new batch starts with the event message after the one with the replay ID that you set. The events are resent in their original order based on the ReplayID field values, which are unchanged. The trigger processes the resent events and later batches sequentially. The setResumeCheckpoint(replayId) method doesn’t cause the trigger execution to stop, but you can end the execution explicitly. For example, to control the batch size, end the execution flow after some event messages are processed.
If the supplied Replay ID isn’t valid, the method throws an EventBus.InvalidReplayIdException. An invalid Replay ID is a replay ID that isn’t in the current trigger batch of events in the Trigger.new list.
Example
This example trigger sets the replay ID of the last processed event message in each iteration. If a limit exception occurs, the trigger is fired again and resumes processing starting with the event message after the one with the set replay ID.
Example
This example controls the platform event trigger batch size and matches it with the 200 batch size of Apex object triggers. The trigger counts the number of event messages processed. The setResumeCheckpoint(replayId) is called in each iteration of the loop after each event message that is successfully processed. The loop is exited if you exceed the count of 200 events, and the trigger stops execution. If you have unprocessed event messages, the trigger fires again. The list of event messages sent to the new trigger invocation starts with the event message after the one with the set replay ID.
The TestBatchSizeTriggerResumption test class contains a test for the ControlBatchSizeTrigger. The test method in the class publishes 201 event messages. Next, it calls the deliver() method twice to fire the trigger twice. The first invocation processes 200 event messages. The second invocation processes the last event message. The test verifies that the trigger was invoked by inspecting the EventBusSubscriber.Position property, which holds the replay ID of the last processed event message.