Sub topic 11
Handling failures with resume checkpoints and retries
This chapter assumes you can write Apex triggers, know how governor limits and transactions work, and have already built a platform event trigger like the one in the earlier chapter on subscribing with Apex triggers. You should also know what a replay ID is from the chapter on replay and retention.
Why event triggers need their own error handling
A platform event trigger runs in its own transaction, separate from the transaction that published the event. If the publisher's transaction has already committed, nobody is waiting on the subscriber. An unhandled exception in the trigger does not travel back to the publisher. This changes how you think about failure.
A trigger receives events in batches of up to 2,000 in Trigger.new. If your code fails halfway through a batch, you have three choices:
- Let the exception propagate and accept that the batch is lost for this trigger.
- Catch the error, log it, and carry on with the next event.
- Ask the platform to run the trigger again.
The third choice is what resume checkpoints and EventBus.RetryableException give you.
What happens by default
If an event trigger throws an unhandled exception or hits a governor limit, the transaction rolls back. Any DML the trigger did for that batch is undone. The platform does not redeliver the batch. The events are gone from the point of view of this trigger, although they stay on the event bus until the retention window ends. The trigger moves on to later events.
This is a major difference from record triggers, where a failure surfaces to the user who caused the DML. With events, a failure can go unnoticed unless you log it or retry it.
Retrying with EventBus.RetryableException
When you throw EventBus.RetryableException, Salesforce rolls back the current trigger transaction and runs the trigger again with the same batch of events. The retry happens after a delay, and it repeats until the trigger succeeds or the retry limit is reached.
Use it for temporary problems, for example:
- A row lock on a record that another transaction is updating.
- A callout dependency that is briefly unavailable.
- A limit that is likely to clear on the next run.
Do not use it for permanent problems, such as a validation rule that will fail every time, or a null value that your code does not expect. Retrying those gives the same result every time and wastes capacity.
How many retries are allowed
A trigger can be retried up to 9 times, so it runs at most 10 times for the same batch. After the last retry, if the trigger still throws, the batch is dropped for that trigger. Check the current Platform Events Developer Guide for the exact figure, because Salesforce may change limits between releases.
Resume checkpoints
A plain retry starts again from the first event in Trigger.new. If the trigger already handled 150 of 200 events, and the 151st fails, a plain retry repeats work on the first 150. Worse, the transaction rolled back, so the first 150 results were discarded anyway.
A resume checkpoint tells the platform where to start next time. You call setResumeCheckpoint with the replay ID of the last event you want to count as done. When the trigger is retried, Trigger.new contains only the events after that replay ID.
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);
}
}Three details in this code matter:
- The checkpoint is set after the event is processed, so a retry resumes after that event, not on it.
- The exception is thrown outside the point where the checkpoint is set, so the failing event is never checkpointed.
evt.ReplayIdis the field the platform fills in for each delivered event.
The retry sequence
The diagram shows one batch with a failure on the third event.
What a checkpoint does to your DML
This point causes many bugs. When you throw RetryableException, the transaction rolls back. If DML for events 1 and 2 was still pending in the same transaction, that work is lost, while the checkpoint says events 1 and 2 are done.
The platform handles this by committing the work done up to the last checkpoint before it retries. Even so, treat the behavior with care:
- Keep per-event work small and self-contained, so a checkpoint marks a clean boundary.
- Avoid batching all DML into one list at the end of the loop if you also set checkpoints inside it. Work you have not yet committed cannot be covered by a checkpoint you have already set.
- Test the failure path, not only the success path.
If you must bulkify DML for efficiency, set the checkpoint only after the DML for those events succeeds:
trigger OrderShippedBulkTrigger on Order_Shipped__e (after insert) {
List<Task> tasks = new List<Task>();
Order_Shipped__e lastEvent;
for (Order_Shipped__e evt : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
));
lastEvent = evt;
}
try {
insert tasks;
} catch (DmlException e) {
throw new EventBus.RetryableException('Retrying batch: ' + e.getMessage());
}
if (lastEvent != null) {
EventBus.TriggerContext.currentContext().setResumeCheckpoint(lastEvent.ReplayId);
}
}This version treats the whole batch as one unit. A failure retries the full batch, which is acceptable here because the insert either succeeds completely or rolls back.
Choosing between retry, catch, and fail
Not every error deserves a retry. Use this table as a starting point.
| Situation | Suggested response |
|---|---|
| Row lock or temporary contention | Throw `EventBus.RetryableException` |
| Callout target briefly unavailable | Throw `EventBus.RetryableException` |
| Bad data in one event, such as a missing required field | Catch, log, and continue with the next event |
| Programming error, such as a null reference | Fix the code. Do not retry |
| Governor limit exceeded because the batch is large | Reduce work per event, or use a checkpoint so each run handles fewer events |
A common pattern is to separate the two kinds of problem:
trigger OrderShippedSafeTrigger on Order_Shipped__e (after insert) {
for (Order_Shipped__e evt : Trigger.new) {
if (String.isBlank(evt.Order_Number__c)) {
// Permanent problem: log it and skip. Retrying cannot fix it.
System.debug(LoggingLevel.ERROR, 'Skipping event ' + evt.ReplayId + ': no order number');
} else {
try {
insert new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
);
} catch (DmlException e) {
// Possibly temporary: ask for a retry from the last checkpoint.
throw new EventBus.RetryableException('Retrying: ' + e.getMessage());
}
}
EventBus.TriggerContext.currentContext().setResumeCheckpoint(evt.ReplayId);
}
}Skipped events still get a checkpoint, so a later retry does not revisit them.
Common errors
- Retrying a permanent failure. The trigger fails up to the retry limit, then the batch is dropped. You also delay later events in the same channel.
- Setting the checkpoint before the work. If the event then fails, a retry skips it and the event is silently lost.
- Forgetting that retries repeat side effects. If your trigger sends a callout or creates a record before it fails, the retry may do it again. Make the work idempotent. For example, store the event's
ReplayIdor a unique key on the record and check it before creating a duplicate. - Catching the exception and not rethrowing. If you catch an error and swallow it, the platform sees success and never retries.
- Expecting retries in tests to behave like production. The retry delay and limits are platform behavior, so confirm retry handling in a sandbox as well as in unit tests.
Observing failures
Because failures do not reach the publisher, you need to look for them. Useful places include:
- Debug logs for the Automated Process user, which runs event triggers by default.
- The Apex Jobs and event monitoring data described in the chapter on allocations and monitoring.
- A custom log object that your catch blocks write to.
You can also run a trigger as a specific user by configuring the trigger's subscription, which changes whose permissions apply and whose name appears in logs. Check the setup options for platform event triggers in your org.
Summary of the working model
- Event triggers run in their own transaction, so failures stay with the subscriber.
EventBus.RetryableExceptionrolls back and reruns the trigger for temporary problems.setResumeCheckpointwith an event'sReplayIdmakes a rerun start after that event.- Set checkpoints after the work succeeds, and write idempotent logic.
- Log or skip permanently bad events, and retry only what can recover.
Exercise
A trigger processes 100 events in a loop. For each event it calls setResumeCheckpoint(evt.ReplayId) first, and then inserts a Task. On event 40 the insert hits a row lock and the trigger throws EventBus.RetryableException. What goes wrong, and how do you fix it?
Show answer
The checkpoint for event 40 was already set before its work finished, so the retry resumes after event 40 and the event is skipped, leaving its Task uncreated. Move the setResumeCheckpoint call to after the insert succeeds, so the checkpoint only covers events that are done and the retry starts again at event 40.
Exercise
An event arrives with a blank Order_Number__c, and your code treats a blank value as an error. Should the trigger throw EventBus.RetryableException? Explain.
Show answer
No. A blank value is a permanent data problem, and a retry sees the same event with the same blank value, so it fails again until the retry limit is reached and the batch is dropped. Log or record the bad event, skip it, set the checkpoint for it, and continue with the next event. Reserve retries for temporary problems such as row locks.