Publishing Platform Events Without Error Handling
“Platform Events can fail to publish. If you don't check, you'll never know.”
What Happened
I set up Platform Events to decouple a complex Opportunity process at Mobilization Funding. Fire-and-forget, right? Wrong. During a high-volume import, some events hit the publish limit. The trigger kept running but events silently dropped. Half the downstream automations never fired. The ops team spent a full day reconciling records manually.
The Wrong Way
trigger OpportunityEvents on Opportunity (after insert) {
List<Opp_Created__e> events = new List<Opp_Created__e>();
for (Opportunity opp : Trigger.new) {
events.add(new Opp_Created__e(
Opp_Id__c = opp.Id,
Amount__c = opp.Amount
));
}
EventBus.publish(events); // fire and forget - hope it works!
}The Right Way
trigger OpportunityEvents on Opportunity (after insert) {
List<Opp_Created__e> events = new List<Opp_Created__e>();
for (Opportunity opp : Trigger.new) {
events.add(new Opp_Created__e(
Opp_Id__c = opp.Id,
Amount__c = opp.Amount
));
}
List<Database.SaveResult> results = EventBus.publish(events);
List<Error_Log__c> errors = new List<Error_Log__c>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
errors.add(new Error_Log__c(
Source__c = 'OpportunityEvents Trigger',
Message__c = err.getMessage(),
Record_Id__c = Trigger.new[i].Id
));
}
}
}
if (!errors.isEmpty()) { insert errors; }
}The Lesson
EventBus.publish returns SaveResults. Check them. Log failures. Platform Events are reliable but not infallible.
Enjoyed this? Get more like it.
Glen's Musings — AI, investing, and building things. Occasional. Free.
More Integration Mistakes
Making a Callout from a Trigger
You cannot make HTTP callouts from a synchronous trigger context. Period.
Read moreCareer-EndingHardcoding API Credentials Instead of Using Named Credentials
Hardcoded API keys in Apex are a security audit's worst nightmare.
Read moreAnnoyingNo Retry Logic on External API Calls
External APIs fail. Your integration should expect that.
Read more