[SalesForce] Future Method: Too many future calls : 51

Working on a future method to post values to external web service. But since there is a limit of 50 callouts per invocation, I am getting error "Too many future calls : 51". Cases are loaded into salesforce from external ETL in bulk. So is there a way to workaround this error.

Class

public with sharing class caseTrigger {  
   //method invoked by trigger after insert
    public void CaseInsert(List<Case> caseIns){
          list<Id> caseIds = new list<id>();
            List<Case> caseList = [Select id from case WHERE Id IN :caseIds];
                for(Case c : caseList){
                    if(c.Status != 'closed'){
                        caseIds.add(c.id);
                    }         
                if(f.caseId_User.size()>0){PostCases(caseIds);}
     }
    //postCases (future method)
    @future(callout = true)
    public static void PostCases(List<Id> Ids){
        //prepare Json to post to webservice
   }
}

Best Answer

Use a batch job rather than starting the future method directly from the trigger.

I.e.

  1. Trigger fires, and starts/queues the batch job to process the new cases that were just inserted. The batch job should support callouts (Database.AllowsCallouts).
  2. The batch jobs execute method is called with the Case details for the newly inserted records.
  3. The execute method performs the required callout.

If the number of transactions inserting cases becomes significant you might be better of with a non-trigger based sync process. The common approach here is to have a scheduled job start a batch at some interval. The batch job will run using a SOQL query that indicates the Cases that still need to be processed. You would need to determine a mechanism to identify the Cases that still need to be processed. This could be as simple as a checkbox custom field on the Cases that gets flagged once the sync is complete.

Related Topic