Sub topic 10
Gap and overflow events
Change events are normally a reliable stream of record changes. Sometimes Salesforce can't give you the full change event. In those cases it sends a gap event or an overflow event, and your integration must notice and recover.
This chapter assumes you know the ChangeEventHeader fields, how change types work, and how to write an Apex trigger on a change event or subscribe from an external client. It also assumes you know what a replay ID is.
Why the stream can have holes
A normal change event carries the changed field values, so a subscriber can apply it without calling back to Salesforce. That only works when Salesforce can build the event. Two situations prevent it:
- An internal error occurs while Salesforce generates the event for a change. Salesforce sends a gap event instead.
- A single transaction changes too many records of one object, more than 100,000 in the same transaction. Salesforce stops generating individual events and sends an overflow event.
In both cases the original data change still succeeded in the database. Only the notification is degraded. Your copy of the data is now possibly stale until you reconcile it.
Gap events
A gap event replaces a change event that Salesforce could not generate. It tells you which records were affected and what kind of change happened, but it does not tell you the new values.
The changeType in the header tells you the kind of change:
| changeType | Meaning |
|---|---|
| `GAP_CREATE` | Records were created, but the event could not be generated |
| `GAP_UPDATE` | Records were updated, but the event could not be generated |
| `GAP_DELETE` | Records were deleted, but the event could not be generated |
| `GAP_UNDELETE` | Records were undeleted, but the event could not be generated |
| `GAP_OVERFLOW` | More than 100,000 changes in one transaction for the entity |
A gap event has these properties:
recordIdslists the affected records, so you know exactly what to re-read.- The field values are missing. Only header metadata is present, and
changedFieldsis empty. You cannot tell which fields changed. - It keeps the same
entityName,commitTimestamp,commitUser, andtransactionKeyinformation as a normal event, so you can still order and trace it. - It arrives on the same channel as the normal events, for example
/data/AccountChangeEvent.
Because gap events arrive on the channel you already subscribe to, any consumer that assumes every message has field values will misbehave. A gap event for an update does not mean "nothing changed." It means "something changed and we can't say what."
Overflow events
An overflow event is a special gap event for large transactions. Suppose a data load or a batch job updates 250,000 accounts in one transaction. Salesforce sends individual events for the first 100,000 changes, then sends a single overflow event for that entity.
An overflow event differs from a regular gap event in these ways:
changeTypeisGAP_OVERFLOW.recordIdsis empty. You do not get a list of the affected records.- It is sent once per entity in the transaction, not once per record.
- The events before it in that transaction are normal. Only the changes after the 100,000 limit are unreported.
So an overflow event says "an unknown number of records of this entity changed in this transaction, and you can't tell which ones." The only safe recovery is to query for what changed.
The header's commitTimestamp marks when the transaction committed. Use it as the starting point for a "changed since" query.
The reconciliation pattern
Gap and overflow events share a recovery strategy: stop trusting your local copy for the affected data and re-read it from Salesforce.
Follow these rules when you reconcile:
- For
GAP_CREATE,GAP_UPDATE, andGAP_UNDELETE, query the listed IDs and overwrite your copy with what you find. - For
GAP_DELETE, treat the IDs as deleted. A query that returns nothing confirms it. - For
GAP_OVERFLOW, query the entity for records whereLastModifiedDateis at or after a time slightly before the commit timestamp. Subtract a safety margin because clocks and commit times can differ by a small amount. - Do not rely on
changedFields. It tells you nothing for gap events. - Make your reconciliation idempotent. Re-reading and overwriting the same record twice must be harmless.
Overflow recovery cannot find deleted records with a LastModifiedDate query, because deleted records no longer match. If your integration must propagate deletes, a full ID comparison or a query with ALL ROWS on the deleted records is needed.
Handling gap events in an Apex trigger
Here is a trigger that separates normal events from gap events and overflow events. It collects the IDs from gap events, notes whether any overflow occurred, and hands the work to a Queueable so the trigger stays light.
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
Set<Id> idsToReread = new Set<Id>();
Boolean overflowSeen = false;
Long earliestCommit = null;
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
if (header.changeType == 'GAP_OVERFLOW') {
overflowSeen = true;
if (earliestCommit == null || header.commitTimestamp < earliestCommit) {
earliestCommit = header.commitTimestamp;
}
} else if (header.changeType.startsWith('GAP_')) {
for (String recordId : header.recordIds) {
idsToReread.add((Id) recordId);
}
} else {
// Normal event: field values are present and can be used directly.
System.debug('Normal ' + header.changeType + ' for ' + header.recordIds);
}
}
if (overflowSeen || !idsToReread.isEmpty()) {
System.enqueueJob(new AccountReconciler(idsToReread, overflowSeen, earliestCommit));
}
}The Queueable does the actual re-read:
public class AccountReconciler implements Queueable {
private Set<Id> ids;
private Boolean fullEntity;
private Long sinceMillis;
public AccountReconciler(Set<Id> ids, Boolean fullEntity, Long sinceMillis) {
this.ids = ids;
this.fullEntity = fullEntity;
this.sinceMillis = sinceMillis;
}
public void execute(QueueableContext context) {
List<Account> accounts;
if (fullEntity) {
// Go back five minutes to allow for timing differences.
Datetime since = Datetime.newInstance(sinceMillis).addMinutes(-5);
accounts = [SELECT Id, Name, Phone, LastModifiedDate
FROM Account WHERE LastModifiedDate >= :since LIMIT 10000];
} else {
accounts = [SELECT Id, Name, Phone, LastModifiedDate
FROM Account WHERE Id IN :ids];
}
for (Account a : accounts) {
System.debug('Reconcile ' + a.Id + ' ' + a.Name);
}
}
}The System.debug call stands in for your real logic. In a real integration you would push these records to the downstream system.
The LIMIT 10000 in this example is a placeholder. After an overflow, the real number of affected records can be much larger than one query returns. In production, page through the results or use Batch Apex.
Handling gap events in an external subscriber
External clients receive the same events through CometD or the Pub/Sub API. The logic is the same: check the header first.
function classify(payload) {
const header = payload.ChangeEventHeader;
if (header.changeType === 'GAP_OVERFLOW') {
return { action: 'resync-entity', entity: header.entityName, since: header.commitTimestamp };
}
if (header.changeType.startsWith('GAP_')) {
return { action: 'reread-records', ids: header.recordIds };
}
return { action: 'apply', fields: payload };
}
const gap = {
ChangeEventHeader: {
entityName: 'Account',
changeType: 'GAP_UPDATE',
recordIds: ['001XXXXXXXXXXXXXXX'],
commitTimestamp: 1700000000000
}
};
console.log(classify(gap));Run this with Node.js and it prints { action: 'reread-records', ids: [ '001XXXXXXXXXXXXXXX' ] }.
Gaps you create yourself
Salesforce is not the only source of lost events. These cases look different but need the same recovery:
- Your subscriber was offline longer than the retention window (three days), so the events you missed are no longer available on replay.
- You stored a replay ID, but it is now older than the oldest retained event.
- Your consumer dropped messages because of a bug or a crash before checkpointing.
None of these produce a gap event. Salesforce does not warn you. Plan a full resynchronization for these cases, for example a bulk query of all records, followed by resuming from the latest replay ID.
Common mistakes
- Reading
changedFieldson a gap event and concluding nothing changed. - Casting
recordIds[0]without checking the list. An overflow event has an empty list. - Writing a trigger that handles only
CREATE,UPDATE,DELETE, andUNDELETE. Gap events then fall through silently. - Running the reconciliation query inside the trigger itself. Large queries and callouts there can hit limits, so enqueue the work.
- Ignoring overflow because "we never load that much data." One integration user running a data fix can trigger it.
Exercise
A nightly job updates 300,000 Account records in one transaction. Your subscriber receives normal Account change events, then one event with changeType GAP_OVERFLOW and an empty recordIds list. What happened, and how should the subscriber recover?
Show answer
Salesforce generated individual events for the first 100,000 changes, then stopped and sent a single overflow event for the Account entity. The remaining changes are not reported individually and the overflow event lists no IDs. The subscriber should query Account for records where LastModifiedDate is at or after the event's commitTimestamp (minus a small safety margin), paging through the results, and overwrite its local copy. If it must also track deletes, it needs a separate check, because deleted records do not appear in a LastModifiedDate query.