Sub topic 12
What a rollback does not revert
This chapter assumes you can write Apex classes and run DML, you know try/catch with DmlException, and you have already used Database.setSavepoint and Database.rollback. Here you will learn the limits of a rollback. Database.rollback(sp) restores the database. It does not restore the Apex heap, the governor counters, or anything that left the transaction.
The database is reverted, your variables are not
A rollback undoes database changes made after the savepoint: inserts, updates, deletes, and undeletes. Your running code lives in memory, so it keeps whatever state it had when you called rollback.
| Item | Reverted by rollback? |
|---|---|
| Rows inserted, updated, or deleted after the savepoint | Yes |
| `Id` on an sObject you inserted | No |
| Field values you changed on in-memory sObjects | No |
| Static variables and other heap state | No |
| Governor limit usage (DML statements, queries, CPU) | No |
| Callouts already made to external systems | No |
| Platform events published with the publish-immediately behavior | No |
The diagram below shows the same split as a flow.
sObject Ids survive the rollback
When insert succeeds, Apex writes the new Id onto your in-memory record. A rollback deletes the row, but the record variable still holds that Id. The Id now points at nothing.
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Temp');
insert a;
Database.rollback(sp);
System.debug('Id after rollback: ' + a.Id); // still populated
System.debug('Rows found: ' + [SELECT COUNT() FROM Account WHERE Id = :a.Id]); // 0
a.Id = null; // clear the stale Id before reusing the record
insert a;If you skip a.Id = null, the second insert fails with a DmlException whose message says you cannot specify an Id in an insert call. An update on the stale record fails too, because the row no longer exists.
Setting Id to null works, but a cleaner option is to clone. clone(false) copies the field values and drops the Id:
Savepoint sp = Database.setSavepoint();
Account original = new Account(Name = 'Temp');
insert original;
Database.rollback(sp);
Account fresh = original.clone(false); // preserveId = false
insert fresh;
System.debug(fresh.Id != original.Id); // trueThe same applies to lists. If you insert a List<Contact> and then roll back, every element keeps its Id. Clear or clone each element before retrying.
Field values on in-memory records stay changed
A rollback does not touch the values you set on a record. This matters when a trigger or your own code modifies fields before saving. For example, if you set acct.Description = 'Processed' and then roll back, the variable still says 'Processed'. If you pass that variable to a later update, you write the changed value back to the database as if nothing happened.
When you retry after a rollback, rebuild the records from a fresh query or from clones. Do not assume the objects in memory match the database.
Static variables keep their values
Static variables belong to the transaction, not to the database. This is a common source of bugs in trigger handlers that use a static flag to prevent recursion.
public class RunOnce {
public static Boolean hasRun = false;
}Run this as anonymous Apex:
Savepoint sp = Database.setSavepoint();
RunOnce.hasRun = true;
insert new Account(Name = 'Temp');
Database.rollback(sp);
System.debug(RunOnce.hasRun); // true, not falseAfter the rollback the account is gone, but hasRun is still true. If you retry the same work in the same transaction and your trigger checks RunOnce.hasRun, the trigger skips its logic. The retry then saves incomplete data without any error.
Two fixes work well:
- Reset the flag yourself right after the rollback.
- Store the flag per record, for example in a
Set<Id>of processed Ids. Then remove the Ids of rolled-back records from the set.
public class ProcessedTracker {
private static Set<Id> processed = new Set<Id>();
public static Boolean isProcessed(Id recordId) {
return processed.contains(recordId);
}
public static void markProcessed(Id recordId) {
processed.add(recordId);
}
public static void forget(Set<Id> recordIds) {
processed.removeAll(recordIds);
}
}Call ProcessedTracker.forget(...) in the same catch block that calls Database.rollback, so the cleanup cannot be forgotten.
Governor limits are not refunded
Each call to Database.setSavepoint() and each call to Database.rollback() counts as one DML statement against the limit of 150 per transaction. Rolling back does not give back the statements or rows that the undone work used.
Integer start = Limits.getDmlStatements();
Savepoint sp = Database.setSavepoint(); // +1
insert new Account(Name = 'Temp'); // +1
Database.rollback(sp); // +1
System.debug('DML statements used: ' + (Limits.getDmlStatements() - start)); // 3Query counts, CPU time, and heap size behave the same way. A loop that sets a savepoint, saves a record, and rolls back on failure spends up to three DML statements per iteration. With 50 or more iterations you can approach the limit even though almost nothing was committed. For bulk work, prefer one savepoint around the whole batch of records, or use Database.insert(records, false) and handle failures through SaveResult.
External effects cannot be undone
A rollback only reaches the Salesforce database. If your transaction already did one of the following, the effect stays:
- A callout. If you called a payment service and then rolled back the order, the payment service still has the charge. Apex also blocks the reverse order. A callout after uncommitted DML in the same transaction raises a "You have uncommitted work pending" error. The usual pattern is to make callouts first, then do DML. Alternatively, move the callout to a separate transaction with a queueable job.
- Publishing a platform event with the publish-immediately behavior. The event is delivered whether or not the transaction later rolls back. Events configured with the publish-after-commit behavior are not sent if the transaction rolls back.
- Debug log entries. Log lines written before the rollback remain in the log. That helps you, because the log shows what was attempted.
Design these steps so a rollback does not leave the systems inconsistent. A common approach is to do the database work first, commit, and only then call the external system. If that call fails, record the failure and compensate, for example with a refund or a retry job.
Putting it together
Here is a guarded block that accounts for everything above:
List<Account> accts = new List<Account>{
new Account(Name = 'Alpha'),
new Account(Name = 'Beta')
};
Savepoint sp = Database.setSavepoint();
try {
insert accts;
// ... more work that might throw ...
throw new DmlException('Simulated failure');
} catch (Exception e) {
Database.rollback(sp);
// The rows are gone, but the in-memory records still carry Ids.
List<Account> retry = new List<Account>();
for (Account a : accts) {
retry.add(a.clone(false));
}
accts = retry;
System.debug('Rolled back. Clean records ready: ' + accts.size());
}The catch block does three jobs in order: it undoes the database work, it repairs in-memory state, and it leaves the variables ready for a retry or a report.
Exercise
A trigger handler uses public static Boolean hasRun = false; to prevent recursion. Your code sets a savepoint, runs DML that fires the trigger (which sets hasRun = true), hits an error, rolls back to the savepoint, and then retries the same DML in the same transaction. The retry silently saves records without the trigger logic. Why, and how do you fix it?
Show answer
The rollback reverts database rows but not static variables, so hasRun is still true and the trigger skips its logic on the retry. Fix it by resetting the flag in the catch block right after Database.rollback, or by tracking processed record Ids in a static Set<Id> and removing the rolled-back Ids from it.
Exercise
You insert a list of Contacts, roll back to a savepoint, and then call insert contacts; again with the same list. What error do you get, and what are two ways to avoid it?
Show answer
The insert fails with a DmlException saying an Id cannot be specified in an insert call, because the rollback removed the rows but left the Ids on the in-memory records. Avoid it by setting each record's Id to null before re-inserting, or by building new records with clone(false).
Exercise
A loop processes 100 records. For each one it calls Database.setSavepoint(), inserts the record, and calls Database.rollback(sp) when a validation fails. If every record fails, how many DML statements does the loop use at most, and why does rolling back not help?
Show answer
Up to 300: each iteration spends one statement on setSavepoint, one on insert, and one on rollback. That exceeds the limit of 150. A rollback does not refund governor usage, and the savepoint and rollback calls themselves count as DML statements.