Sub topic 12
Event-driven integration with Platform Events, CDC, and Pub/Sub API
The REST and Bulk APIs are request-driven. A client asks Salesforce for data and gets an answer. Event-driven integration reverses this: Salesforce, or another system, announces that something happened, and any interested subscriber receives the message. This chapter covers the two event types (Platform Events and Change Data Capture), the delivery mechanisms, and how to pick between them.
It assumes you can already get an access token (see the authentication chapter) and can send REST calls with curl. Basic Apex reading skills help for the trigger examples.
Why events instead of polling
An integration that needs to know when an Account changes could query the REST API every minute. That approach has three costs:
- Most polls return nothing, yet each one counts against your API request allocation.
- Changes arrive up to one polling interval late.
- You must track "last seen" timestamps yourself and handle clock and ordering problems.
With events, Salesforce pushes the change to subscribers shortly after it commits. Producers and consumers also stay decoupled. The publisher does not know who is listening, and new subscribers can be added without touching it.
The event bus and its two main event types
Salesforce events travel over an event bus. Each event is published to a channel, and subscribers listen to that channel. The bus stores events temporarily, so a subscriber that disconnects can catch up. Every event gets a replay ID, an increasing identifier that marks its position in the stream.
The two event types differ in who defines the message.
| Row | Platform Events | Change Data Capture (CDC) |
|---|---|---|
| Who defines the payload | You, as a custom object ending in `__e` | Salesforce, generated from an object's fields |
| What triggers it | Something you publish (Apex, Flow, API) | A record is created, updated, deleted, or undeleted |
| Channel name | `/event/Order_Event__e` | `/data/AccountChangeEvent` |
| Best for | Business signals ("order shipped") | Replicating data changes to another system |
Both channels are retained for a limited window, commonly 72 hours (three days). Check the current limits for your edition and event type, because allocations for published and delivered events vary.
Platform Events
A platform event is a custom message you design. You create it in Setup much like a custom object. Fields use the usual __c suffix, and the event itself ends in __e. Assume an event named Order_Event__e with two text fields, Order_Number__c and Status__c.
Publishing
Publishing an event is an insert into the event object. From outside Salesforce, use the REST API's sobjects resource:
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Order_Event__e" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Order_Number__c": "1001", "Status__c": "Shipped"}'The response contains an id and "success": true. A success response means the bus accepted the event. It does not mean any subscriber has processed it. Inside Salesforce, Apex calls EventBus.publish(), and Flow has a "Create Records" action that works on event objects.
Platform events are not saved as normal records. You cannot query them with SOQL as you would an Account, and you cannot update or delete them once published.
Subscribing inside Salesforce
An Apex trigger on the event object runs after the event is delivered. Platform event triggers support only after insert.
trigger OrderEventTrigger on Order_Event__e (after insert) {
for (Order_Event__e evt : Trigger.new) {
System.debug('Order ' + evt.Order_Number__c + ' is ' + evt.Status__c
+ ' (replay ID ' + evt.ReplayId + ')');
}
}This trigger runs in its own transaction, separate from the one that published the event. Publish behavior also matters: an event can be configured to publish immediately or after the publishing transaction commits. If you publish immediately and the transaction then rolls back, subscribers still receive the event. For events that describe committed business facts, publish after commit.
Change Data Capture
CDC removes the need to publish anything. When you enable an object for change events, Salesforce emits a message for every create, update, delete, and undelete, with no code on the publishing side. This suits keeping a data warehouse, search index, or external database in sync.
Each change event has two parts:
- A
ChangeEventHeaderwith metadata:entityName,recordIds,changeType,changedFields,commitTimestamp,transactionKey, andchangeOrigin. - The field values. For an update, only the fields that changed are included. For a create, all populated fields are included.
Because updates are partial, a subscriber cannot rebuild the full record from one message. It must apply changes to a copy it already holds, or query the record using the IDs in the header.
You can subscribe from Apex too:
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
for (AccountChangeEvent change : Trigger.new) {
EventBus.ChangeEventHeader header = change.ChangeEventHeader;
if (header.getChangeType() == 'UPDATE'
&& header.getChangedFields().contains('Industry')) {
System.debug('Industry changed on ' + header.getRecordIds());
}
}
}Gap and overflow events
Sometimes Salesforce cannot generate a full change event, for example after an internal error. It then sends a gap event, with a changeType such as GAP_UPDATE, to say that changes were missed for those records. A subscriber that ignores gap events silently drifts out of sync. On a gap event, fetch the current state of the listed records with the REST API. Very large changes can produce an overflow event, which lists the record but omits the field data.
Channel choice
The channel /data/ChangeEvents carries changes for every enabled object. A channel such as /data/AccountChangeEvent carries one object. Use a per-object channel unless you truly want everything, because a single busy object can dominate the shared stream and use up your delivery allocation.
Pub/Sub API
Pub/Sub API is the recommended way for external systems to publish and subscribe to events. It is a gRPC API, which runs over HTTP/2 and uses Protocol Buffers for the call structure. Event payloads are encoded in Apache Avro, a compact binary format. The service address is api.pubsub.salesforce.com:7443.
Key points:
- One API, both directions. It handles platform events, change events, and real-time event monitoring events, and it supports publishing as well as subscribing.
- Authentication through metadata headers. Each call carries
accesstoken,instanceurl, andtenantidheaders. You obtain the token with the OAuth flows from the authentication chapter. - Flow control. The client says how many events it can handle (
num_requestedin aFetchRequest) and the server sends no more than that. This prevents a slow consumer from being flooded. - Replay. A subscription starts from the latest event, the earliest retained event, or a specific replay ID. Storing the last replay ID you processed lets you resume after a crash.
- Schema fetching. Because Avro payloads cannot be read without their schema, the client calls
GetTopicandGetSchema. It then decodes each event with the schema ID in the message.
You generate client stubs from Salesforce's published .proto file. Salesforce maintains example clients in several languages.
The older Streaming API
Earlier integrations used CometD, a long-polling protocol, through the Streaming API. It still works and you will meet it in existing code. For new work, prefer Pub/Sub API, which has better throughput, flow control, and a binary encoding.
Delivery guarantees and design rules
Event delivery is at least once. Design every subscriber to be safe if it sees the same event twice.
- Make handlers idempotent. Use a stable key from the event, such as the replay ID or the
transactionKey, to detect duplicates. - Persist the replay ID after processing, not before. If you save it first and crash mid-processing, you lose the event.
- Act within the retention window. If a consumer is down for longer than the retention period, the replay ID expires. Plan a full resync with the Bulk or REST API as a fallback.
- Keep events small. Put identifiers and status in the event, and let the subscriber fetch details through REST if needed.
- Watch allocations. Both published and delivered event counts are limited, and every external subscriber counts toward delivery.
- Do not assume ordering across channels. Order is preserved by replay ID within one channel only.
Choosing between them
- To tell another system that a business step happened, use a platform event and publish it yourself.
- To mirror record changes into another database, use CDC.
- To connect an external service to either one, use Pub/Sub API. Use Apex triggers or Flow for subscribers inside Salesforce.
- If you need to look up current record data on demand, events are the wrong tool. Use REST or GraphQL.
- If you need to load millions of records, events are also the wrong tool. Use Bulk API 2.0.
Exercise
An external data warehouse must stay in sync with Salesforce Contact records. It was offline for five days, longer than the event retention window. What should the integration do on reconnecting, and why is storing a replay ID not enough?
Show answer
The stored replay ID has expired because the events are no longer retained, so replay cannot recover the missed changes. The integration should do a full resync of the Contact data, for example with a Bulk API 2.0 query job or REST queries. After that it resumes the CDC subscription from the latest event, or from a fresh replay ID, to receive new changes.
Exercise
A CDC update event for an Account arrives with only the fields Industry and Rating. A subscriber needs the Account's Name. How can it get it, and which header values help?
Show answer
Update change events include only the fields that changed, so Name is absent. The subscriber reads the Account ID from the header's recordIds and queries the record with the REST API or SOQL. Alternatively, it applies the change to a local copy that already holds the Name.
Exercise
A platform event published immediately from Apex reached subscribers, but the publishing transaction later rolled back and the order was never saved. What setting would have avoided this?
Show answer
Configure the event to publish after the transaction commits. Then the event is sent only if the publishing transaction succeeds, so subscribers never see an event for data that was rolled back.