Sub topic 14
Savepoints and rollback around DML
This chapter assumes you can write Apex classes and methods, use try/catch, and have met DmlException, the allOrNone parameter, and Database.SaveResult in earlier chapters. It also assumes you know that Apex runs in a transaction bound by governor limits.
Why you need savepoints
Both DML statements and Database methods are atomic only for a single call. When insert accounts; fails, Salesforce undoes that statement. It does not undo any earlier statement in the same transaction.
That gap matters when you catch an exception. Suppose your code inserts an Account, then inserts Contacts, and the Contact insert fails. If you catch the DmlException and carry on, the transaction finishes normally and the Account is committed. You now have an Account with no Contacts, even though your business rule said both must exist.
Compare these outcomes:
| Situation | What happens to earlier DML in the transaction |
|---|---|
| Exception is not caught | The whole transaction rolls back automatically |
| Exception is caught and nothing else is done | Earlier DML is committed when the transaction ends |
| Exception is caught and `Database.rollback` is called | DML after the savepoint is undone |
| One DML call fails with `allOrNone` true | Only that call is undone |
| One DML call has failed rows with `allOrNone` false | Only the failed rows are skipped. Saved rows stay |
A savepoint is a marker you set before a group of DML operations. You can roll the database back to that marker later in the same transaction.
The basic pattern
You set a savepoint with Database.setSavepoint(), which returns a Savepoint value. You undo work with Database.rollback(savepoint).
Savepoint sp = Database.setSavepoint();
try {
insert new Account(Name = 'Acme');
insert new Contact(LastName = 'Smith');
// Further logic may decide the work must be undone
throw new CalloutException('Simulated downstream failure');
} catch (Exception e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
}Both inserts succeed. The simulated failure then sends control to the catch block, and Database.rollback(sp) removes the Account and the Contact from the pending transaction. When the transaction ends, neither record exists.
Set the savepoint before the first DML statement you might want to undo. A rollback cannot reach back past the savepoint.
What a rollback does and does not undo
A rollback restores database state. It does not restore everything your code touched. These are the gaps that cause most bugs.
In-memory records keep their IDs
After insert, each record in your variable or list has an Id. Rolling back removes the row from the database, but your in-memory record still holds the old Id. Inserting that same object again fails, because you cannot specify an Id on insert.
Savepoint sp = Database.setSavepoint();
Account original = new Account(Name = 'Acme');
insert original;
System.debug('Id before rollback: ' + original.Id);
Database.rollback(sp);
System.debug('Id after rollback: ' + original.Id); // still populated
// Clone without the Id to retry the insert
Account retry = original.clone(false, true, false, false);
insert retry;
System.debug('New Id: ' + retry.Id);The first argument to clone is false, so the copy does not preserve the Id. For a list, build fresh records or clone each one the same way.
Static variables and other state
Rollback does not reset static variables, member variables, or collections. A static counter or a static Set<Id> that you filled during the transaction still holds those values afterward. This also affects trigger recursion guards. A static Boolean set to true before the rollback stays true, so later trigger runs in the same transaction may skip logic they should run.
Governor limits are not refunded
Work done before the rollback still counts. The limits for DML statements, DML rows, SOQL queries, and CPU time stay consumed. Rollback undoes data, not resource use.
Savepoints and rollbacks count as DML
Each call to Database.setSavepoint() counts as one DML statement against the per-transaction limit of 150. Each call to Database.rollback() counts as one as well. Keep this in mind in loops. Setting a savepoint for every record in a 200-record batch uses 200 DML statements and fails with a limit exception.
Side effects outside the database
A rollback cannot recall a callout that has already completed. Treat any change outside Salesforce as outside the savepoint. Where you can, do callouts before or after the DML block rather than in the middle of it.
Multiple savepoints
You can set more than one savepoint in a transaction. Rolling back to an earlier savepoint invalidates every savepoint you set after it. Using an invalidated savepoint throws a runtime error.
Savepoint outer = Database.setSavepoint();
insert new Account(Name = 'Outer Account');
Savepoint inner = Database.setSavepoint();
insert new Account(Name = 'Inner Account');
// Undo only the inner account
Database.rollback(inner);
// Outer Account is still pending. Undo it too.
Database.rollback(outer);
// This would fail: inner was set after outer, so it is no longer valid
// Database.rollback(inner);The savepoints behave like a stack. Rolling back to inner leaves outer valid. Rolling back to outer discards everything after it, including inner.
Combining savepoints with partial success
Partial success and savepoints solve different problems. Setting allOrNone to false lets good rows save while bad rows fail. A savepoint lets you undo several operations as a unit. You often need both in one method: tolerate failures within a step, then decide whether the whole unit is acceptable.
public with sharing class OnboardingService {
public class OnboardingException extends Exception {}
public static Id onboard(String accountName, List<Contact> contacts) {
Savepoint sp = Database.setSavepoint();
try {
Account acct = new Account(Name = accountName);
insert acct;
for (Contact c : contacts) {
c.AccountId = acct.Id;
}
List<Database.SaveResult> results = Database.insert(contacts, false);
Integer failures = 0;
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failures++;
}
}
if (failures > 0) {
throw new OnboardingException(failures + ' contact(s) failed to save');
}
return acct.Id;
} catch (Exception e) {
Database.rollback(sp);
throw e;
}
}
}Database.insert(contacts, false) does not throw when a Contact fails, so the method counts the failures itself. If any row failed, it throws its own exception, and the catch block rolls back the Account and every Contact that did save. The method then rethrows, so the caller still learns about the failure.
This pattern also shows a choice. If you used the plain statement insert contacts;, a failed Contact would throw a DmlException on its own. The same catch block would handle it. You need the Database form only when you want to inspect row-level results before deciding.
Rolling back versus letting the exception escape
Rethrowing after a rollback is a design choice. Consider both options:
- Rethrow after rollback. The caller sees the failure. If the exception reaches the top of the transaction, Salesforce rolls back everything anyway, and your explicit rollback was redundant but harmless.
- Roll back and return normally. The transaction continues and commits whatever else it did. Use this when the failed unit is optional, for example one record in a larger import, and you report the error through a return value or a log record.
Be careful with the second option. If you write a log record after the rollback, that log row is committed, which is usually what you want. If you write it before the rollback, the rollback erases it.
Testing rollback logic
In a test, force the failure and check that the data is gone. Reusing the service above:
@IsTest
private class OnboardingServiceTest {
@IsTest
static void rollsBackAccountWhenContactFails() {
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Valid'),
new Contact() // LastName is required, so this row fails
};
try {
OnboardingService.onboard('Rollback Test Co', contacts);
System.assert(false, 'Expected an exception');
} catch (OnboardingService.OnboardingException e) {
System.assert(e.getMessage().contains('1 contact'));
}
System.assertEquals(0,
[SELECT COUNT() FROM Account WHERE Name = 'Rollback Test Co']);
System.assertEquals(0,
[SELECT COUNT() FROM Contact WHERE LastName = 'Valid']);
}
}The test checks both objects. A passing test confirms that the valid Contact, which saved successfully inside the call, was removed along with the Account.
Summary of decisions
- Use a plain statement or
allOrNonetrue when a single DML call must succeed or fail as one unit. - Add a savepoint when several DML calls must succeed or fail together and you catch exceptions.
- Combine
allOrNonefalse with a savepoint when you need row-level results but also want an all-or-nothing outcome for the whole unit. - After a rollback, discard or clone any in-memory records that received IDs, and remember that static state is not reset.
Exercise
A method sets a savepoint, inserts an Account, then inserts a list of Contacts with Database.insert(contacts, false). Two of the ten Contacts fail validation. The method does not check the results and does not call Database.rollback. What is in the database when the transaction ends, and why?
Show answer
The Account and the eight valid Contacts are committed. With allOrNone set to false, record-level failures do not throw an exception, so nothing triggers the rollback, and the savepoint has no effect unless Database.rollback is called. The method needs to check isSuccess() on each SaveResult and roll back if any row failed.
Exercise
After Database.rollback(sp), you call insert acct; again on the same Account variable that you inserted before the rollback. The insert fails. What causes the failure, and how do you fix it?
Show answer
The in-memory acct still holds the Id assigned by the first insert, and an insert cannot specify an Id. Create a copy without the Id, for example Account retry = acct.clone(false, true, false, false);, and insert the copy.
Exercise
A loop runs 200 times, and each iteration calls Database.setSavepoint() and, on failure, Database.rollback(sp). What problem will you hit, and what is a better design?
Show answer
Each setSavepoint and each rollback counts as a DML statement, and the transaction limit is 150. The loop will exceed it and throw a limit exception. Set one savepoint before the loop, collect the records, and use one bulk DML call, or use allOrNone false and inspect the results instead of rolling back per record.