2

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.

4

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 Jun 18 '15 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 Jun 19 '15 at 2:11
0

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);
       toInsert.add(myRecord);
    }
    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 Jun 19 '15 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.