Sub topic 2
Synchronous and asynchronous communication
This chapter covers the timing model behind every Salesforce integration pattern. It assumes you know the basic Salesforce data model, can read Apex and JSON, and understand HTTP methods and status codes. Later chapters build request-reply, fire-and-forget, and batch sync on the ideas introduced here.
Why timing is the first design decision
Every integration answers one question before any other: does the sender wait for the result? The answer decides how tightly the two systems are tied together, what the user sees when something is slow, and how failures show up.
- In synchronous communication, the caller sends a message and blocks until it gets a response or a timeout.
- In asynchronous communication, the caller hands the message off and continues. The work completes later, in a different transaction, and the result (if any) comes back by another path.
Neither style is better in general. Each trades one set of problems for another.
Synchronous communication
A synchronous call keeps the caller's thread open. In Apex, Http.send() does not return until the remote system answers or the timeout expires. The caller can use the response immediately, for example to show a value on a screen or to decide whether to save a record.
Strengths
- The caller gets an answer right away and can act on it in the same transaction.
- The flow is easy to reason about. Success and failure arrive in the same place.
- The caller knows at once if the remote system rejected the request.
Costs
- Temporal coupling. Both systems must be available at the same moment. If the remote system is down, the call fails now.
- Latency is shared. The caller is only as fast as the slowest system in the chain.
- Limits apply to the waiting. Salesforce caps the time and number of callouts per transaction. A slow endpoint can use up the allowed time.
- Failure propagates. An error in the remote system becomes an error for your user or your process.
Callout timeouts
Apex lets you set a timeout per request with setTimeout, in milliseconds. The default is 10 seconds and the maximum is 120 seconds. A long timeout does not make a slow system faster. It holds your transaction open longer. Choose a value slightly above the remote system's normal worst case, and handle the timeout as a failure you expect.
public with sharing class QuoteClient {
public static Decimal fetchPrice(String sku) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Pricing_API/prices/' + EncodingUtil.urlEncode(sku, 'UTF-8'));
req.setMethod('GET');
req.setTimeout(5000);
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (Decimal) body.get('price');
}
throw new CalloutException('Pricing API returned ' + res.getStatusCode());
} catch (System.CalloutException e) {
// Covers timeouts and connection errors as well as the status check above.
System.debug(LoggingLevel.ERROR, 'Price lookup failed: ' + e.getMessage());
throw e;
}
}
}This example uses a Named Credential called Pricing_API, which a later chapter covers. The point here is the shape: the code waits, then branches on the outcome.
Asynchronous communication
An asynchronous exchange separates sending from processing. The sender passes the message to something that holds it, such as an event bus, a queue, or a job, and returns. A receiver picks the message up later.
Strengths
- Loose coupling. The sender does not need the receiver to be online. The message waits.
- Better user experience. The user does not wait for a slow remote system.
- Load smoothing. A burst of messages can be processed at the receiver's pace.
- Isolation of failure. A receiver error does not roll back the sender's transaction.
Costs
- No immediate answer. The sender cannot use a result in the same transaction. If it needs one, you need a second message or a polling step.
- Eventual consistency. For a time, the two systems disagree about the state of the data.
- Harder failure handling. Errors surface later and elsewhere. You must plan for logging, retries, and replay.
- Duplicates and ordering. Most asynchronous delivery is at-least-once. The same message can arrive twice, and messages can arrive out of order.
Two kinds of asynchronous
The word "asynchronous" covers two different mechanisms, and mixing them up leads to wrong designs.
- Asynchronous within Salesforce. You move work out of the current transaction using Queueable Apex, Batch Apex,
@futuremethods, or Scheduled Apex. The work still runs on Salesforce, and it can make callouts from its own transaction. This changes when the call happens. The call is still a request-reply call once it runs. - Asynchronous between systems. You publish a message, such as a platform event, and one or more subscribers handle it independently. The publisher does not wait for them and often does not know who they are.
A request-reply call made from a Queueable job is "async" from the user's point of view but synchronous from the point of view of the job, which still waits for the response.
Comparing the two styles
| Concern | Synchronous | Asynchronous |
|---|---|---|
| Caller waits | Yes, until response or timeout | No, returns after hand-off |
| Response available in same transaction | Yes | No |
| Coupling in time | Tight, both must be up | Loose, the message waits |
| Failure of remote system | Caller sees it immediately | Caller may never see it |
| Consistency | Immediate | Eventual |
| Delivery risk | Retry may repeat a request | Duplicates and reordering are normal |
| Best for | Lookups, validation, user-facing answers | Notifications, propagation, bulk movement |
How the two flows differ in time
The diagram shows the same business event handled both ways. In the synchronous flow, Salesforce is blocked while the remote system works. In the asynchronous flow, Salesforce finishes first and the remote system acts later.
A decision test: four questions
Use these questions to place a requirement on the spectrum.
- Does the caller need the answer to continue? If a user cannot proceed without the value, such as a live price or an address check, lean synchronous.
- Can the other system be unavailable for a while without harm? If yes, asynchronous removes a failure mode.
- How many messages, and how fast? Large or bursty volumes favor asynchronous or batch movement, because a synchronous call per record consumes limits quickly.
- What is the cost of a stale view? If a few seconds or minutes of disagreement is acceptable, eventual consistency is fine. If not, you need synchronous confirmation.
How this maps onto the three patterns
The three patterns in this tutorial sit at different points on this spectrum.
- Request-reply is synchronous. Salesforce calls out and waits for the answer.
- Fire-and-forget is asynchronous between systems. Salesforce publishes and moves on.
- Batch sync is asynchronous in a different sense. Data moves in volume, on a schedule or on demand, and the job runs on its own timeline.
Later chapters give each pattern its own treatment. For now, keep the axis in mind: who waits, for how long, and what happens when a side is unavailable.
Edge cases and common mistakes
Callouts after uncommitted work
Apex does not allow a callout in a transaction that has uncommitted DML (database changes not yet saved). If you insert a record and then call out, you get a System.CalloutException saying you have uncommitted work pending. Make the callout first, or move it into a separate asynchronous transaction such as Queueable Apex with Database.AllowsCallouts.
Callouts from triggers
A trigger runs inside the transaction that saves the record, and synchronous callouts are not allowed there. Triggers must hand callout work to an asynchronous job. The user's save then completes without waiting for the remote system.
public with sharing class InvoiceSyncJob implements Queueable, Database.AllowsCallouts {
private final Id accountId;
public InvoiceSyncJob(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts/' + accountId);
req.setMethod('GET');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Billing API returned ' + res.getStatusCode());
}
// Process the response here. This runs in its own transaction.
}
}A trigger would call System.enqueueJob(new InvoiceSyncJob(acc.Id)) after it has collected the record IDs. This is asynchronous inside Salesforce, but the job's call is still request-reply.
Retrying a synchronous call blindly
If a call times out, you do not know whether the remote system processed it. Retrying a non-idempotent request, such as a POST that creates an order, can create a duplicate. Retries need idempotency, which a later chapter covers with external IDs.
Treating "accepted" as "processed"
With asynchronous delivery, a success result from the publisher means the platform accepted the message. It does not mean any subscriber handled it. Do not report "done" to a user on that basis.
Hiding latency behind a synchronous call in the UI
A synchronous callout from a user action makes the page wait. If the remote system averages two seconds and sometimes spikes to thirty, your users feel the spikes. Consider whether the user truly needs the answer, or whether showing "processing" and updating later is acceptable.
Putting it together: a worked scenario
A company wants Salesforce to do two things when a sales rep marks an Opportunity as won.
- Show the rep the customer's current credit status from an ERP system before they confirm the deal.
- Tell the warehouse system that a new order exists.
Apply the four questions.
- Credit status. The rep needs the answer to proceed, and a stale value is risky. This is a synchronous lookup. If the ERP is unavailable, the screen shows that the check could not be made, and the rep decides what to do.
- Warehouse notification. The rep does not need a reply. The warehouse can be offline briefly and catch up. Volumes can spike at quarter end. This is asynchronous, with a published event that the warehouse subscribes to.
One business event produces two different timing choices. A single integration design often mixes styles, and the skill is matching each interaction to its own requirement.
Summary of trade-offs
- Choose synchronous when the answer is needed now and the cost of waiting is acceptable.
- Choose asynchronous when the sender should not depend on the receiver's availability or speed.
- Moving work to a Queueable job or
@futuremethod changes when a call runs, not whether it waits for its response. - Asynchronous designs need explicit handling for duplicates, ordering, and failures that appear later.
Exercise
A trigger on Order must send the new order to a shipping system. A developer writes a synchronous callout inside the trigger and gets an error at runtime. Explain why, and describe a fix that keeps the user's save fast.
Show answer
Synchronous callouts are not allowed in a trigger transaction, and a callout after uncommitted DML in the same transaction also raises a CalloutException. The fix is to have the trigger enqueue a Queueable job that implements Database.AllowsCallouts, or to publish a platform event that a subscriber handles. The save then completes without waiting for the shipping system, and the callout runs in its own transaction.
Exercise
A team says their integration is "asynchronous" because a Queueable job calls an external pricing API and waits for the price before updating a record. Is this the asynchronous style described in this chapter? What changes and what stays the same compared with calling from the original transaction?
Show answer
It is asynchronous only inside Salesforce. The job runs later, so the user's transaction does not wait. But the job itself still sends a request and blocks until the response or timeout, so the exchange with the pricing API is still request-reply. The caller is the job instead of the user's transaction, and the failure now appears in the job rather than on the user's screen.
Exercise
You publish a message and the publish result reports success. Which of these can you conclude: (a) the platform accepted the message, (b) a subscriber processed it, (c) the external system's data is now updated? Name one design consequence.
Show answer
Only (a). Asynchronous publishing confirms acceptance, not processing, and the external data may not change until later. A design consequence is that you must not tell the user the work is done based on the publish result, and you need a way to detect and handle failures later, such as logging, retries, or replay.