Sub topic 1
How publishers, the event bus, and subscribers fit together
Prerequisites
Assume you know basic Apex, triggers, Salesforce custom fields, and transactions. You should also understand that Apex governor limits restrict work in one transaction.
The event-driven model
A publisher creates a message called a platform event. Salesforce places the event on the event bus, which temporarily stores and delivers it. A subscriber listens for that event and performs work when delivery occurs. Subscribers can be Apex triggers, flows, Lightning Web Components, or external applications.
The publisher and subscriber are loosely coupled. The publisher does not call a subscriber directly or need to know how it handles the event.
Defining a platform event and its fields
A platform event is a Salesforce metadata object whose API name ends in __e. Define it in Setup, then add custom fields such as Order_Number__c and Status__c. These fields form the event payload, the data carried by each message.
An event is not the same as an ordinary record. Subscribers receive delivered messages, and the event bus assigns each message a replay ID that can help a subscriber resume from a known position.
Choosing publish timing
Choose the publish behavior based on transaction consistency:
- Publish After Commit sends the event only when the transaction commits. Use it when subscribers must not see a message about data that later rolls back.
- Publish Immediately sends the event during the transaction. Use it when subscribers need the message even if the publishing transaction fails later. The subscriber might then observe data that was not committed.
After-commit publishing is usually safer for events describing saved business data. Immediate publishing can support notifications or integration signals that must not wait for the transaction result.
Publishing from Apex
Apex publishes an event with EventBus.publish. Check the returned SaveResult and log or handle errors.
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());
}
}Exercise
When should an order-shipped event use Publish After Commit?
Show answer
Use Publish After Commit when subscribers should act only after the order transaction has committed successfully.