I am making a callout and then trying to insert the data and then immediately I make another callout followed by insert operation. This process continues for users matching my criteria. How to avoid below exception?

I know that its not allowed to do a callout and a DML in series. But as per the requirement I need to follow this process.

System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

Note: I cannot use future method since I am running this process in a batch class.

2 Answers 2


Batch Size of 1

Database.executeBatch(myClass, 1);

This will let you perform a callout per record. It'll be kind of slow though (~3 seconds per record).

Callout First

Perform all callouts (up to 100) first, then perform one batch update. You'll want to do this anyways to avoid other governor limits like query limits, dml limits, or timeout limits.

  • Thanks for the reply, it works as expected. I have another question, what if there are 10000 batches, will this work or will it require something else?
    – Sriram Lns
    Commented Jun 18, 2015 at 23:29
  • @SriramLns Sure, you can have up to 250,000 calls per day (shared between future methods, batches, and queuable). You'll have a decently hard time trying to reach that limit.
    – sfdcfox
    Commented Jun 19, 2015 at 2:11

The better design would be to do the following:

  1. Loop through qualified users, making a callout for each one
  2. Create records with response from callout.
  3. update create records

    List<MyRecord__c> toInsert = new List<MyRecord__c>();
    for(User u : users){
       String resp = makeCallout(u);
       MyRecord__c myRecord = createRecordFromResponse(resp);
    insert toInsert;

I believe you can have up to 100 callouts in a single execution context so you'll want to execute the batch class like so: Database.executeBatch(myClass, 100);

It would be even better if the webservice was bulkified but with third party systems, this often isn't an option.

  • your solution also makes sense but only thing that I am worried is that what if after 100 batches I get any exception like Apex CPU time limit exceeded. What will happen to the un-inserted records?
    – Sriram Lns
    Commented Jun 19, 2015 at 14:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .