Sub topic 6
Fire-and-forget: publishing events without waiting
This chapter assumes you know Apex basics and triggers, the Salesforce data model, and HTTP and JSON. It also assumes you have read the earlier chapters on synchronous versus asynchronous communication and on the Salesforce integration toolbox. Here you will see how fire-and-forget works with platform events, what the publisher is told and what it isn't, and where this pattern fails.
What fire-and-forget means
In fire-and-forget, the sender hands a message to a channel and moves on. It does not wait for the receiver to process the message, and it does not receive a business answer. Request-reply is the opposite. There the caller blocks until the other system responds.
The pattern fits when:
- The sender does not need a result to continue its own work.
- Several systems may care about the same fact.
- The receiving system may be slow or temporarily offline.
- You want the sender and receivers to change independently.
Shipping a package is a typical case. The order system announces "order 00123 shipped". A billing system, a customer notification service, and a data warehouse can each react. The order system does not know or care how many of them exist.
Platform events as the Salesforce mechanism
The main Salesforce feature for this pattern is the platform event. A platform event is a custom message type you define in setup. Its API name ends in __e, such as Order_Shipped__e. It has fields like a custom object, but it differs from a record in important ways:
- Events are published to an event bus, not saved in a normal table. You cannot query them with SOQL as you would an Account.
- Events are immutable. You cannot update or delete one after publishing.
- Events are retained on the bus for a limited time. For high-volume platform events this is 72 hours, and subscribers can replay events inside that window.
- Delivery is at-least-once. A subscriber can receive the same event more than once.
Publishers and subscribers can be inside Salesforce or outside it.
| Role | Inside Salesforce | Outside Salesforce |
|---|---|---|
| Publisher | Apex (`EventBus.publish`), Flow, Process Builder | REST API insert into `/sobjects/Order_Shipped__e`, Pub/Sub API |
| Subscriber | Apex trigger on the event, Flow, Lightning component | Pub/Sub API (gRPC), CometD/Streaming API client |
Change Data Capture (CDC) uses the same event bus. Salesforce publishes a change event whenever a record is created, updated, deleted, or undeleted. Use CDC when you want to broadcast data changes without writing publishing code. Use platform events when you want to announce a business fact that you define yourself.
The message flow
The sequence below shows an Apex publisher, the event bus, an Apex trigger subscriber, and an external subscriber.
The SaveResult returned to the publisher comes before any subscriber runs. That timing is what makes the pattern asynchronous.
Publishing from Apex
Here is the publish call from the plan. It builds an event, publishes it, and checks the result.
Order_Shipped__e evt = new Order_Shipped__e(
Order_Number__c = '00123',
Carrier__c = 'ACME'
);
Database.SaveResult result = EventBus.publish(evt);
if (!result.isSuccess()) {
for (Database.Error err : result.getErrors()) {
System.debug(LoggingLevel.ERROR, 'Publish failed: ' + err.getMessage());
}
}isSuccess() is true when Salesforce accepted the event for publishing. It does not mean any subscriber received or processed the event. If you need proof of processing, the subscriber has to report it some other way, for example by writing a record or calling back. That is a design choice, and it moves you toward request-reply.
Publish in bulk
EventBus.publish also accepts a list. Publishing a list in one call is better than calling it in a loop. Each call counts as a DML statement against the Apex governor limits, so a loop over many records can hit the limit.
List<Order_Shipped__e> events = new List<Order_Shipped__e>();
for (Order o : shippedOrders) {
events.add(new Order_Shipped__e(
Order_Number__c = o.OrderNumber,
Carrier__c = o.Carrier__c
));
}
List<Database.SaveResult> results = EventBus.publish(events);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug(LoggingLevel.ERROR,
'Event for ' + events[i].Order_Number__c + ' failed: '
+ results[i].getErrors()[0].getMessage());
}
}Results come back in the same order as the input list. This is why the index i lines up with events[i]. Some events in a list can succeed while others fail, so check each result.
Publish behavior and transactions
When an event is published from a transaction that also changes records, you must decide what happens if the transaction rolls back. The event definition has a Publish Behavior setting.
| Setting | When the event is published | If the transaction rolls back | Typical use |
|---|---|---|---|
| Publish After Commit | After the transaction commits | The event is not published | A subscriber that reads the saved records |
| Publish Immediately | As soon as the publish call runs | The event is still published | Logging or error events that must survive a rollback |
Publish After Commit is the safer default. A subscriber that receives "order shipped" can trust that the shipped status is already saved. With Publish Immediately, a subscriber might act on a change that never happened.
Subscribing with an Apex trigger
A platform event trigger runs after the event is delivered. Only after insert is supported. The trigger runs asynchronously, in its own transaction, as the Automated Process user. It does not run as the user who published the event. Sharing and permission assumptions you made in the publisher do not carry over.
The trigger below writes one log record per event. It assumes a custom object Shipment_Log__c with fields Order_Number__c, Carrier__c, and a unique external ID field Event_Uuid__c. It uses the built-in EventUuid field, which is unique per event, to avoid duplicates.
trigger OrderShippedSubscriber on Order_Shipped__e (after insert) {
List<Shipment_Log__c> logs = new List<Shipment_Log__c>();
for (Order_Shipped__e e : Trigger.new) {
logs.add(new Shipment_Log__c(
Event_Uuid__c = e.EventUuid,
Order_Number__c = e.Order_Number__c,
Carrier__c = e.Carrier__c
));
}
List<Database.UpsertResult> results =
Database.upsert(logs, Shipment_Log__c.Event_Uuid__c, false);
for (Database.UpsertResult r : results) {
if (!r.isSuccess()) {
// A transient failure: ask the bus to redeliver this batch.
throw new EventBus.RetryableException(
'Upsert failed: ' + r.getErrors()[0].getMessage());
}
}
}Three points about this trigger:
- Batches.
Trigger.newcan hold many events, up to 2,000 per batch. Write the trigger for lists, as with any trigger. - Idempotency. Upserting by
Event_Uuid__cmeans a redelivered event updates the same record. It does not create a second one. The next chapters on external IDs go deeper on this. - Retries. Throwing
EventBus.RetryableExceptionmakes Salesforce redeliver the batch later. The retry count is capped, at up to 9 retries. After that, the batch is dropped from this trigger's point of view. Use retries only for transient problems such as a record lock. A permanent data error will fail on every attempt.
External subscribers and replay
An external system subscribes through the Pub/Sub API (gRPC) or the older CometD Streaming API. Each event carries a replay ID, a number that grows with each published event. The subscriber should store the replay ID of the last event it fully processed. After a restart, it asks the bus to resume from that ID and receives what it missed.
Replay has limits:
- It works only inside the retention window (72 hours for high-volume events).
- If the subscriber was down longer than that, the missed events are gone. It then needs a catch-up path, such as a Bulk API query or a full resync, as described in the batch sync chapter.
- A subscriber should commit the replay ID only after it has processed the event. If it commits first and then crashes, that event is lost to it.
Publishing from outside Salesforce
An external system can also act as the publisher. It inserts the event through the REST API, as it would create a record, by sending POST /services/data/v60.0/sobjects/Order_Shipped__e with a JSON body. It uses an OAuth access token, covered in the authentication chapter. The response says whether Salesforce accepted the event. As with Apex, acceptance is not processing.
Failure modes to design for
Fire-and-forget moves failure from the publisher's call stack to other places. Plan for each one.
- Silent publish failures. If you ignore the
SaveResult, rejected events vanish. Always check it, and log failures with enough data to rebuild the event. - Duplicate delivery. At-least-once delivery means subscribers must tolerate repeats. Make handlers idempotent.
- Out-of-order processing. Events are ordered by replay ID on the bus, but retries and parallel consumers can break the effective order. Do not depend on arrival order for correctness. Carry a timestamp or version in the payload and compare it.
- Subscriber lag. A slow subscriber falls behind. If it falls behind more than the retention window, it loses events.
- Allocation limits. Salesforce limits how many events you can publish per hour and how many an org can deliver to external subscribers per day. The numbers depend on edition and add-on licenses. Check the current figures in your org's limits before sizing a design.
- Payload size. An event carries only the fields you define. Keep it small. Put identifiers and the facts that changed in the event, and let the subscriber fetch more data if it needs it.
When this pattern is the wrong choice
Choose another pattern when:
- The caller needs a value back to continue, such as a price quote or validation result. Use request-reply.
- You must move hundreds of thousands of records at once. Use Bulk API 2.0.
- The business requires proof, in the same transaction, that the other system took the action. A fire-and-forget event cannot give that.
Summary
A publisher sends an event and continues. EventBus.publish tells you Salesforce accepted the event, not that anyone processed it. Choose Publish After Commit unless you need events to survive a rollback. Subscribers run in separate transactions, can see duplicates, and need idempotent logic. External subscribers use replay IDs to recover from downtime, within the retention window.
Exercise
An Apex method updates an Order to "Shipped" and then publishes an OrderShipped_e event with Publish After Commit. A validation rule later in the same transaction fails and the transaction rolls back. Does a subscriber receive the event? What would you change if the business needed the event sent anyway, and what new risk would that add?
Show answer
No. With Publish After Commit, the event is published only if the transaction commits, so a rollback means no event is sent. To send it anyway, set the event to Publish Immediately (or publish from a separate transaction). The new risk is that subscribers may act on a shipment that was never saved, so they must not assume the Order record shows "Shipped".
Exercise
Your Apex trigger subscriber receives the same OrderShippede event twice and creates two ShipmentLog__c records. Name the cause and give a fix.
Show answer
Platform events use at-least-once delivery, so redelivery is expected, and the trigger inserted a new record each time. Fix it by making the handler idempotent: upsert ShipmentLogc on an external ID field (such as EventUuid__c populated from the event's EventUuid) so a repeat updates the existing record instead of creating a new one.