Newer Version Available
Retry Event Triggers with EventBus.RetryableException
An example of a transient condition: A trigger adds a related record to a master record if a field on the master record equals a certain value. It is possible that in a subsequent try, the field value changes and the trigger can perform the operation.
To retry the event trigger, throw EventBus.RetryableException. The event is resent after a small delay. The delay increases in subsequent retries. A resent event has the same field values as the original event, but the batch sizes of the events can differ. For example, the initial trigger can receive events with replay ID 10 to 20. The resent batch can be larger, containing events with replay ID 10 to 40.
You can run a trigger up to 10 times when it is retried (the initial run and 9 retries). After the trigger is retried 9 times, it moves to the error state and stops processing new events. To resume event processing, fix the trigger and save it. Events sent after the trigger moves to the error state and before it returns to the running state are not resent to the trigger. We recommend setting a limit to retry the trigger to less than 9 times. Use the EventBus.TriggerContext.currentContext().retries property to check how many times the trigger has been retried.
This example is a skeletal trigger that gives you an idea of how to throw EventBus.RetryableException and limit the number of retries. The trigger uses an if statement to check whether a certain condition is true. Alternatively, you can use a try-catch block and throw EventBus.RetryableException in the catch block.
1trigger ResendEventsTrigger on Low_Ink__e (after insert) {
2 if (condition == true) {
3 // Process platform events.
4 } else {
5 // Ensure we don't retry the trigger more than 4 times
6 if (EventBus.TriggerContext.currentContext().retries < 4) {
7 // Condition isn't met, so try again later.
8 throw new EventBus.RetryableException(
9 'Condition is not met, so retrying the trigger again.');
10 } else {
11 // Trigger was retried enough times so give up and
12 // resort to alternative action.
13 // For example, send email to user.
14 }
15 }
16}