Sub topic 15
Integration design patterns and common pitfalls
This chapter assumes you can read a ChangeEventHeader, write an Apex trigger on a change event, and subscribe with empApi or the Pub/Sub API. It also assumes you know what replay IDs, gap events, and overflow events are. Here you combine those pieces into integration designs and learn the mistakes that most often break them.
When CDC fits, and when it does not
CDC is a good fit when an external system needs a near-real-time copy of Salesforce record changes, or when you want to react to changes without writing triggers on the standard object itself. It is a poor fit in these cases:
- You need a guaranteed, ordered, exactly-once transfer. CDC provides at-least-once delivery within a retention window.
- You need to react to a specific business moment, such as "order approved", that is not a field change. A platform event published from your own logic expresses that better.
- You need to veto or modify a save. Change events are published after commit, so they cannot block or alter the transaction.
| Need | Better choice |
|---|---|
| Mirror record data to another system | CDC |
| Notify on a business milestone | Platform event |
| Validate or block a save | Before-save trigger or validation rule |
| One-time bulk export or nightly full load | Bulk API |
Pattern 1: Subscribe, then reconcile
A CDC consumer is never the only source of truth for correctness. Retention is limited to 72 hours, and gap and overflow events can arrive. A resilient integration therefore has two paths: a streaming path for speed and a reconciliation path for repair.
Treat the change event as a signal that a record changed, and treat the Salesforce API as the authority on what the record looks like now. For gap events, the payload does not carry the field values. You must query the records.
Pattern 2: Store the replay ID after processing
Persist the replay ID only after your work for that event has succeeded. If you store it first and then crash, the event is lost to you. If you store it after, a crash replays the event, and your processing must tolerate that.
- Keep one replay ID per channel per subscriber.
- On startup, subscribe from the stored value. Use
-1only for a first run where history does not matter. - If the stored replay ID is older than the retention window, the platform cannot replay from it. Handle that error by falling back to
-1and running a full reconciliation.
Pattern 3: Make consumers idempotent
Because delivery is at-least-once and replay can resend events, applying the same event twice must be harmless. Two techniques work well:
- Upsert by Salesforce ID. Write the record keyed on its ID, not as a blind insert.
- Compare commit numbers. Store the highest
commitNumberyou applied for each record and ignore any event with a lower or equal value. This also protects against out-of-order delivery when several subscribers or retries are involved.
// Node.js sketch of an idempotent apply step
const applied = new Map(); // recordId -> highest commitNumber seen
function applyChange(header, fields) {
for (const recordId of header.recordIds) {
const last = applied.get(recordId) ?? 0;
if (header.commitNumber <= last) {
continue; // duplicate or stale event
}
applied.set(recordId, header.commitNumber);
console.log(`apply ${header.changeType} to ${recordId}`, fields);
}
}In production, keep this state in a database, not in memory, so it survives restarts.
Pattern 4: Avoid feedback loops
Two-way sync is the most common source of runaway traffic. The sequence looks like this:
- A user edits an Account in Salesforce.
- Your integration copies the edit to the external system.
- The external system writes the "change" back to Salesforce.
- Salesforce publishes another change event, and the cycle continues.
To break the loop, identify changes made by your own integration and skip them. The header gives you two handles:
commitUseris the ID of the user who made the change. If the integration uses a dedicated integration user, you can filter on it.changeOrigindescribes where the change came from. When an API client sets theclientvalue in theSforce-Call-Optionsrequest header, that value appears inchangeOrigin, so you can tag your own writes.
Also write back only when the value actually differs. A no-op update still takes a transaction in Salesforce, and depending on the fields touched it may still produce a change event.
Pattern 5: Hand heavy work to asynchronous Apex
A change event trigger runs in its own transaction as the Automated Process user, and it receives events in batches. Keep it light. Do the classification in the trigger, then enqueue a Queueable for callouts and longer logic. The trigger below skips integration-originated changes, collects records from gap events, and flags overflow for a full reconciliation.
trigger ContactChangeTrigger on ContactChangeEvent (after insert) {
Set<Id> changedIds = new Set<Id>();
Boolean fullReconcile = false;
for (ContactChangeEvent evt : Trigger.new) {
EventBus.ChangeEventHeader header = evt.ChangeEventHeader;
if (header.changeType == 'GAP_OVERFLOW') {
fullReconcile = true;
continue;
}
// Skip writes made by our own integration to avoid loops
if (header.changeOrigin != null &&
header.changeOrigin.contains('client=ExternalSync')) {
continue;
}
// Gap events and normal events both carry record IDs
for (String recordId : header.recordIds) {
changedIds.add(Id.valueOf(recordId));
}
}
if (fullReconcile || !changedIds.isEmpty()) {
System.enqueueJob(new ContactSyncJob(changedIds, fullReconcile));
}
}public class ContactSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> recordIds;
private Boolean fullReconcile;
public ContactSyncJob(Set<Id> recordIds, Boolean fullReconcile) {
this.recordIds = recordIds;
this.fullReconcile = fullReconcile;
}
public void execute(QueueableContext ctx) {
// Re-read current values; the event is only a signal.
List<Contact> current = [
SELECT Id, FirstName, LastName, Email
FROM Contact
WHERE Id IN :recordIds
];
// Send 'current' to the external system here.
// If fullReconcile is true, start a batch job that re-syncs all contacts.
System.debug('Syncing ' + current.size() + ' contacts');
}
}A trigger can ask the platform to redeliver a batch by throwing EventBus.RetryableException. Use this only for temporary conditions, such as a locked record. The platform limits retries, so a permanent error needs a different handling path, such as logging the failure for reconciliation.
Common pitfalls
Assuming the event holds the full record
An update event contains only changed fields plus the header. If your consumer needs the whole record, query it, or keep a local copy and merge the changes into it. Fields that did not change are absent from the payload, which is different from being null. Use changedFields in the header to tell "set to null" apart from "not touched".
Ignoring multi-record events
One event can cover several records in the same transaction when the changes are identical, and recordIds is a list. Code that reads only recordIds[0] silently drops the rest. Always loop over the list.
Relying on ordering across records
Events for one record arrive in commit order. You should not depend on any order between different records or different channels. Use transactionKey and sequenceNumber to group the events that came from one transaction, and use commitNumber to compare commits.
Forgetting field-level access
Subscribers receive only the fields their user can see, and the same goes for the Apex trigger user. When an external system shows missing fields, check the subscribing user's field-level security before you debug the code. Integration users should be granted exactly the fields the integration needs.
Exhausting allocations
Delivery to external clients counts against a daily allocation that depends on your edition and add-ons. Selecting many objects, or a busy object with many subscribers, can exhaust it. Reduce volume with custom channels and entity selection, enrich only the objects you need, and watch usage in Setup. Because limits vary by edition, check your org's current values before you size a design.
Treating tests as proof of delivery
Apex tests use Test.enableChangeDataCapture() and Test.getEventBus().deliver() to simulate delivery. They show that your trigger logic works. They do not prove that your external subscriber reconnects, resumes from its replay ID, or survives an overflow. Test those paths against a sandbox.
A design checklist
- Is there a reconciliation path for gap events, overflow events, and expired replay IDs?
- Is the replay ID saved only after successful processing?
- Does applying an event twice leave the same result?
- Can your own writes be recognized and skipped?
- Does the consumer loop over all
recordIds? - Does the subscribing user have field-level access to every needed field?
- Does expected daily event volume fit the allocation?
Exercise
Your two-way sync between Salesforce and an ERP system creates an endless stream of Account update events. Name the cause and two header-based ways to stop it.
Show answer
The integration writes ERP changes back to Salesforce, and each write produces a new change event, which is sent to the ERP again. To stop it, skip events whose commitUser is the dedicated integration user, or tag the integration's API calls with a client value in the Sforce-Call-Options header and skip events whose changeOrigin contains that value. You can also avoid writing back when the value is unchanged.
Exercise
A subscriber crashed for five days and restarts with its saved replay ID. What happens, and what should the design do?
Show answer
Change events are retained for 72 hours, so the saved replay ID is outside the retention window and the platform cannot replay from it. The subscriber should detect this error, resubscribe from -1 (new events only), and run a full reconciliation to recover the changes made while it was down.