Sub topic 12
Rolling back with savepoints
This chapter assumes you can write try/catch blocks, throw and catch DmlException, and know that one Apex execution context is one database transaction. It covers how to undo part of a transaction yourself when you catch an error.
Why catching an exception can leave bad data behind
An uncaught exception rolls back the whole transaction. Every insert, update, and delete made since the execution context started is discarded, and the user sees the error.
A caught exception changes that. Once your catch block handles the error, Apex treats the transaction as healthy, and the transaction commits when execution finishes. Any DML that succeeded before the failure is saved with it.
Consider this code:
try {
Account acc = new Account(Name = 'Parent');
insert acc;
insert new Contact(AccountId = acc.Id); // fails: LastName is required
} catch (DmlException e) {
System.debug('Failed: ' + e.getMessage());
}The Contact insert fails, but the Account insert has already succeeded, and the catch block does nothing to undo it. When the transaction commits, you have an Account with no Contact. If your business rule says the two records belong together, the data is now inconsistent.
A savepoint lets you undo that earlier work from inside the catch block.
Setting a savepoint and rolling back
Database.setSavepoint() marks the current state of the database and returns a Savepoint object. Database.rollback(sp) restores the database to that state.
Savepoint sp = Database.setSavepoint();
try {
Account acc = new Account(Name = 'Parent');
insert acc;
insert new Contact(AccountId = acc.Id);
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}The sequence is:
- Set the savepoint before any DML you may need to undo.
- Do the work inside
try. - In
catch, callDatabase.rollback(sp). - Rethrow, wrap, or return an error so the caller knows the operation failed.
Rolling back and then swallowing the error is allowed, but the caller then cannot tell that the work did not happen. Pick a signal deliberately.
A service method that wraps and rolls back
Combining a savepoint with a custom exception gives callers one predictable failure type. The original DmlException stays available as the cause.
public with sharing class OnboardingService {
public class OnboardingException extends Exception {}
public static Id onboard(String accountName, String lastName) {
Savepoint sp = Database.setSavepoint();
try {
Account acc = new Account(Name = accountName);
insert acc;
insert new Contact(AccountId = acc.Id, LastName = lastName);
return acc.Id;
} catch (DmlException e) {
Database.rollback(sp);
throw new OnboardingException('Onboarding failed: ' + e.getMessage(), e);
}
}
}If a caller catches OnboardingException and continues, the database holds neither record. Without the rollback, the orphaned Account would be committed.
What a rollback does and does not undo
A rollback restores database state only. Several things stay as they were.
| Item | After `Database.rollback` |
|---|---|
| Inserted, updated, deleted records | Restored to the savepoint state |
| `Id` field on sObject variables you inserted | Still populated |
| Static variables and other in-memory state | Not restored |
| Savepoints created after the one you roll back to | Invalid |
| DML statement count against the governor limit | Not refunded |
Ids stay on your variables
After a rollback, the record no longer exists, but the sObject variable still holds the Id that insert assigned. Inserting that variable again fails because an insert cannot specify an Id.
Savepoint sp = Database.setSavepoint();
Account acc = new Account(Name = 'Temp');
insert acc;
Database.rollback(sp);
System.debug('Id still set: ' + (acc.Id != null)); // true
Account retry = new Account(Name = acc.Name);
insert retry; // works: new variable, no IdTo retry, build a fresh sObject or clone the old one without its Id. Do not reuse the original variable.
Nested savepoints
You can set several savepoints in one transaction. Rolling back to an earlier savepoint invalidates every savepoint created after it.
Savepoint spOuter = Database.setSavepoint();
insert new Account(Name = 'A');
Savepoint spInner = Database.setSavepoint();
insert new Account(Name = 'B');
Database.rollback(spInner); // B is gone, A remains
Database.rollback(spOuter); // A is gone too
// Database.rollback(spInner) here would fail: spInner is now invalidUsing an invalid savepoint raises a runtime error. This matters in layered code. If a helper method sets its own savepoint and an outer method rolls back past it, the helper's savepoint cannot be used afterward.
Governor limits
Each setSavepoint call and each rollback call counts as a DML statement. The synchronous limit is 150 DML statements per transaction. Setting a savepoint inside a loop is a common way to exhaust that limit.
// Avoid: one savepoint and one possible rollback per record
for (Account a : accounts) {
Savepoint sp = Database.setSavepoint();
// ...
}Set one savepoint around the unit of work instead. If you need per-record failure handling, use partial-success DML from the previous chapter, not one savepoint per record.
Savepoints and callouts
Rollback only covers database changes. It cannot unsend an HTTP request. If your method makes a callout and then fails, the external system keeps whatever it received. Apex also restricts making a callout after DML in the same transaction, which is why callouts are normally placed first or moved to asynchronous Apex. A savepoint does not change that restriction.
When you need a savepoint and when you do not
| Situation | Savepoint needed? |
|---|---|
| One DML statement with `allOrNone` true (the default) | No. The statement is already atomic. |
| Several DML statements, and you let the exception propagate | No. The platform rolls back everything. |
| Several DML statements, and you catch the exception and continue | Yes. Earlier DML would otherwise commit. |
| Partial-success DML where you accept some failures | No. Failed records are never saved. |
| Unit tests | No. The platform discards test data at the end of the test. |
The second row is the most useful to remember. If the right response to a failure is "stop and report the error", it is usually simplest to let the exception propagate, or to wrap and rethrow it, without catching it in the middle of the work. Use a savepoint when you must catch the error and keep running.
Common mistakes
- Setting the savepoint after the first DML, so that DML is not covered.
- Rolling back and then swallowing the exception, so the caller assumes success.
- Reusing an inserted sObject variable after rollback and getting an error about the Id.
- Using a savepoint variable after rolling back to an earlier one.
- Creating savepoints inside loops and exceeding the DML statement limit.
- Expecting rollback to restore static variables, collections, or external systems.
Practice
Exercise
A method sets a savepoint, inserts an Account, then inserts a Contact that fails with a DmlException. The catch block logs the error with System.debug and does not call Database.rollback or rethrow. What is in the database after the transaction finishes, and what is the minimum change that fixes it?
Show answer
The Account is committed, because the caught exception lets the transaction commit and nothing undid the first insert. The Contact is not saved. The minimum fix is to call Database.rollback(sp) in the catch block, using the savepoint set before the Account insert. You should also rethrow or wrap the exception so the caller knows the operation failed.
Exercise
You set spA, insert a record, set spB, insert another record, then call Database.rollback(spA). What happens if you later call Database.rollback(spB), and why?
Show answer
It fails with a runtime error. Rolling back to spA, which was created earlier, invalidates every savepoint created after it, including spB.
Exercise
After Database.rollback(sp), you call insert on the same Account variable you inserted before the savepoint rollback, and it fails. Why, and how do you retry?
Show answer
The rollback removed the record from the database but did not clear the Id on the sObject variable. Inserting a record that already has an Id is an error. Create a new Account with the same field values, or clone the original without its Id, and insert that.