Apex Transaction Savepoints Explained

Apex Transaction Savepoints Explained: Savepoint & Rollback in Salesforce

Introduction

Salesforce Apex allows developers to perform multiple database operations within a single transaction. However, what happens when one operation fails after several records have already been processed?

This is where Apex Transaction Savepoints become useful.

Savepoints allow developers to mark a specific point in a transaction and roll back database changes made after that point.

They are especially useful when working with complex business processes involving multiple DML operations.

In this blog, we’ll explore Apex Savepoints, how they work, their syntax, practical examples, limitations, and best practices.

What Is a Savepoint in Salesforce Apex?

A Savepoint is a marker within an Apex transaction that allows developers to restore the database state to an earlier point in that transaction.

In Salesforce, developers create savepoints using:

Database.setSavepoint()

To restore the database state to a previously created savepoint, they use:

Database.rollback(savepoint)

These methods provide greater control over transaction behavior.

Simple Example

Imagine an application performing three operations:

  1. Create an Account.
  2. Create a Contact.
  3. Create an Opportunity.

If the Opportunity operation fails, the developer may want to undo the Account and Contact creation.

A savepoint can help roll back these database changes when the application detects a failure.

Understanding Apex Transactions

An Apex transaction is a unit of work that contains operations executed together.

Salesforce generally commits successful database changes when the transaction completes.

If an unhandled exception causes the transaction to fail, Salesforce rolls back its database changes.

However, developers sometimes need more precise control over which changes are undone.

Savepoints provide this flexibility.

Without Savepoints

If an exception is handled and the transaction continues successfully, earlier DML operations can remain committed.

With Savepoints

Developers can explicitly roll back database changes made after a particular savepoint, even when the exception is caught.

This is an important difference when designing reliable business processes.

Syntax of Apex Savepoint and Rollback

Creating a Savepoint

Savepoint sp = Database.setSavepoint();

This creates a savepoint within the current Apex transaction.

Rolling Back to a Savepoint

Database.rollback(sp);

This restores the transaction’s database state to the specified savepoint.

Important: A rollback reverses database changes made after the savepoint. It does not restart Apex execution or automatically restore every in-memory variable.

Practical Example: Savepoint and Rollback in Apex

Consider a scenario where a developer needs to create an Account and its related Contact.

If the Contact creation fails, the Account should not remain in the database.

Savepoint sp = Database.setSavepoint();

try {
    Account acc = new Account(
        Name = 'ABC Technologies'
    );
    insert acc;

    Contact con = new Contact(
        LastName = 'Sharma',
        AccountId = acc.Id
    );
    insert con;

} catch (DmlException e) {
    Database.rollback(sp);
    System.debug('Transaction rolled back: ' + e.getMessage());
}

How This Code Works

Step 1: A savepoint is created before inserting any records.

Step 2: Salesforce attempts to insert the Account.

Step 3: Salesforce attempts to insert the related Contact.

Step 4: If a DML exception occurs, the catch block executes.

Step 5: Database.rollback(sp) reverses database changes made after the savepoint.

Step 6: The error is logged using System.debug().

If both operations succeed, the transaction can complete normally.

Real-World Example: Order Processing

Imagine an order-processing system where an Apex service must:

  • Create an Order.
  • Create related Order Items.
  • Update inventory information.

If one of the required operations fails, the system may need to reverse the changes to maintain data consistency.

Example Transaction Flow

Start Transaction
       |
Create Savepoint
       |
Create Order
       |
Create Order Items
       |
Update Inventory
       |
   Any Error?
    /     \
  Yes      No
   |        |
Rollback   Complete
   |        |
Handle     Commit at
Error      Transaction End

Savepoints help ensure that related database operations can be treated as one logical unit of work.

Multiple Savepoints in Apex

Apex supports creating multiple savepoints within a transaction, subject to platform limits.

This allows developers to establish different rollback points.

Example

Account acc = new Account(Name = 'First Account');
insert acc;

Savepoint sp1 = Database.setSavepoint();

Account acc2 = new Account(Name = 'Second Account');
insert acc2;

Savepoint sp2 = Database.setSavepoint();

Account acc3 = new Account(Name = 'Third Account');
insert acc3;

Database.rollback(sp2);

Result

After rolling back to sp2:

  • First Account remains part of the transaction.
  • Second Account remains part of the transaction.
  • Third Account insertion is rolled back.

The remaining changes are committed only if the transaction completes successfully.

Rolling back to an earlier savepoint can also invalidate savepoints created after it.

Savepoint vs Automatic Transaction Rollback

Feature Savepoint Rollback Automatic Rollback
Trigger Explicit developer action Transaction failure
Method Database.rollback() Platform-managed
Scope Changes after selected savepoint Entire failed transaction
Control Developer chooses rollback point Controlled by transaction outcome
Common Use Recover from handled errors Unhandled exceptions

Key Difference: Savepoints allow developers to control rollback behavior within a transaction, while automatic rollback occurs when the transaction fails.

Savepoint vs Database.insert with AllOrNone

Salesforce also provides partial-success DML operations.

For example:

Database.SaveResult[] results =
    Database.insert(accountList, false);

Using false for allOrNone allows valid records to succeed even when some records fail.

However, this does not provide the same functionality as savepoints.

Key Differences

Feature Savepoint Database.insert(records, false)
Purpose Restore earlier transaction state Allow partial DML success
Scope Multiple database operations Specific DML operation
Rollback Control Explicit rollback Per-record success or failure
Best For Related operations requiring consistency Independent records in bulk operations

Developers should choose the approach based on business requirements.

Important Limitations of Apex Savepoints

1. Savepoints Work Within the Current Transaction

A savepoint cannot roll back changes committed by a previous transaction.

2. Savepoint Operations Affect Governor Limits

Creating savepoints and performing rollbacks count toward applicable DML statement limits.

Developers should avoid unnecessary savepoint operations.

3. Rollback Does Not Reset Governor Limits

If an Apex transaction consumes SOQL queries, CPU time, or DML statements, rolling back database changes does not restore those consumed limits.

4. Rollback Does Not Reverse External Side Effects

Savepoints control database transaction state.

They do not undo external operations that have already occurred outside Salesforce.

5. In-Memory Objects Are Not Automatically Restored

After a rollback, Apex variables and sObject instances may still contain values assigned during the rolled-back operations.

For example, an sObject may retain an ID assigned during an insert even though the record was rolled back.

6. Callout Restrictions Require Care

Uncommitted database work can prevent HTTP callouts.

Salesforce provides savepoint-related methods such as Database.releaseSavepoint() in supported API versions, but developers must follow the platform’s transaction and callout requirements.

Best Practices for Apex Transaction Savepoints

1. Create Savepoints Before Critical Operations

Place savepoints before a sequence of related DML operations that may need to be reversed.

2. Avoid Unnecessary Savepoints

Savepoints consume transaction resources and should be used only when rollback control is required.

3. Use Proper Exception Handling

Catch expected exceptions and decide whether to roll back, retry, or propagate the error.

4. Keep Transactions Efficient

Avoid excessive database operations and unnecessary processing.

5. Test Rollback Scenarios

Write Apex unit tests that verify whether expected records remain or are removed after rollback.

6. Understand Partial Success

Use partial-success DML for independent records and savepoints when multiple operations must be reversed together.

7. Review Callout Requirements

Plan HTTP callouts carefully when using savepoints, DML operations, and external integrations.

Common Mistakes Developers Should Avoid

  • Creating a savepoint after the operation that needs protection.
  • Assuming rollback restores governor limits.
  • Expecting rollback to reverse external API calls.
  • Using multiple savepoints unnecessarily.
  • Ignoring exceptions after rollback.
  • Assuming all in-memory objects return to their earlier values.
  • Failing to test transaction behavior.

Understanding these mistakes helps developers create more reliable Apex applications.

Frequently Asked Questions (FAQs)

Q1. What is a Savepoint in Salesforce Apex?

A Savepoint is a marker within an Apex transaction that allows developers to roll back database changes made after that marker.

Q2. Which method creates a Savepoint in Apex?

The Database.setSavepoint() method creates a savepoint.

Q3. How do you roll back a Savepoint in Salesforce?

Use Database.rollback(sp), where sp references the savepoint.

Q4. Can Apex have multiple Savepoints?

Yes. Apex supports multiple savepoints within a transaction, subject to applicable platform limits.

Q5. Does rollback restore Salesforce governor limits?

No. Rollback reverses database changes but does not reset consumed governor limits.

Q6. Can Savepoints roll back external API calls?

No. External operations that have already occurred outside the Salesforce transaction are not reversed automatically.

Q7. What is the difference between Savepoint and Rollback?

A Savepoint marks a point in a transaction, while Rollback restores the database state to that point.

Conclusion

Apex Transaction Savepoints provide developers with greater control over database operations in Salesforce.

By using Database.setSavepoint() and Database.rollback(), developers can reverse changes made during a transaction and manage complex business processes more safely.

Savepoints are particularly useful when several related DML operations must succeed together.

However, developers should understand governor limits, transaction boundaries, callout restrictions, and exception handling before implementing them.

Final Takeaway: Use Apex Savepoints when you need controlled rollback of related database operations within a single Salesforce transaction.

Newsletter

Recent Posts

Scroll to Top