Sub topic 9
Designing a retry policy
This chapter assumes you can write an Apex callout, tell a thrown CalloutException from an HTTP error response, and classify failures as retryable or not. It also assumes you know that a retry must be safe to repeat, which means using an idempotency key. Here you combine those pieces into one policy that you can write down, test, and change in one place.
What a policy decides
A retry policy answers four questions:
- Which failures qualify? Only transient ones: timeouts, connection failures, 408, 429, and 5xx.
- How many attempts are allowed in total?
- How long should the code wait between attempts?
- What happens when the attempts run out?
Keep these answers in one class. If the numbers are scattered across callout code, they drift apart and nobody can say what the system actually does.
Cap the attempts
Every retry loop needs a hard limit. Without one, a permanently broken endpoint keeps consuming async capacity forever. Four attempts is a common starting point: the first try plus three retries. Count the first try, so MAX_ATTEMPTS = 4 means at most three retries.
Use increasing delays
Retrying immediately usually hits the same overloaded or unavailable service. Exponential backoff doubles the wait after each failure, which gives the remote system time to recover.
Apex has no sleep, so you cannot pause inside a transaction. Instead you enqueue a new Queueable job with a delay. System.enqueueJob(job, delay) accepts whole minutes from 0 to 10. This has two consequences:
- The smallest useful wait is about a minute. Backoff in seconds is not available this way.
- The cap is 10 minutes. A longer wait needs Scheduled Apex or a platform event, which this chapter does not cover.
Add jitter
If a service fails at 09:00 and 500 jobs all retry exactly 2 minutes later, they arrive together and can knock the service over again. Jitter adds randomness so the retries spread out. A simple form is "equal jitter": wait at least half the backoff, plus a random amount up to the other half.
public with sharing class RetryPolicy {
public static final Integer MAX_ATTEMPTS = 4;
private static final Integer MAX_DELAY_MINUTES = 10;
// attempt is the number of the attempt that just failed (1-based)
public static Boolean shouldRetry(Integer attempt) {
return attempt < MAX_ATTEMPTS;
}
public static Integer delayMinutes(Integer attempt) {
Integer base = Math.min(MAX_DELAY_MINUTES, (Integer) Math.pow(2, attempt - 1));
Integer half = base / 2;
Integer jitter = (Integer) Math.floor(Math.random() * (base - half + 1));
return Math.min(MAX_DELAY_MINUTES, half + jitter);
}
}With this policy the wait after each failed attempt falls in these ranges:
| Failed attempt | Backoff base (minutes) | Actual wait (minutes) |
|---|---|---|
| 1 | 1 | 0 to 1 |
| 2 | 2 | 1 to 2 |
| 3 | 4 | 2 to 4 |
| 4 | none | no retry, handle exhaustion |
The worst case adds up to 7 minutes of waiting before the policy gives up.
Respect Retry-After
Some services send a Retry-After header with a 429 or 503 response. The server knows its own recovery time better than your formula does, so prefer the header when it is present. Convert it to minutes, round up, and cap it at the 10-minute limit.
public static Integer delayFromHeader(HttpResponse res, Integer attempt) {
String header = res.getHeader('Retry-After');
if (header != null && header.isNumeric()) {
Integer seconds = Integer.valueOf(header);
Integer minutes = (Integer) Math.ceil(seconds / 60.0);
return Math.min(10, minutes);
}
return RetryPolicy.delayMinutes(attempt);
}Retry-After can also hold an HTTP date. This sketch handles only the numeric form and falls back to the formula for anything else.
How the pieces fit
The diagram shows one pass through the policy after an attempt.
Pitfalls
- Retrying non-idempotent requests without an idempotency key can create duplicate orders.
- Passing an
attemptvalue that starts at 0 in one place and 1 in another gives the wrong delays. Pick one convention. - Retrying a 400 or 401 never helps. The request itself needs to change.
Exercise
A service returns 429 with the header Retry-After: 150. Using the delayFromHeader method above, how many minutes will the next Queueable job be delayed, and why is a fixed formula a worse choice here?
Show answer
3 minutes. 150 seconds divided by 60 is 2.5, and Math.ceil rounds it up to 3, which is within the 10-minute cap. The formula ignores the server's own recovery estimate, so it might retry too early and get another 429 or wait longer than needed.