Sub topic 11
Savepoints and the DML Statement Limit
This chapter assumes you can write Apex classes and methods, run insert and update statements, and handle DmlException with try/catch. It also assumes you know that Apex enforces governor limits per transaction. You have already seen how Database.setSavepoint and Database.rollback work. Here the topic is what they cost.
Savepoints are not free
A savepoint looks like bookkeeping, so it is easy to treat it as a free operation. It is not. Apex counts both of these against the DML statements limit:
- Each call to
Database.setSavepoint()counts as one DML statement. - Each call to
Database.rollback(sp)counts as one DML statement.
The limit is 150 DML statements per transaction. It is the same for synchronous and asynchronous Apex. The limit counts statements, not rows. One insert of 200 records uses one statement, and so does one setSavepoint().
| Operation | DML statements used |
|---|---|
| `insert accts;` (any number of records) | 1 |
| `Database.insert(accts, false);` | 1 |
| `Database.setSavepoint();` | 1 |
| `Database.rollback(sp);` | 1 |
| `Database.rollback(sp)` after a rollback to an earlier savepoint | Fails at runtime. See the previous chapter |
Measuring the cost yourself
The Limits class reports consumption. Limits.getDmlStatements() returns the number of statements used so far. Limits.getLimitDmlStatements() returns the maximum. The test below confirms that each savepoint call and each rollback adds exactly one.
@IsTest
private class SavepointCostTest {
@IsTest
static void savepointAndRollbackEachCountAsDml() {
Integer start = Limits.getDmlStatements();
Savepoint sp = Database.setSavepoint();
Integer afterSet = Limits.getDmlStatements();
Database.rollback(sp);
Integer afterRollback = Limits.getDmlStatements();
System.assertEquals(start + 1, afterSet, 'setSavepoint should cost one statement');
System.assertEquals(afterSet + 1, afterRollback, 'rollback should cost one statement');
System.assertEquals(150, Limits.getLimitDmlStatements());
}
}Run it and the assertions pass. Rolling back does not give the statements back. Governor limit usage only goes up during a transaction, even when the data changes are undone.
Where the cost becomes a problem
The risk is a savepoint set inside a loop. Suppose you want each record to succeed or fail on its own, and you write this:
public with sharing class PerRecordLoader {
// Anti-pattern: two DML statements per record, plus one more per failure.
public static void load(List<Account> accts) {
for (Account a : accts) {
Savepoint sp = Database.setSavepoint(); // +1
try {
insert a; // +1
} catch (DmlException e) {
Database.rollback(sp); // +1 on failure
}
}
}
}With 50 records and no failures, the loop uses 100 statements. With 75 records it reaches 150 statements. After that, the next DML statement throws System.LimitException: Too many DML statements: 151. A LimitException cannot be caught, so the whole transaction fails and rolls back. A trigger that receives 200 records from a data load can hit this on the first batch.
This code is also redundant. The insert of a single record is already atomic, and a failed insert changes nothing. The savepoint protects against nothing here.
Cost rule: one savepoint per unit of work, not per record
Set savepoints around a logical unit of work, such as "create the account and its contacts". Do not set them around each record. Handle per-record failures with the partial-success Database methods, which report failures without any savepoint.
This version uses three statements in the worst case, whatever the list size:
public with sharing class BulkLoader {
public class LoadResult {
public Boolean rolledBack = false;
public List<String> messages = new List<String>();
}
// Cost: 1 (setSavepoint) + 1 (Database.insert) + at most 1 (rollback) = 3 statements.
public static LoadResult loadAllOrNothing(List<Account> accts) {
LoadResult result = new LoadResult();
Savepoint sp = Database.setSavepoint();
Database.SaveResult[] saveResults = Database.insert(accts, false);
Boolean anyFailed = false;
for (Integer i = 0; i < saveResults.size(); i++) {
if (!saveResults[i].isSuccess()) {
anyFailed = true;
for (Database.Error err : saveResults[i].getErrors()) {
result.messages.add('Row ' + i + ': ' + err.getMessage());
}
}
}
if (anyFailed) {
Database.rollback(sp);
result.rolledBack = true;
}
return result;
}
}The partial-success insert lets you collect every error in one pass. The savepoint then lets you discard the records that did save, if the business rule says all or none must be kept. If your rule is "keep the good records", drop the savepoint and the rollback and use only Database.insert(accts, false), which costs one statement.
Several units of work in one transaction
Sometimes you need more than one savepoint. An example is a method that processes a list of order groups, where each group is a unit that must be all-or-nothing. The cost is then one setSavepoint per group, plus a rollback for each group that fails. Budget for it before you write the loop:
public with sharing class GroupProcessor {
public static void process(List<List<Account>> groups) {
// Worst case: 3 statements per group (set, insert, rollback).
// Stop early if the remaining budget cannot cover another group.
for (List<Account> grp : groups) {
Integer remaining = Limits.getLimitDmlStatements() - Limits.getDmlStatements();
if (remaining < 3) {
System.debug(LoggingLevel.WARN, 'Stopping: not enough DML statements left');
break;
}
Savepoint sp = Database.setSavepoint();
try {
insert grp;
} catch (DmlException e) {
Database.rollback(sp);
}
}
}
}Two points about this code:
- Stopping early is a design choice. Skipping the remaining groups silently is rarely acceptable in production. A better approach is to return the unprocessed groups to the caller, or to hand them to a Queueable job, which starts a new transaction with a fresh limit.
- If you need a savepoint for each of hundreds of groups, move the work to Batch Apex with a small scope size. Each
executecall is its own transaction with its own 150-statement budget.
Other limits that interact with rollback
A rollback undoes data changes. It does not undo limit consumption. Every resource below stays counted after Database.rollback:
- DML statements. The statements you used for the inserts you rolled back are still counted.
- DML rows. The 10,000 row limit still counts rows that you inserted and then rolled back.
- SOQL queries and CPU time. These also continue to accumulate.
A retry loop that rolls back and tries again therefore consumes the budget on every attempt. Keep retries bounded, and check Limits before you retry.
Summary of rules
- Count each
setSavepointand eachrollbackas one DML statement against the limit of 150. - Place savepoints around a logical unit of work, not around each record.
- Use
Database.insert(records, false)for per-record failure handling, because it needs no savepoint. - Remember that a rollback does not refund DML statements, DML rows, or other limits.
- For many independent units of work, use Batch Apex or Queueable Apex so that each chunk gets its own limits.
Exercise
A trigger handler receives 200 Contact records. For each one it calls Database.setSavepoint(), then update contact;, and on a DmlException calls Database.rollback(sp). No updates fail. Does the transaction succeed? If not, at which point does it fail, and how would you restructure it?
Show answer
It fails. Each iteration uses 2 DML statements (the savepoint and the update), so after 75 iterations the transaction has used 150. The next DML statement, the 76th savepoint, throws an uncatchable System.LimitException: Too many DML statements: 151, and the whole transaction rolls back. To fix it, make one Database.update(contacts, false) call. It costs one statement and returns a SaveResult per record. If the business rule is all-or-nothing, set one savepoint before that call and make at most one Database.rollback(sp) after it if any SaveResult failed. The total is then at most 3 statements.
Exercise
A method uses 10 DML statements, then sets a savepoint, performs a bulk Database.insert(records, false), finds a failure, and calls Database.rollback(sp). What does Limits.getDmlStatements() return afterwards, and why?
Show answer
It returns 13. The initial 10 statements, plus 1 for setSavepoint, 1 for the insert, and 1 for the rollback. The rollback undoes the data changes but does not refund any governor limit usage.