Retrying Failed Callouts in Salesforce Apex: Best Practices with Code Snippet

In Salesforce Apex, callouts are used to communicate with external systems and APIs. However, callouts can sometimes fail due to network issues or API errors, leading to errors in your Apex code. To improve reliability and error handling, it's vital to implement retry logic for failed callouts.

In this blog post, we'll discuss best practices for retrying failed callouts in Salesforce Apex and provide code snippets to help you get started.

Best Practices for Retrying Failed Callouts

  1. Set a maximum number of retries: Limiting the number of times you retry a failed callout is important to avoid infinite loops and excessive API usage. We recommend setting a maximum number of retries, such as three or five.
  2. Add a delay between retries: Adding a delay between retries can help prevent overloading the external system or API and improve the chances of success on the next attempt. We recommend a delay of at least five seconds.
  3. Catch-specific exceptions: When catching exceptions during a callout, it's important to catch specific exceptions rather than general exceptions. For example, you can catch System.CalloutException for general callout exceptions or System.HttpException for HTTP-specific exceptions.
  4. Implement exponential backoff: Exponential backoff is a retry strategy that increases the delay between retries exponentially with each retry attempt. This strategy can help reduce API usage and improve the chances of success on subsequent retries.

Code Snippet for Retrying Failed Callouts

Here's a code snippet that demonstrates how to implement retry logic for failed callouts in Salesforce Apex:

public class makeCallout {
    
    public static HttpResponse makeCallout(String url, String method, String body) {
        HttpRequest request = new HttpRequest();
        request.setEndpoint(url);
        request.setMethod(method);
        request.setBody(body);
        
        Integer numAttempts = 3; // Maximum number of retry attempts
        Integer delayMillis = 5000; // Delay in milliseconds between attempts
        
        while (numAttempts > 0) {
            try {
                Http http = new Http();
                HttpResponse response = http.send(request);
                if (response.getStatusCode() >= 200 && response.getStatusCode() < 300) {
                    // Callout was successful, return response
                    return response;
                }
                // Callout was not successful, decrement attempts and retry
                numAttempts--;
            } catch (Exception ex) {
                // An exception occurred during the callout, decrement attempts and retry
                numAttempts--;
            }
        }
        // Maximum number of retry attempts reached, return null
        return null;
    }    
}

In this example, we set a maximum of three retry attempts with a five-second delay between attempts. We also implement exponential backoff by doubling the delay between each retry attempt. Finally, we catch System.CalloutException and retry the callout if an exception occurs.

Conclusion

Implementing retry logic for failed callouts is essential for improving reliability and error handling in Salesforce Apex. By setting a maximum number of retries, adding a delay between retries, catching specific exceptions, and implementing exponential backoff, you can improve the chances of success on subsequent retries and reduce API usage. Use the code snippet provided in this post to get started with retrying failed callouts in Salesforce Apex.