Sub topic 7
Reacting to changes with Apex triggers
An Apex trigger on a change event lets Salesforce code react to record changes without touching the original object's triggers. This chapter assumes you know basic Apex triggers and DML, can read the ChangeEventHeader described in the previous chapter, and know how channel names work. By the end you can write a change event trigger, avoid its common errors, and explain how it differs from a trigger on the object itself.
How a change event trigger differs from an object trigger
A trigger on Account runs inside the transaction that saves the record. A trigger on AccountChangeEvent runs later, in its own transaction, after the original transaction commits. The two never share a transaction.
This has practical effects:
- A failure in the change event trigger does not roll back the original save. The user's update has already succeeded.
- The trigger runs as the Automated Process user, not as the user who made the change. The header's
commitUserfield tells you who made it. - Delivery is asynchronous. The delay is usually short, but you must not write code that expects the result to exist right after the original DML.
- You cannot block or validate a change. Use
beforetriggers or validation rules on the object for that.
| Aspect | Trigger on `Account` | Trigger on `AccountChangeEvent` |
|---|---|---|
| Runs in | Same transaction as the save | Separate transaction after commit |
| Timing events | `before` and `after` | `after insert` only |
| Can roll back the save | Yes | No |
| Runs as | The user making the change | Automated Process user |
| Record data | Full record in `Trigger.new` | Header plus changed fields only |
The diagram below is the sequence in the table's first rows, shown in order.
The trigger skeleton
The trigger name is arbitrary, but the sObject is the change event type. For a standard object, add ChangeEvent to the API name, as in AccountChangeEvent. For a custom object Invoice__c, use Invoice__ChangeEvent.
Only after insert is supported. Publishing a change event is an insert into the event bus, and events cannot be edited or deleted, so no other timing exists.
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
List<Task> followUps = new List<Task>();
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
if (header.changeType == 'UPDATE' && header.changedFields.contains('Phone')) {
for (String recordId : header.recordIds) {
followUps.add(new Task(
Subject = 'Verify updated phone number',
WhatId = recordId
));
}
}
}
if (!followUps.isEmpty()) {
insert followUps;
}
}The trigger does four things worth noticing:
- It reads
event.ChangeEventHeader, a typedEventBus.ChangeEventHeaderobject, rather than parsing JSON. - It filters on
changeTypefirst, then onchangedFields, so it ignores updates that touched other fields. - It loops over
recordIdsbecause one event can describe several records. - It collects new records in a list and runs one DML statement after the loop.
Reading the header in code
The header properties you use most often are:
| Property | Type | Use |
|---|---|---|
| `entityName` | String | Object API name, useful when one trigger code path serves several objects |
| `recordIds` | List of String | IDs of the affected records |
| `changeType` | String | `CREATE`, `UPDATE`, `DELETE`, `UNDELETE`, or a gap or overflow type |
| `changedFields` | List of String | Names of fields that changed on an update |
| `commitUser` | String | ID of the user who made the change |
| `changeOrigin` | String | The API or client that made the change |
| `transactionKey` | String | Groups events from the same original transaction |
| `sequenceNumber` | Integer | Position of the event within that transaction |
Two details cause frequent confusion.
First, changedFields lists only fields that changed on UPDATE. For a CREATE, the event carries all populated fields, and you read them directly from the event, for example event.Name. For a DELETE, the record's data is gone, so only the header and a few system fields are available.
Second, a field not in the event is null when you read it in Apex, whether it was empty or merely unchanged. The event does not distinguish them. If you must know whether Phone changed, check header.changedFields, not event.Phone == null.
Batches and multiple records
One trigger invocation receives a list of events, up to 2,000 in a batch. Treat Trigger.new as a bulk list, as you would in any trigger. Two kinds of bulk behavior apply here.
Many events in one invocation. Collect data across the loop, run SOQL once before it if you need related data, and run DML once after it.
Many records in one event. When a single transaction changes several records of the same type in the same way, Salesforce can merge them into one event. This is why recordIds is a list. The Apex example iterates it instead of reading recordIds[0]. Code that reads only the first ID silently ignores the others.
An example that queries related data safely, by collecting IDs first:
trigger ContactChangeTrigger on ContactChangeEvent (after insert) {
Set<Id> contactIds = new Set<Id>();
for (ContactChangeEvent event : Trigger.new) {
if (event.ChangeEventHeader.changeType == 'CREATE') {
for (String recordId : event.ChangeEventHeader.recordIds) {
contactIds.add(recordId);
}
}
}
if (contactIds.isEmpty()) {
return;
}
List<Contact> contacts = [
SELECT Id, Email, Account.OwnerId
FROM Contact
WHERE Id IN :contactIds
];
List<Task> tasks = new List<Task>();
for (Contact c : contacts) {
tasks.add(new Task(
Subject = 'Welcome call',
WhatId = c.AccountId,
WhoId = c.Id,
OwnerId = c.Account.OwnerId
));
}
insert tasks;
}Querying the record is useful when the event does not contain the field you need, but remember that the query returns the current state, which may be newer than the event. If order matters, rely on the event's data and the commit number rather than assuming the two agree.
Avoiding loops
A change event trigger that updates the same object produces another change event. That event runs the trigger again, which can loop until the trigger hits an event or DML limit.
Safeguards:
- Filter narrowly. Act only on the specific fields and change types you need, as the first example does with
Phone. - Skip changes you caused. Compare
header.commitUserto the Automated Process user's ID, or checkchangeOrigin, and return early. - Write to a different object when you can, such as a
Taskor a custom log record.
Error handling and retries
If an unhandled exception occurs, the platform does not roll back the original change. It retries the trigger with the same batch of events. Retries use EventBus.RetryableException.
trigger OrderChangeTrigger on Order__ChangeEvent (after insert) {
try {
// processing that might hit a temporary lock
} catch (DmlException e) {
throw new EventBus.RetryableException('Retrying: ' + e.getMessage());
}
}Keep these rules in mind:
- Throw
EventBus.RetryableExceptiononly for temporary problems, such as a record lock. The platform retries up to 9 times before it stops redelivering that batch. - Retries use the same batch, so code must be idempotent. If the first attempt created some records before failing, the retry must not duplicate them.
- Platform events and change events share the same trigger retry model. Do not use retries for permanent errors such as bad data, because they cannot succeed.
- If you do not throw the retry exception, a failure ends the trigger run for that batch, and the events are not redelivered to the trigger.
Governor limits and checkpoints
The trigger gets its own set of governor limits per invocation. Each invocation handles one batch, and limits apply to the whole batch, so the bulk practices above matter.
A trigger processes events in order, and the platform moves forward as each batch finishes. For large batches that risk timeouts, EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId) lets the trigger mark the last event processed. A later retry resumes after that point instead of redelivering the whole batch.
trigger InvoiceChangeTrigger on Invoice__ChangeEvent (after insert) {
for (Invoice__ChangeEvent event : Trigger.new) {
// process one event
EventBus.TriggerContext.currentContext().setResumeCheckpoint(event.ReplayId);
}
}Set the checkpoint only after an event is fully processed, and combine it with EventBus.RetryableException for temporary failures.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Trigger does not fire | CDC not enabled for the object | Enable it in Change Data Capture settings |
| Compile error on `before insert` | Only `after insert` is supported | Change the timing keyword |
| Only first record handled | Code reads `recordIds[0]` | Loop over every ID |
| Field logic fires on every update | Checks the field for `null` instead of `changedFields` | Check `changedFields` |
| Repeated or runaway events | Trigger updates the object it listens to | Filter and skip your own changes |
| Duplicate records after a retry | Work is not idempotent | Use upserts or an external ID |
| Trigger works in tests but not live | Different user context or unflushed delivery | Check the Automated Process user's access |
Exercise
A change event trigger on ContactChangeEvent needs to run only when Email is edited on an existing contact. Which header values do you check, and why do you not check event.Email != null?
Show answer
Check that header.changeType == 'UPDATE' and that header.changedFields.contains('Email'). Testing the field value for null is unreliable because an unchanged field and a cleared field can both read as null, and an unchanged field is not included in the event at all.
Exercise
Your trigger creates a Task for each change event, and the original save succeeds even when the trigger throws an exception. Why does the save succeed, and what would you throw if a record lock caused a temporary failure?
Show answer
The trigger runs in a separate transaction after the original save commits, so its failure cannot roll the save back. For a temporary problem, throw EventBus.RetryableException so the platform redelivers the same batch, and keep the work idempotent so a retry does not create duplicates.