How do asynchronous Apex callouts prevent user interface blocking during long-running external web service requests?
Answer
Basics: A synchronous callout holds the user's save or page load open until the remote service answers, up to the callout timeout. Triggers also cannot make callouts synchronously. Async Apex queues work to run later in its own transaction. Note that async here means background execution after the user transaction commits; the UI does not wait.
How it works:
- The trigger or controller collects the record IDs and enqueues a job.
- The user's transaction commits and returns.
- Salesforce runs the job in a new transaction with its own limits (async CPU 60,000 ms, heap 12 MB).
- The job re-queries current data, makes the callout, and writes the result back.
- Failures are logged and optionally retried.
Advanced / deep dive: Options compared. @future(callout=true): simple, static method, parameters must be primitives or collections of primitives, max 50 per transaction, cannot chain or be called from a future or batch. Queueable: accepts complex types, returns a job ID, can chain (only one child job from a running queueable; chain depth unlimited in production, 5 in Developer Edition/trials), up to 50 enqueued per synchronous transaction. Batch with Database.AllowsCallouts suits large volumes (each execute has up to 100 callouts). Continuation (Visualforce or @AuraEnabled(continuation=true) for Lightning) makes long-running callouts without holding an Apex thread, with up to 3 callouts per continuation. Remember the callout limits: 100 per transaction and 120 seconds cumulative. Async execution is subject to the org's 24-hour async allocation (250,000 or licenses times 200, whichever is greater). Use a Platform Event as an alternative decoupling mechanism where the subscriber does the callout.