How do developers optimize high-throughput event publishing strategies to prevent governor limit exhaustion?
Answer
Basics: Each EventBus.publish call counts as one DML statement (limit 150 per transaction), and each event counts toward an hourly publishing allocation for the org. Publishing one event per loop iteration can burn the DML limit quickly and also wastes allocation efficiency.
How it works:
- Collect events in a
List<Event__e>during the transaction. - Call
EventBus.publish(list)once, after the loop. - Inspect each
SaveResult. - For very large volumes, move the work to Batch or Queueable Apex, or publish from outside Salesforce through Pub/Sub API or REST in batches.
- Monitor usage with
/limits(hourly published events) and alert before you hit the cap.
Advanced / deep dive: Combine several small business changes into a single event with a list payload, if subscribers can handle it, to cut event counts. Remember that Change Data Capture publishes for you without Apex, so do not duplicate it with custom events. Use "Publish After Commit" so rolled-back transactions publish nothing. When failures happen, a stray retry loop can double-publish, so use an idempotency key. If your publisher is Flow, use a single Create Records element with a collection rather than one per record. For external publishers, the Pub/Sub API supports batch publish and is better than one REST call per event. If you exceed the hourly allocation, publishing returns errors, and you may need to queue events in a custom object and retry (verify current error codes).
Code / config example:
public static void {
List<Order_Event__e> batch = <Order_Event__e>();
(Order o : orders) {
batch.add( (Order_Id__c = o.Id, Key__c = o.Id + + o.LastModifiedDate.getTime()));
}
(!batch.isEmpty()) {
List<Database.SaveResult> res = EventBus.publish(batch);
System.debug( + (Limits.getLimitDmlStatements() - Limits.getDmlStatements()));
}
}