How do architects manage transaction boundaries and rollback limitations when combining database DML with external callouts?
Answer
Basics: A Salesforce transaction is all-or-nothing for database changes, but an external system's change is outside that transaction. If you save a record then call out and the call fails, you can roll back Salesforce but not the remote system. Worse, Salesforce blocks a callout after DML with the error "You have uncommitted work pending. Please commit or rollback before calling out".
How it works:
- Pattern A: callout first, then DML (works in one transaction if the logic allows it).
- Pattern B: DML commits, then an asynchronous job (Queueable with Database.AllowsCallouts, @future(callout=true), or platform event subscriber) performs the callout and updates status.
- Pattern C: outbox, where the transaction inserts an "outbound message" record; a job processes the outbox and marks it Sent or Failed.
- On failure, apply compensation (a reversing call) or retry with idempotency keys.
Advanced / deep dive: Savepoints and Database.rollback restore only Salesforce data; each setSavepoint and rollback counts as a DML statement toward the 150 limit. Triggers cannot make synchronous callouts, so triggers should enqueue jobs. Platform events default to Publish After Commit, so subscribers only act on committed data; Publish Immediately is not rolled back and is for logging. Distributed consistency uses eventual consistency and a saga: each step has a compensating step. Idempotency keys prevent duplicates when retrying after a timeout. Queueable chaining continues after failure only if you coded it; track attempts and use a dead-letter status. Batch Apex with Database.AllowsCallouts supports callouts per execute, with 100 callouts per execute transaction.
Code / config example:
public , Database.AllowsCallouts {
{
List<Outbox__c> rows = [SELECT Id, Payload__c, Attempts__c FROM Outbox__c
LIMIT ];
(Outbox__c r : rows) {
();
req.setEndpoint(); req.setMethod();
req.setHeader(, r.Id); req.setBody(r.Payload__c);
{ r.Status__c = ().send(req).getStatusCode() < ? : ; }
(CalloutException e) { r.Status__c = ; }
r.Attempts__c = (r.Attempts__c == ? : r.Attempts__c) + ;
}
update rows;
}
}