# How do Apex developers publish Platform Event messages programmatically using the EventBus class?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Platform Events, Apex Publishing

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-apex-developers-publish-platform-event-messages-programmatically-using-the-eventbus-class

## Answer

**Basics:** Platform events are messages on a Salesforce event bus. The publisher creates an instance of the event type (an sObject whose API name ends in `__e`) and publishes it, and any subscribed Apex trigger, Flow, LWC or external client receives it. Publishing is a fire-and-forget step, so the publisher does not wait for subscribers.

**How it works:**
1. Define the event (Setup > Platform Events), with its fields and its Publish Behavior.
2. Build instances in Apex with `new Order_Event__e(...)`.
3. Call `EventBus.publish(list)`. Each element returns a `SaveResult`.
4. Check `isSuccess()` and read `getErrors()` for problems such as a missing required field.
5. The bus stores the event and delivers it to subscribers asynchronously.

**Advanced / deep dive:** Publishing counts as one DML statement per call, so batch events into a list. It also counts against the hourly event publishing allocation for the org (verify the current figure for your edition). Publish Behavior decides whether the event goes out immediately or only after the transaction commits. A successful result for an after-commit event only means it is queued until the commit. Publishing is also possible through REST, Pub/Sub API and Flow (Create Records on an event object). In tests, publish between `Test.startTest()` and `Test.stopTest()` and call `Test.getEventBus().deliver()` to force delivery.

**Code / config example:**
```apex
public with sharing class OrderEventPublisher {
    public static void publish(List<Order> orders) {
        List<Order_Event__e> events = new List<Order_Event__e>();
        for (Order o : orders) {
            events.add(new Order_Event__e(Order_Id__c = o.Id, Status__c = o.Status));
        }
        // One DML statement for the whole list
        List<Database.SaveResult> results = EventBus.publish(events);
        for (Database.SaveResult sr : results) {
            if (!sr.isSuccess()) {
                for (Database.Error err : sr.getErrors()) {
                    System.debug(LoggingLevel.ERROR, err.getStatusCode() + ': ' + err.getMessage());
                }
            }
        }
    }
}
```

**Hidden gotchas & must-remember points:**
- A failed publish does not throw an exception. You must inspect the results.
- Events are not stored in the database, so you cannot query them with SOQL as normal records.
- Publish After Commit events vanish if the transaction rolls back.
- Event messages have a size limit (about 1 MB) and a field count limit. Verify current numbers.
- Subscribers run in their own transaction, so they cannot roll back the publisher.
- Events cannot be updated or deleted once published.

**Best practice:** Publish in bulk, check every SaveResult, and include an idempotency key so subscribers can handle duplicates.

---
Source: ForceChallenges · last updated 2026-11-02
