Since in Salesforce, we are living in a multi-tenant architecture, so calling external services synchronously can create issues if the response is taking too much of time to come due to network latency or complex calculation or long running requests. There can be n number of reasons why the response is taking longer time. To make sure System resources are available to all customers, Salesforce introduces limitation on how much synchronous callout you can do from a single organization. Limit is each org can make a maximum of 10 synchronous requests running for more than 5 seconds. When the limit is reached, any subsequent request will fail until and unless an existing request completes successfully.
Apex continuation is an architectural design which will allow to call long running external web services in a scalable fashion without blocking any server threads and also avoiding Apex concurrency limit. With Apex continuation, you can make asynchronous external web service callout and then continue working on other activities. When the response is available, callback method will take care of that and take actions like – updating some values in object, rendering a section of the visual force page to display the result.
Below code snippet will demonstrate how you can use Continuation object for making Asynchronous callout.
I will be using two external web services for this demo. So you need to add them in your developer org’s Remote Site settings.
- https://my-json-server.typicode.com/suddeb/MyJasonServer
- https://long-running.herokuapp.com/products?latency=6000
Visualforce Page: click here
Apex Controller: click here
Here is the demo – click here
You can learn more about Apex continuation below –
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_Continuation.htm