Sub topic 2
The event bus and publish/subscribe
This chapter explains the messaging layer that carries change events. It assumes you know basic Salesforce objects and records, can read simple Apex, and have a general idea of what a message queue or event system does. Later chapters cover enabling CDC, channel names, and subscribing in detail. Here the goal is the working model underneath them.
Why CDC runs on an event bus
When a record changes, other systems often need to know. A common approach is polling. The consumer queries Salesforce on a schedule, for example "give me accounts where LastModifiedDate is later than my last run." Polling has costs:
- It uses API calls even when nothing changed.
- It delays the consumer by up to one polling interval.
- It misses hard deletes unless you also query the recycle bin.
- It can only see the current state of a record, not the sequence of changes.
Change Data Capture avoids these costs by pushing messages instead. Salesforce publishes one message per change transaction to a shared message stream. Interested parties receive the message when it arrives. That stream is the event bus.
What the event bus is
The event bus is the Salesforce service that receives, stores, and delivers event messages. It follows the publish/subscribe (pub/sub) pattern, which has three roles:
- A publisher sends an event to the bus. It does not know who will receive it.
- A subscriber tells the bus which channel it wants. It does not know who published.
- A channel is a named stream of events. Subscribers listen to a channel, and publishers write to it.
This separation is called decoupling. You can add a second subscriber, such as a reporting service, without changing the publisher or the first subscriber. In point-to-point integration, by contrast, the sender must call each receiver, so every new receiver means a change to the sender.
For CDC, the publisher is the Salesforce platform. Your code does not publish change events. When a record of an enabled object is created, updated, deleted, or undeleted, the platform writes a change event to that object's channel.
Properties of the bus that shape your design
Events are published after commit
A change event is published only after the transaction that changed the record commits. If the transaction rolls back, no event is published. This means subscribers never see changes that did not happen. It also means the event arrives after the data is saved, so a subscriber that queries the record sees the committed state or a later one.
Delivery is asynchronous
The publisher does not wait for subscribers. The user's save completes first, and delivery happens separately. A slow or failing subscriber cannot make the original save fail or slow down. The trade-off is that subscribers work with eventual consistency. By the time your code reacts to an event, the record may have changed again. Write handlers that tolerate this. Use the values in the event, and query the record only when you need data the event does not carry.
Events have an order and an identifier
Each event on a channel gets a replay ID, an opaque number that increases as events are added. Subscribers receive events in replay ID order. The IDs are not guaranteed to be consecutive, so do not infer missing events from gaps in the numbers. Treat the replay ID as a bookmark, not a counter.
The bus stores events for a limited time
Unlike a simple notification system, the bus retains events. Change events are kept for 3 days (72 hours). A subscriber that disconnects can reconnect later and ask for events after its last replay ID, as long as that ID is still inside the retention window. This is what makes pub/sub usable for integrations that cannot be online all the time. The [replay chapter](#) covers the mechanics. For now, remember that retention is finite. A consumer that stays offline longer than the window loses events and must reconcile by other means.
Subscribers are independent
Each subscriber tracks its own position. One subscriber being behind does not affect another. An Apex trigger and an external client can both read the same event, each at its own pace.
Change events and platform events
CDC is built on the same bus as platform events, and the two are easy to confuse. The difference is who defines and publishes the message.
| Row | Change event | Platform event |
|---|---|---|
| Publisher | Salesforce, automatically | Your code, a flow, or an API client |
| Schema | Fixed by the object, plus `ChangeEventHeader` | You define the fields |
| Trigger | A record is created, updated, deleted, or undeleted | Whenever your code publishes |
| Channel | `/data/<Object>ChangeEvent` | `/event/<Name>__e` |
| Typical use | Mirror record changes to other systems | Signal a business occurrence |
Because both share the bus, they use the same subscriber tools: Apex triggers, lightning/empApi, CometD, and the Pub/Sub API. What you learn about subscribing to one carries over to the other.
Publishing a platform event shows the publisher side, which CDC performs for you. This example assumes a platform event named Order_Shipped__e with a text field Order_Number__c.
Order_Shipped__e shipped = new Order_Shipped__e(Order_Number__c = 'ORD-1001');
Database.SaveResult result = EventBus.publish(shipped);
if (!result.isSuccess()) {
for (Database.Error err : result.getErrors()) {
System.debug('Publish failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}With CDC you write none of this. The platform does the equivalent for you on every committed change to an enabled object.
What subscribing looks like
A subscriber connects to a channel and states where to start. There are three choices:
- Receive only new events from now on. The replay ID is
-1. - Receive all retained events. The replay ID is
-2. - Resume after a specific saved replay ID.
After that, the bus pushes events as they are published. A subscriber that wants reliable processing saves the replay ID of each event it has finished handling. After a restart, it resumes from the last saved ID instead of starting over or skipping ahead.
Apex triggers on change events are a special case. The platform stores and advances their position for you, so you do not manage replay IDs yourself.
Failure modes to expect
Thinking in terms of a bus gives you a checklist of what can go wrong:
- Subscriber offline too long. The retained events expire, and the subscriber cannot replay what it missed. Plan a reconciliation path, such as a query-based resync.
- Duplicate or repeated handling. After a reconnect or retry, a subscriber may process an event it already handled. Make handlers idempotent, meaning that processing the same event twice gives the same result as processing it once.
- Out-of-date reads. A handler that queries the record sees the current state, which may be newer than the event. Prefer data from the event itself.
- Burst load. Many changes in a short time produce many events. A subscriber that processes slowly falls behind. Because the bus is asynchronous, this lag shows up in the subscriber, not in the users who saved the records.
- Platform limits. Event publishing and delivery are subject to allocations, covered in a later chapter. Design with those limits in mind from the start.
Summary of the model
- Salesforce publishes change events to channels on the event bus after each committed change.
- Subscribers listen to channels. They do not call the publisher and do not affect it.
- Events are ordered by replay ID and retained for 3 days.
- Delivery is asynchronous, so subscribers work with eventually consistent data.
- Reliable consumers save their position, handle events idempotently, and have a plan for gaps.
Exercise
A teammate says they will replace their hourly polling job with a CDC subscriber. The subscriber service will be down for a four-day maintenance window. What problem will they hit when it comes back, and what should the design include to handle it?
Show answer
Change events are retained for only 3 days, so replay IDs from the start of the four-day window will have expired. The subscriber cannot recover every change by replaying from its last saved replay ID. The design needs a reconciliation step, such as a query-based resync of the affected records (for example by LastModifiedDate), run after outages longer than the retention window. Handlers should also be idempotent, so overlap between the resync and the resumed event stream does not cause errors.
Exercise
A record save is rolled back because a validation rule fails later in the same transaction. Will subscribers receive a change event for it? Why does this matter for your design?
Show answer
No. Change events are published only after the transaction commits, so a rolled-back save produces no event. Subscribers therefore see only changes that were actually saved, and they do not need logic to discard events for failed saves.