Sub topic 3
Choosing publish after commit or publish immediately
This chapter assumes you can read Apex triggers and DML, and that you know a Salesforce transaction either commits or rolls back as a unit. It also assumes you have defined a platform event, as covered in the previous chapter. Here you decide when Salesforce should publish an event relative to the transaction that asked for it.
The setting lives on the event definition
Every platform event definition has a publish behavior. The behavior belongs to the event, not to the code that publishes it. Every EventBus.publish call, flow, or REST request for that event follows the same rule. There are two values:
- Publish After Commit: the event is published only after the publishing transaction commits successfully.
- Publish Immediately: the event is published when the publish call runs. The outcome of the surrounding transaction does not matter.
In Setup, you choose this when you create the event, using the Publish Behavior field. In metadata, it is the publishBehavior element:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<deploymentStatus>Deployed</deploymentStatus>
<eventType>StandardVolume</eventType>
<label>Order Shipped</label>
<pluralLabel>Order Shipped Events</pluralLabel>
<publishBehavior>PublishAfterCommit</publishBehavior>
</CustomObject>Use PublishImmediately as the value for the other behavior. Because the setting is part of the event's design, decide it before subscribers depend on the event. Changing it later changes what every existing subscriber can assume.
What each behavior guarantees
The behaviors differ in two ways: what happens on rollback, and what a subscriber can see when it runs.
| Question | Publish After Commit | Publish Immediately |
|---|---|---|
| When is the event published? | After the transaction commits | When the publish call executes |
| What if the transaction rolls back? | The event is never published | The event is already published and stays published |
| Can a subscriber see the transaction's data changes? | Yes, they are committed before the event is published | Not reliably. The subscriber may run before the commit, or the commit may never happen |
| Typical use | Announcing that business data changed | Logging, auditing, and failure reports that must survive a rollback |
The following diagram shows both paths for a transaction that fails.
Publish After Commit: events that describe committed data
Publish After Commit is the right default for most business events. An event such as Order_Shipped__e says "this happened." If the transaction that records the shipment fails and rolls back, the shipment did not happen, so no one should be told it did.
This behavior gives you two benefits:
- No phantom events. A rollback removes both the data changes and the event, so downstream systems never act on something that was undone.
- Data is visible to subscribers. By the time a subscriber trigger or an external client receives the event, the data it refers to is committed. A subscriber can query the order record and find it.
The cost is that a failed transaction leaves no trace in the event stream. If an event must record the failure itself, this behavior hides it.
A related point concerns SaveResult. For an after-commit event, isSuccess() returning true means Salesforce accepted the publish request. It does not prove subscribers received the event, because the commit has not happened yet. If a later statement in the same transaction throws an unhandled exception, the event is discarded even though your SaveResult check passed.
Publish Immediately: events that must survive a rollback
Some events are not claims about committed data. They report on the transaction itself. Think of error logs, audit records, and diagnostics. If you wrote an error log as a custom object record, a rollback would delete the log along with the work that failed. A platform event published immediately avoids that, because the event is not part of the database transaction.
This example uses an event named Integration_Error__e with Publish Immediately set. It has two text fields, Source__c and Message__c.
public with sharing class ShipmentService {
public class ShipmentException extends Exception {}
public static void markShipped(List<Order> orders) {
try {
for (Order o : orders) {
o.Status = 'Shipped';
}
update orders;
// Simulate a later step that fails and forces a rollback.
if (orders.size() > 200) {
throw new ShipmentException('Too many orders in one request');
}
} catch (Exception e) {
// Published immediately, so it is not lost when the
// transaction rolls back after the exception is rethrown.
EventBus.publish(new Integration_Error__e(
Source__c = 'ShipmentService.markShipped',
Message__c = e.getMessage()
));
throw e;
}
}
}The throw e; ends the transaction with a rollback, and the order updates are undone. The error event stays published. A subscriber, such as a trigger that creates a log record in its own transaction, still receives it.
The risks of publishing immediately
Publish Immediately gives up the guarantees that Publish After Commit provides. Keep these points in mind:
- Subscribers may run before the commit. A subscriber that queries the data named in the event can find old values or no record at all.
- Events can describe things that never happened. If you publish "Order shipped" immediately and the transaction then rolls back, downstream systems have already acted on a false event. You cannot recall a published event.
- Retries can duplicate events. A failed transaction that is retried may publish the same event again.
Because of these risks, reserve this behavior for events that say something about the attempt, such as "this step failed," and not for events that claim a business fact.
Publish limits and bulk calls
The behavior does not change how you should call the API. Publish a list in one call so that Salesforce counts one publish operation instead of many:
List<Order_Shipped__e> events = new List<Order_Shipped__e>();
for (Order o : [SELECT OrderNumber FROM Order WHERE Status = 'Shipped' LIMIT 100]) {
events.add(new Order_Shipped__e(
Order_Number__c = o.OrderNumber,
Status__c = 'Shipped'
));
}
List<Database.SaveResult> results = EventBus.publish(events);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
System.debug('Publish failed: ' + sr.getErrors()[0].getMessage());
}
}EventBus.publish with a list returns one SaveResult per event, in the same order as the input. Check each one. A publish call can partially succeed.
A decision guide
Use these questions in order:
- Does the event claim that business data changed? If yes, choose Publish After Commit.
- Must the event survive a rollback of the work that raised it? If yes, choose Publish Immediately.
- Does a subscriber need to read committed data that the event refers to? If yes, choose Publish After Commit.
- Could a false event cause harm downstream, such as a charge or a shipment? If yes, choose Publish After Commit.
If you cannot decide, choose Publish After Commit. Its failure mode is a missing event after a failed transaction, which is easy to reason about. Publish Immediately fails with events that disagree with the data.
Common mistakes
- Using Publish Immediately for a business event "to be faster." The event is not delayed in a meaningful way by waiting for the commit, and you lose consistency.
- Expecting an error log event with Publish After Commit to appear after a failure. If the transaction rolls back, the log event is discarded with it.
- Treating
isSuccess()as delivery confirmation. It confirms that the platform accepted the publish request, not that the commit happened or that subscribers ran. - Testing only the success path. Include a test where the transaction fails, and check whether the event appears or not, depending on the behavior you chose.
Exercise
Your team defines a platform event named PaymentFailed_e that a billing class publishes inside a catch block, just before rethrowing the exception. The event uses Publish After Commit, and no subscriber ever sees it. Why, and what change fixes it?
Show answer
The rethrown exception rolls back the transaction, and Publish After Commit discards events from a transaction that does not commit. Change the event's publish behavior to Publish Immediately, so the event is published when the publish call runs and survives the rollback. Subscribers must not assume the related data is committed.
Exercise
A subscriber trigger for OrderShipped_e queries the Order record named in each event and sometimes finds the old status. The event uses Publish Immediately. What is the likely cause, and which behavior is the safer choice for this event?
Show answer
With Publish Immediately, the event can be delivered before the publishing transaction commits, so the subscriber reads data that is not yet committed or never will be. OrderShipped_e claims a committed business fact, so Publish After Commit is the safer choice. It guarantees the data is committed before any subscriber receives the event.