Sub topic 10
Why Later Savepoints Become Invalid
This chapter assumes you can set a savepoint with Database.setSavepoint() and roll back with Database.rollback(). It also assumes you know that each of those calls counts against the DML statement limit. Here you will see what happens when a transaction holds more than one savepoint, why some of them stop working, and how to write code that never uses a dead one.
Savepoints are ordered markers
A savepoint marks a point in the transaction's timeline. Each call to Database.setSavepoint() returns a Savepoint object that refers to the database state at that moment. Savepoints form an ordered sequence, and the order matters.
Rolling back to a savepoint discards everything that happened after it. That includes any savepoints you set after it, because the moments they marked no longer exist. The rule is:
- If you roll back to a savepoint that is not the most recent one, every savepoint created after it becomes invalid.
- Using an invalid savepoint causes a runtime error.
The Savepoint variable still exists in your code and still compiles. Nothing warns you at the point where it was invalidated. The failure appears only when you pass the variable to Database.rollback().
Savepoint sp1 = Database.setSavepoint();
insert new Account(Name = 'A');
Savepoint sp2 = Database.setSavepoint();
insert new Account(Name = 'B');
Database.rollback(sp1); // removes A and B, and invalidates sp2
Database.rollback(sp2); // runtime error: sp2 no longer existsThe second Database.rollback makes no sense. After the first rollback, the state sp2 pointed at (account A inserted, B not yet) is gone. There is nothing to return to.
The timeline
The diagram shows the same sequence as the code above.
Rolling back in the safe direction
Rolling back to a later savepoint first, then to an earlier one, is valid. Going back in time one step at a time never invalidates a savepoint you still need.
Savepoint sp1 = Database.setSavepoint();
insert new Account(Name = 'A');
Savepoint sp2 = Database.setSavepoint();
insert new Account(Name = 'B');
Database.rollback(sp2); // B is removed, A remains
Database.rollback(sp1); // A is removed; sp1 was set before sp2, so it is still validThe order of rollbacks is therefore the thing to design. A rollback to the newest savepoint invalidates nothing that you still need. A rollback to an older savepoint invalidates everything newer.
How this happens in real code
You rarely write sp1 and sp2 next to each other as in the examples. Invalid savepoints usually come from code that is spread across several methods.
Consider a service method that sets a savepoint, calls a helper, and the helper sets its own savepoint:
public class OrderService {
public static void process(List<Account> accounts) {
Savepoint outer = Database.setSavepoint();
try {
insert accounts;
OrderHelper.createContacts(accounts);
} catch (DmlException e) {
Database.rollback(outer);
throw e;
}
}
}
public class OrderHelper {
public static void createContacts(List<Account> accounts) {
Savepoint inner = Database.setSavepoint();
List<Contact> contacts = new List<Contact>();
for (Account a : accounts) {
contacts.add(new Contact(LastName = 'Primary', AccountId = a.Id));
}
try {
insert contacts;
} catch (DmlException e) {
Database.rollback(inner); // valid: inner is the newest savepoint here
throw e;
}
}
}This code is safe. The helper rolls back to its own savepoint, which is the newest one. Then the exception propagates, and the caller rolls back to the older savepoint. Each rollback goes from newer to older.
The same structure breaks if the helper keeps its savepoint somewhere that outlives the call, for example in a static field, and the caller rolls back first. Any later use of that field raises the runtime error.
Savepoints do not cross trigger invocations
A second kind of invalidation has nothing to do with ordering. Each trigger invocation is a new execution context. A savepoint created in one trigger invocation cannot be used in another. If you store a savepoint in a static variable and use it from a later trigger invocation, you get a runtime error.
public class SavepointHolder {
public static Savepoint saved;
}Setting SavepointHolder.saved in one trigger run and calling Database.rollback(SavepointHolder.saved) in the next run fails. Keep a savepoint in a local variable and use it within the same invocation that created it.
Tracking savepoints so you never use an invalid one
Apex has no method that asks whether a savepoint is still valid. You cannot test a Savepoint before using it, so the safe approach is to track validity yourself.
The class below keeps savepoints on a stack. When you roll back to one, it discards that entry and all later ones. Any later attempt to use a discarded entry fails with a clear message instead of a vague runtime error from the platform.
public class SavepointScope {
private List<Savepoint> stack = new List<Savepoint>();
// Sets a savepoint and returns its position.
public Integer mark() {
stack.add(Database.setSavepoint());
return stack.size() - 1;
}
// Rolls back to the savepoint at the given position.
// That savepoint and every later one are treated as consumed.
public void rollbackTo(Integer position) {
if (position < 0 || position >= stack.size()) {
throw new IllegalArgumentException(
'Savepoint ' + position + ' is unknown or was invalidated by an earlier rollback');
}
Database.rollback(stack[position]);
while (stack.size() > position) {
stack.remove(stack.size() - 1);
}
}
}The class treats the target savepoint as consumed along with the later ones. This is deliberately conservative. If you need to roll back to the same point again, call mark() once more after the rollback.
Here is how it behaves in an anonymous Apex block:
SavepointScope scope = new SavepointScope();
Integer first = scope.mark();
insert new Account(Name = 'A');
Integer second = scope.mark();
insert new Account(Name = 'B');
scope.rollbackTo(first); // undoes A and B, discards both marks
try {
scope.rollbackTo(second);
} catch (IllegalArgumentException e) {
System.debug(e.getMessage()); // Savepoint 1 is unknown or was invalidated ...
}Each mark() and rollbackTo() still counts against the DML statement limit, because the underlying setSavepoint and rollback calls do. The wrapper adds no extra cost.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Rolling back to an older savepoint, then to a newer one | Runtime error on the second rollback | Roll back newest first, or set a new savepoint after the rollback |
| Storing a savepoint in a static variable and reusing it in another trigger run | Runtime error | Keep the savepoint in a local variable |
| Helper method rolls back to a savepoint passed in by the caller | Caller's later savepoints may be invalid without the caller knowing | Have each method roll back only to savepoints it created |
| Catching the failed rollback and continuing | The transaction may hold work you expected to be undone | Avoid the situation instead of handling the error |
The third row deserves attention. When a method receives a Savepoint as a parameter and rolls back to it, it invalidates every savepoint the caller set afterwards. The caller cannot see this. Passing savepoints into other methods spreads the knowledge of ordering across your codebase. Keeping each savepoint inside the method that created it limits the damage.
Design guidance
- Prefer one savepoint per unit of work, and roll back only to the savepoint you set yourself.
- If you need several savepoints, roll back newest first.
- After rolling back to an earlier savepoint, treat all later
Savepointvariables as unusable and set fresh ones if you need them. - Do not store savepoints in static fields that outlive the method that created them.
- Remember that each
setSavepointandrollbackcall counts toward the DML statement limit. A design that sets many savepoints in a loop can run out of statements before it runs out of records.
Exercise
A transaction runs this code. Which line causes a runtime error, and why? How would you reorder the rollbacks so that both succeed? Savepoint a = Database.setSavepoint(); insert new Account(Name = 'One'); Savepoint b = Database.setSavepoint(); insert new Account(Name = 'Two'); Savepoint c = Database.setSavepoint(); insert new Account(Name = 'Three'); Database.rollback(a); Database.rollback(c);
Show answer
The line Database.rollback(c) fails. Rolling back to a invalidated b and c, because both were set after a. To make both rollbacks succeed, roll back to c first and then to a. Rolling back to c removes only the third account, and a is older than c, so it stays valid for the second call.
Exercise
A trigger stores a Savepoint in a public static field on a helper class. A later trigger invocation in the same transaction calls Database.rollback with that field. Why is this a problem, and what is the safer approach?
Show answer
Each trigger invocation is a new execution context, and a savepoint cannot be used across trigger invocations. Using the stored value raises a runtime error. The safer approach is to set the savepoint in a local variable and use it only within the invocation that created it.
Exercise
Why does the SavepointScope class remove the target position as well as the later positions after a rollback? What would you do if you wanted to roll back to the same point twice?
Show answer
The class is deliberately conservative. It treats the savepoint you rolled back to as consumed, so the code never relies on behavior it cannot confirm. To roll back to the same point twice, call mark() again right after the first rollback and use the new position.