Apex Callouts, Integration Resilience & Recovery
A longer Apex callout timeout is not resilience
The timeout disappeared; the failure moved
A pricing integration sometimes takes 14 seconds, so a team raises its Apex callout timeout from ten seconds to 60. Timeout errors fall, but sales users now stare at a blocked screen, duplicate submissions appear after impatient retries and a remote outage consumes one Salesforce transaction after another. The setting changed. The dependency did not become more reliable.
The JSBC Labs position is that a longer Apex callout timeout is not resilience. A timeout is the maximum waiting period inside one interaction; it does not provide safe retry, load protection, duplicate prevention, outcome certainty or recovery. Treat every callout as a distributed business operation with an explicit latency budget, failure classification, idempotency rule and reconciliation path. Increase a timeout only when measured normal behaviour and the user journey justify the wait—not because the error is inconvenient.
Choose the interaction pattern before writing HttpRequest
Salesforce Architects distinguishes synchronous request-reply from asynchronous fire-and-forget. Use request-reply when the user or transaction genuinely needs the remote answer before it can continue: validating a payment token, calculating a price that must be shown now or reserving scarce inventory. Use an asynchronous boundary when Salesforce can record intent, return control and process the remote outcome later. Near-real-time is often operationally safer than pretending every dependency is local.
Define the business deadline separately from the technical ceiling. A user-facing quote might need a response within three seconds even though Apex can wait much longer. A fulfilment instruction may be acceptable within five minutes and should not occupy an interactive transaction at all. State what the caller sees on success, timeout, rejection and unknown outcome. If the business cannot explain what happens while the remote system is slow, the integration pattern is incomplete.
Use timeout as a latency budget—not a tuning escape
Salesforce documents a ten-second default timeout for Apex callouts, a configurable per-call range up to 120 seconds, and a maximum cumulative callout timeout of 120 seconds in one transaction. A transaction can make up to 100 callouts, but that numerical allowance does not make a long sequence operationally sensible. Cumulative wait, response parsing, Apex work and the user's tolerance all constrain the real budget.
Set each timeout from measured percentiles and business value. Reserve time for Salesforce to validate the response, perform permitted DML and return a meaningful result. Split independent requests only when concurrency and remote capacity support it. Salesforce recommends Continuations for long-running UI callouts because they improve the user experience and can run requests in parallel; they do not make a slow dependency healthy, and regular callout time has already been excluded from the long-running request limit since Winter '20.
Classify failure before deciding to retry
A timeout is ambiguous: the remote operation may have failed, may still be running or may have succeeded while its response was lost. Authentication failures, invalid payloads, business rejections, rate limits, connection failures and server errors require different treatment. Retrying every exception turns permanent defects into extra load and can repeat successful writes. Returning every failure as ‘try again’ transfers integration risk to users.
Create a small failure taxonomy in the integration contract. Treat invalid requests and most client errors as non-retryable until data or configuration changes. Respect a `Retry-After` instruction for rate limiting. Retry transient connection and server failures only when the operation is safe, with bounded attempts, increasing delay and jitter. Record the endpoint, operation, correlation ID, attempt, category and safe response metadata. Never log credentials, authorization headers or sensitive payloads.
Idempotency makes retry a controlled operation
A retry is a second business request, even when the code line is identical. Salesforce's integration guidance warns that repeated invocations without idempotency can create duplicate records and transactions. For every remote write, generate a stable request key before the first attempt and reuse it for every retry. The receiving system should return the existing outcome for that key rather than performing the operation again.
Use a Salesforce business identifier or dedicated operation ID, not a timestamp created per attempt. Persist request state such as prepared, submitted, confirmed, failed or unknown, with the last response and next eligible attempt. If the external API cannot support idempotency, place a controlled integration service in front of it or remove automatic retry. A network timeout after a non-idempotent payment request must enter reconciliation, not blind replay.
Remote success and Salesforce commit are separate facts
Salesforce prevents callouts after pending uncommitted work in the same transaction. Making the callout first avoids that platform error, but it creates another distributed-systems edge: the remote write can succeed and a later Salesforce DML operation can fail. No Apex transaction can atomically commit both systems. A savepoint does not roll back work already completed by an external service.
Model the gap explicitly. For synchronous work, persist only after a validated remote response and design reconciliation for remote-success/local-failure. For asynchronous work, create a durable Salesforce intent before a separate transaction performs the callout, then update the outcome with idempotent state transitions. Do not mark a business process complete merely because the endpoint returned HTTP 200; verify the response semantics, local commit and any downstream hand-off required by the process.
Protect both systems during an outage
When an endpoint is failing, immediate retries from every transaction amplify the outage. Salesforce Well-Architected specifically flags the absence of a circuit breaker when external failures leave transactions waiting for the full timeout. The JSBC Labs recommendation is to stop calling temporarily after a measured threshold, return a controlled unavailable state and probe recovery with a small number of requests instead of using production traffic as the health check.
Add bulkheads around each dependency: bounded queues, maximum concurrent work, per-tenant or per-service rate limits and an operator-controlled pause. Give asynchronous retries a cap and a dead-letter or exception queue with an accountable owner. Monitor latency percentiles, timeout rate, retry volume, circuit state, oldest pending request and reconciliation age. A healthy integration is not one that never fails; it is one whose failure remains contained, visible and recoverable.
Test degraded behaviour—not only mocked success
Salesforce supports `HttpCalloutMock` and `Test.setMock()` for deterministic Apex tests. Use them to simulate timeouts, malformed bodies, authentication errors, rate limits, duplicate acknowledgements, partial responses and server failures—not only a perfect 200 response. Assert the classification, retry decision, idempotency key, persisted state and user-safe error. Test that a second attempt cannot create a second business outcome.
Mocks prove the Salesforce decision logic, not the real endpoint, network or credentials. Add contract tests against a controlled provider environment, production-scale latency tests and operational drills that disable the dependency. Verify dashboards, circuit transitions, queued recovery and reconciliation. Named Credentials should manage endpoint and authentication configuration, but they do not supply the missing resilience contract. The goal is not a callout that waits long enough to succeed; it is a business operation that remains correct when the response is slow, lost or uncertain.
Official references
- Salesforce Developers — Callout Limits and Limitations
- Salesforce Developers — Apex Governor Limits
- Salesforce Developers — Make Long-Running Callouts with Continuations
- Salesforce Developers — Named Credentials as Callout Endpoints
- Salesforce Architects — Integration Patterns
- Salesforce Architects — Reliability: Availability and Performance Patterns
- Salesforce Architects — Reliability
- Salesforce Developers — Testing HTTP Callouts
- Salesforce Developers — Apex Transaction Control