Sub topic 4
Publishing events from Apex
This chapter covers publishing platform events with EventBus.publish. You should already know basic Apex (classes, triggers, DML), how a transaction commits or rolls back, and the governor limits. You should also have defined a platform event like Order_Shipped__e, with its fields and publish behavior, in the earlier chapters.
What EventBus.publish does
In Apex you publish a platform event by building an instance of the event's sObject type and passing it to EventBus.publish. An event type is an sObject whose API name ends in __e, so the code looks like record creation. The difference is that you don't call insert. You call EventBus.publish, and the event goes to the event bus instead of the database.
Order_Shipped__e evt = new Order_Shipped__e(
Order_Number__c = '00012345',
Status__c = 'Shipped'
);
Database.SaveResult sr = EventBus.publish(evt);
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug('Publish failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}EventBus.publish has two overloads:
| Call | Returns |
|---|---|
| `EventBus.publish(SObject event)` | `Database.SaveResult` |
| `EventBus.publish(List<SObject> events)` | `List<Database.SaveResult>` |
The list version returns one result per event, in the same order as the input list. You can use the index to match a failure to the event that caused it.
What a successful result means
isSuccess() returns true when Salesforce accepted the event for publishing. It does not mean any subscriber has received or processed the event. It also does not mean the event is already on the bus. When the event's publish behavior is Publish After Commit, a successful result means the event is queued. It is sent only if the surrounding transaction commits.
EventBus.publish does not throw an exception when an event fails validation. For example, a required field might be missing, or a field value might be too long. It returns an unsuccessful SaveResult. If you ignore the result, a failed publish is silent. Always check it.
Publish behavior decides when the event leaves
Publish behavior is a property of the event definition. You cannot choose it per call in Apex. The same EventBus.publish line behaves differently depending on that setting.
- Publish After Commit: the event is published only after the transaction commits successfully. If the transaction rolls back, for example because of an unhandled exception, the event is discarded. Subscribers never see events about changes that did not happen.
- Publish Immediately: the event is published as soon as
EventBus.publishruns. A later rollback does not retract it. This suits events that must survive a failure, such as logging or error reporting.
A practical consequence follows. If a subscriber trigger queries a record that your publishing transaction just saved, the record is visible only when the event uses Publish After Commit. With Publish Immediately, the subscriber might run before your commit and find stale or missing data. When the event describes saved data, prefer Publish After Commit. Publish Immediately is for events that must go out even if the transaction fails.
Publishing in bulk
Each EventBus.publish call counts as one DML statement against the per-transaction limit of 150. Calling it inside a loop wastes that limit and can fail on a large trigger batch. Build a list and publish once.
public with sharing class OrderShipmentPublisher {
public static void publishShipped(List<Order> orders) {
List<Order_Shipped__e> events = new List<Order_Shipped__e>();
for (Order o : orders) {
events.add(new Order_Shipped__e(
Order_Number__c = o.OrderNumber,
Status__c = 'Shipped'
));
}
List<Database.SaveResult> results = EventBus.publish(events);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(
LoggingLevel.ERROR,
'Event for order ' + orders[i].OrderNumber + ' failed: '
+ err.getStatusCode() + ' ' + err.getMessage()
);
}
}
}
}
}The index i works for both lists because the results keep the order of events, and events was built in the same order as orders. If you filter or skip orders while building the list, keep a separate list of the source records so the indexes still match.
Calling the publisher from a trigger
A common pattern is to publish from an after update trigger on a record. Keep the trigger thin and hand the work to a class like the one above.
trigger OrderStatusTrigger on Order (after update) {
List<Order> shipped = new List<Order>();
for (Order o : Trigger.new) {
Order oldOrder = Trigger.oldMap.get(o.Id);
if (o.Status == 'Shipped' && oldOrder.Status != 'Shipped') {
shipped.add(o);
}
}
if (!shipped.isEmpty()) {
OrderShipmentPublisher.publishShipped(shipped);
}
}The trigger compares old and new values so it publishes only when the status changes. Without that check, every later update to a shipped order would publish a duplicate event.
Failure modes and gotchas
- Unchecked results. A failed publish returns normally. Check every
SaveResult, or you will lose events with no error. - Rollback after publish. With Publish After Commit, an exception later in the transaction discards the queued event. This is usually what you want. With Publish Immediately, the event is already out, so subscribers can act on a change that was rolled back.
- Duplicates. Subscribers can receive an event more than once, and the order across separate publishes is not a business guarantee. Design subscribers to be idempotent, for example by keying on
Order_Number__c. - No return of event data. The
SaveResultdoes not give you a record you can query or update. A platform event is a message, not a stored row. TheReplayIdis assigned by the bus and subscribers see it. You don't get it back from the publish call. - Limits. Besides the DML statement count, a transaction has a cap on events published, and the org has a daily allocation of delivered events. A later chapter covers these and how to monitor them. If you publish thousands of events, check the current numbers for your edition.
- Sharing and security. Event definitions have object permissions. The running user needs create access on the event to publish it. A user without it gets a failed result or an insufficient-access error, so test with realistic profiles, not only as an administrator.
Verifying publishing in a test
Events published in a test are not delivered until Test.stopTest() runs. Place the publish call between Test.startTest() and Test.stopTest(), then assert on what the subscriber created.
@IsTest
private class OrderShippedTriggerTest {
@IsTest
static void createsTaskWhenEventIsDelivered() {
Test.startTest();
Database.SaveResult sr = EventBus.publish(
new Order_Shipped__e(Order_Number__c = '00012345', Status__c = 'Shipped')
);
Test.stopTest();
System.assert(sr.isSuccess(), 'The event should be published');
System.assertEquals(1, [SELECT COUNT() FROM Task WHERE Subject = 'Follow up on order 00012345']);
}
}This test checks two things. The SaveResult shows the publish was accepted, and the Task count shows the subscriber trigger ran after delivery. If you query before Test.stopTest(), the count is 0, because the event has not been delivered yet. Chapter-level testing details, such as publishing in a unit test of the publisher class alone, come later.
Quick reference
| Question | Answer |
|---|---|
| Can Apex choose the publish behavior per call? | No. It is set on the event definition. |
| Does `isSuccess()` mean subscribers processed the event? | No. It means the event was accepted for publishing. |
| What happens on a validation error? | An unsuccessful `SaveResult` is returned. No exception is thrown. |
| How should I publish many events? | Pass one list to a single `EventBus.publish` call. |
| When does a test deliver events? | At `Test.stopTest()`. |
Exercise
A trigger on Order publishes one Order_Shipped__e inside a for loop over Trigger.new, and a bulk update of 200 orders fails with a DML limit error. What is the cause, and how do you fix it?
Show answer
Each EventBus.publish call counts as one DML statement, so 200 calls in a loop exceed the 150 DML statement limit. Build a List<Order_Shipped__e> in the loop, call EventBus.publish(events) once after the loop, and check every SaveResult in the returned list.
Exercise
An event is defined with Publish After Commit. Your Apex code calls EventBus.publish, gets isSuccess() == true, and then throws an unhandled exception later in the same transaction. Do subscribers receive the event? What would change if the event used Publish Immediately?
Show answer
No. With Publish After Commit the event is only queued, and the rollback discards it. With Publish Immediately the event is sent when EventBus.publish runs, so subscribers receive it even though the transaction rolls back.