Sub topic 15
Commit and post-commit work
This chapter assumes you can write a basic Apex trigger, know what DML is, and have read the earlier chapters on the steps before the save. Here we cover the last part of the order of execution: the commit, and the work Salesforce does only after the commit succeeds.
Where the commit sits
By this point the record has been written to the database, but the write is not permanent. Before triggers, validation, after triggers, workflow, flows, roll-up summaries and criteria-based sharing have all run inside one open database transaction. If any of them fails, everything is rolled back.
The commit is the step that makes all of those changes permanent. After the commit, Salesforce runs post-commit logic.
What counts as post-commit work
Post-commit work is anything Salesforce holds back until it knows the data is safe. The common cases are:
- Email. Email alerts, and emails sent with
Messaging.sendEmail(), are queued during the transaction and sent after the commit. - Asynchronous Apex. Jobs started with
@futuremethods,System.enqueueJob()(Queueable) orDatabase.executeBatch()do not start running until the transaction commits. Each job then runs in its own transaction. - Platform events. An event defined with the Publish After Commit behavior is published only after a successful commit.
- Outbound messages and similar actions. These are sent after the commit.
- Flow paths that run after the save. Scheduled paths and asynchronous paths in a record-triggered flow run later, in separate transactions.
Because these items wait for the commit, a rollback cancels them. If a validation rule fails in step 6, the user never receives the "Account created" email and your queued job never runs. This is the main benefit of the design: outside systems and users don't hear about records that were never saved.
Why async work is a good fit
An after trigger often needs to call an external system. The trigger cannot do this directly if it has already performed DML in the same transaction. Apex throws a CalloutException ("You have uncommitted work pending") when a callout follows uncommitted DML.
Queueable Apex solves this. The callout moves to a new transaction that starts after the commit. This trigger and job pair shows the pattern. It assumes a Named Credential called Billing_API exists in the org.
trigger AccountSync on Account (after insert) {
// The Ids exist now, and the job starts only after commit
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [
SELECT Id, Name FROM Account WHERE Id IN :accountIds
];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getBody());
}
}
}The job passes Ids instead of records. By the time it runs, the data may have changed, so it queries fresh values.
Failures after the commit
Rollback no longer applies once the commit has happened. If an email fails to send, or your queueable throws an unhandled exception, the original record stays saved. The failure appears in the async job's own log, the Apex Jobs page, or the email delivery logs. The user's save has already succeeded.
This has a practical consequence. Post-commit code must handle its own errors. Record failures somewhere you can find them, such as a custom log object or a platform event, and retry if the work matters.
Platform events: choose the publish behavior
Platform events have a setting that changes the rule above.
| Publish behavior | When the event is published | If the transaction rolls back |
|---|---|---|
| Publish After Commit | After the commit succeeds | The event is never published |
| Publish Immediately | As soon as the publish call runs | The event is still published |
Use Publish After Commit when subscribers will read the saved record, because the data is guaranteed to exist. Use Publish Immediately for logging or error reporting, where you want the event even when the transaction fails.
Limits and gotchas
- Limits reset per transaction. A queueable job gets its own governor limits, separate from the transaction that enqueued it. That is why moving heavy work into async Apex relieves a nearly exhausted transaction.
- Enqueue limits still apply. A transaction can enqueue only 50 queueable jobs, and a trigger that enqueues one job per record can hit that cap in bulk loads. Enqueue once per trigger run, as the example does.
- Tests. Async jobs run synchronously in a test only when you wrap the code in
Test.startTest()andTest.stopTest(). Callouts in tests also need a mock, so useTest.setMock(). - Emails in tests and sandboxes. Email is subject to the org's deliverability setting, so a sandbox may block it by default.
Summary of the sequence
- Criteria-based sharing evaluation finishes.
- Salesforce commits all changes to the database.
- Post-commit logic runs: emails, async jobs, after-commit events.
- Failures from this point cannot undo the save.
Exercise
An after insert trigger on Account calls System.enqueueJob() and then a later validation-style Apex error in the same transaction aborts the save. Does the queueable job run? Why or why not? And if the job itself later throws an exception, is the Account deleted?
Show answer
The job does not run. Queued async work starts only after a successful commit, and the error rolls the transaction back, which cancels the job. If a job that did start later throws an exception, the Account is not deleted. The commit already happened, and the job runs in its own separate transaction, so its failure cannot roll back the original save.
Exercise
A trigger inserts a Contact and then makes an HTTP callout in the same transaction, and Salesforce throws "You have uncommitted work pending." How would you restructure the code, and what must the new class implement?
Show answer
Move the callout into a Queueable class started with System.enqueueJob() from the trigger. The class must implement Queueable and Database.AllowsCallouts. The job starts after the commit, in a new transaction, so no uncommitted work is pending when the callout runs.