# What is the operational difference between Publish After Commit and Publish Immediately settings for Platform Events?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Publish Behaviors, Transaction Consistency

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-the-operational-difference-between-publish-after-commit-and-publish-immediately-settings-for-platform

## Answer

**Basics:** Each platform event definition has a Publish Behavior setting. After Commit is the default, and it protects consistency, since subscribers never hear about changes that did not happen. Immediately is useful when the message must be delivered even if the transaction rolls back, such as error or audit logging.

**How it works:**
1. Apex or Flow calls `EventBus.publish`.
2. With After Commit, the event waits. If the transaction commits, it is published. If it rolls back, it is dropped.
3. With Immediately, the event goes to the bus at once. The later fate of the transaction does not matter.
4. Subscribers then receive it asynchronously in either case.

**Advanced / deep dive:** The race condition matters most. If an event publishes immediately and the subscriber looks up the record before the publisher's commit, the record may not exist yet, or may have old values. After Commit avoids this. Use Immediately for:
- logging failures from a transaction you expect to roll back,
- progress or telemetry events,
- signals unrelated to database changes.

Also note that for a failed transaction the SaveResult of an After Commit event is already "success" when the call returns, because it only indicates the event was queued. The behavior is configured on the event definition, so a given event type has one behavior for all publishers (verify whether your release allows per-call overrides).

**Code / config example:**
```text
Setup > Platform Events > <Event> > Publish Behavior
  Publish After Commit   -> default; rollback-safe, consistent
  Publish Immediately    -> fires at once; use for logging and rollback-proof messages
```
```apex
Savepoint sp = Database.setSavepoint();
insert acc;
EventBus.publish(new Error_Log__e(Message__c = 'about to roll back'));
Database.rollback(sp);   // Immediately: event still sent. After Commit: event discarded.
```

**Hidden gotchas & must-remember points:**
- The default is Publish After Commit.
- Rolled-back After Commit events are lost silently, with no error.
- Immediately events can reference data that does not exist after a rollback.
- Changing publish behavior later affects existing publishers, so test them.
- Tests with `Test.stopTest()` deliver events, and rollback behavior can be confusing to test.
- Choose by the question "Should subscribers act if the DML fails?"

**Best practice:** Keep After Commit for business events and use Immediately only for diagnostics.

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