Sub topic 1
How Publishers, the Event Bus, and Subscribers Fit Together
This chapter gives you the working model for Salesforce Platform Events. Later chapters cover defining events, publishing, subscribing, replay, testing, and limits. Here you learn the three roles, how a message travels between them, and the mistakes that most often trip up developers.
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax, including classes, triggers, and DML (data manipulation language, the statements that insert, update, and delete records).
- How Salesforce custom objects and fields work.
- Basic Lightning Web Components: JavaScript modules and lifecycle hooks such as
connectedCallback. - That Apex runs in transactions and is bound by governor limits.
You do not need to have created a platform event yet. The next chapter covers that.
What event-driven architecture means
In a request-and-response design, one piece of code calls another and waits for the answer. The caller must know who to call, and a failure in the callee usually breaks the caller.
In an event-driven design, the code that notices something happened only announces it. It does not know who, if anyone, will react. Other pieces of code listen for the announcement and act on it separately.
Salesforce Platform Events implement this model. Three roles take part:
- A publisher is code or a tool that sends an event message. Apex, flows, and external systems calling the REST API can all publish.
- The event bus is the Salesforce-managed channel that receives published events, stores them for a limited time, and delivers them to subscribers.
- A subscriber is code or a tool that listens to the channel and reacts. Apex triggers, platform event-triggered flows, Lightning Web Components, and external clients can all subscribe.
Publishers and subscribers never reference each other. Both reference only the event definition, such as Order_Shipped__e.
What a platform event is
A platform event is a message with a defined shape. You define it in Setup much like a custom object, with fields, and its API name ends in __e instead of __c. Example: Order_Shipped__e with fields Order_Number__c and Status__c.
A platform event differs from a custom object record in several ways that matter for design:
| Aspect | Custom object record | Platform event |
|---|---|---|
| Stored in the database | Yes, until deleted | No. Held on the event bus for a limited retention window |
| Can be queried with SOQL | Yes | No |
| Can be updated or deleted after creation | Yes | No. Events are immutable once published |
| Purpose | Hold business data | Announce that something happened |
| Rollback behavior | Rolled back with the transaction | Depends on the publish behavior you choose |
An event is a notification, not a record of truth. If you need the data later, the subscriber must store it, for example by creating a record.
How a message travels
Follow one event from start to finish.
- A publisher creates an event instance and publishes it. In Apex, that is a call to
EventBus.publish. - Salesforce validates the event and accepts it for publishing. The call returns a result that tells you whether the event was accepted.
- The event bus appends the event to the channel for that event type and assigns it a replay ID, an increasing number that marks the event's position in the channel.
- The bus delivers the event to each active subscriber. Delivery to each subscriber is independent of the others.
- Each subscriber processes the event in its own context. For an Apex trigger, that is a separate transaction from the publisher's.
The sequence below shows the interaction between one publisher and two subscribers.
A first look at the code
Here is a publisher in Apex. It creates one event and publishes it.
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 does not throw an exception when publishing fails. It returns a Database.SaveResult, and you must check isSuccess(). A successful result means Salesforce accepted the event for publishing. It does not mean any subscriber has processed it.
A subscriber in Apex is a trigger on the event object. It runs only on after insert, because events are only ever created.
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
List<Task> tasks = new List<Task>();
for (Order_Shipped__e evt : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
));
}
insert tasks;
}Trigger.new holds the delivered events, possibly many at once, so the trigger builds a list and runs one DML statement. This is the same bulk pattern you use in any trigger.
A Lightning Web Component can also subscribe, using the lightning/empApi module. The next section shows the one idea to take from it: the subscriber names the channel, and the channel name is built from the event's API name.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class OrderShippedListener extends LightningElement {
channelName = '/event/Order_Shipped__e';
subscription = null;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
subscribe(this.channelName, -1, (message) => {
const payload = message.data.payload;
console.log('Order shipped: ' + payload.Order_Number__c);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}The -1 is a replay ID that means "only events published after I subscribe." Replay IDs get their own chapter.
Properties of the model that shape your design
Decoupling
The publisher does not know its subscribers. You can add a second subscriber, such as a flow that emails a customer, without touching the publishing code. You can also publish with no subscribers at all, and nothing fails.
Asynchronous delivery
Subscribers run after the publisher, not inside its call stack. A publisher cannot read a subscriber's result, and a subscriber's error does not roll back the publisher's work. If a business rule requires "do this and that, or neither," a platform event is the wrong tool, because the two halves are in separate transactions.
Fan-out
Every subscriber to a channel receives each event. This differs from a work queue, where each message goes to one worker. If two triggers and a flow subscribe, each event is processed three times, once by each.
Ordering
Events on one channel carry increasing replay IDs, and delivery to a subscriber follows that order. Do not assume ordering across different event types. Do not assume your business logic is correct if it depends on one event type arriving before another.
Separate transactions and limits
An event trigger runs in its own transaction, with its own governor limits. It is not bound by the publisher's limits. The publisher, however, does consume limits for the act of publishing, and the platform also enforces allocations on publishing and delivery. A later chapter covers these.
Limited retention
The bus keeps events for a fixed window, not forever. A subscriber that was offline longer than the window cannot recover what it missed. Subscribers that must not lose events need a plan for this, which is why replay IDs and retention come up again later.
Common errors
- Treating a successful publish as a completed job.
isSuccess()means the bus accepted the event. The work in the subscriber has not necessarily run, and it may still fail. - Ignoring the
SaveResult. Publishing failures, such as a missing required field, come back as errors in the result, not as exceptions. If you never check, you lose events silently. - Querying events like records. There is no SOQL access to platform events. Store what you need from the event in a record when the subscriber runs.
- Writing trigger logic that assumes one event at a time.
Trigger.newcan hold a batch of events. Loop over it and do DML outside the loop. - Expecting the publisher to wait. Do not write publisher code that assumes subscribers have finished. A test, for example, must force delivery explicitly, as the testing chapter shows.
- Using an event where a direct call is simpler. If one class needs the result of another class immediately, call it directly. Events add indirection and a second transaction.
Where the rest of the tutorial goes
The chapters that follow fill in each part of the picture you just saw.
- Define the event and its fields.
- Choose when an event is released relative to the publisher's transaction.
- Publish from Apex, flows, and the REST API.
- Subscribe with triggers, flows, and Lightning Web Components.
- Use replay IDs and retries to recover from gaps and failures.
- Test, monitor, and decide when to use a different tool.
Exercise
A publisher calls EventBus.publish and the returned SaveResult has isSuccess() equal to true. A teammate says, "So the Task records from the subscriber trigger now exist." Is that conclusion correct? Explain what isSuccess() does tell you, and name one reason the Tasks might still be missing.
Show answer
The conclusion is not correct. isSuccess() being true means Salesforce accepted the event for publishing on the event bus. It says nothing about whether any subscriber has run or finished. Delivery is asynchronous, and the trigger runs in its own transaction later. The Tasks might be missing because the trigger has not run yet, or because the trigger threw an error such as a validation failure or a governor limit exception while inserting the Tasks. The publisher does not see that error.
Exercise
Two Apex triggers and one platform event-triggered flow subscribe to OrderShipped_e. The publisher publishes 5 events. How many times is each event processed, and what does that tell you about the difference between an event channel and a work queue?
Show answer
Each event is delivered to every subscriber, so each of the 5 events is processed three times: once by each trigger and once by the flow. That makes 15 processing runs in total. This is fan-out. In a work queue, each message goes to only one worker. On an event channel, every subscriber receives every event, so logic in different subscribers must not duplicate the same side effect.
Exercise
A requirement says: "When an order is marked shipped, update the order and create a shipping record. If either step fails, neither must be saved." Would you split the second step into a platform event subscriber? Why or why not?
Show answer
No. The requirement is all-or-nothing, which needs one transaction. A platform event subscriber runs in a separate transaction after the publisher, so a failure in the subscriber would not roll back the order update, and the two could end up inconsistent. Do both steps in the same transaction instead. Use a platform event only when the second step may be handled separately and asynchronously, and when a failure there should not undo the first.