Sub topic 8
Making repeated requests safe
This chapter assumes you can write a basic Queueable job, you know the HTTP status codes, and you have read the earlier chapters on telling exceptions from error responses and on classifying retryable errors.
Why a retry can do harm
A retry is a second request. Suppose your callout creates an order and the read times out. Your code sees a CalloutException. It does not know whether the server never received the request, received it and failed, or processed it and was too slow to answer.
If the server did create the order and you retry, you now have two orders. A timeout is an ambiguous result, and retrying an ambiguous result is only safe when the operation is idempotent.
What idempotent means
An operation is idempotent if running it several times leaves the system in the same state as running it once. Reading a record is idempotent. Setting a status to Shipped is too. Creating a new record or adding to a balance is not.
HTTP methods carry different expectations:
| Method | Idempotent by definition | Safe to retry blindly |
|---|---|---|
| GET | Yes | Yes |
| PUT | Yes | Usually, if it replaces the whole resource |
| DELETE | Yes | Yes, but a repeat may return 404 |
| POST | No | No, unless the API supports an idempotency key |
These are conventions from the HTTP specification. A badly written API can break them, so check the API documentation before relying on them.
Using an idempotency key
An idempotency key is a unique value you send with a request. The server stores the key together with the result of the first request that used it. If the same key arrives again, the server returns the stored result and does not repeat the work.
Many payment and order APIs accept the key in a header named Idempotency-Key. The server must implement this feature. Sending the header to an API that ignores it protects nothing.
Two rules make the key work:
- Generate the key once, before the first attempt.
- Reuse the same key on every retry of that request.
A key generated inside execute would change on every attempt and defeat the purpose. A key must also be unique per logical request. Reusing one key for two different orders makes the server treat the second order as a repeat.
Carrying the key through retries
The RetryableCallout job from the previous chapter needs one new field. The public constructor creates the key. The private constructor passes it along when the job re-enqueues itself.
public class RetryableCallout implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 4;
private final String payload;
private final String idempotencyKey;
private final Integer attempt;
// Entry point: called once per logical request
public RetryableCallout(String payload) {
this(payload, UUID.randomUUID().toString(), 1);
}
private RetryableCallout(String payload, String idempotencyKey, Integer attempt) {
this.payload = payload;
this.idempotencyKey = idempotencyKey;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', idempotencyKey);
req.setBody(payload);
req.setTimeout(30000);
try {
Integer code = new Http().send(req).getStatusCode();
if (code >= 200 && code < 300) {
return;
}
if (!(code == 408 || code == 429 || (code >= 500 && code <= 599))) {
System.debug(LoggingLevel.ERROR, 'Permanent failure: ' + code);
return;
}
} catch (System.CalloutException e) {
System.debug(LoggingLevel.WARN, 'Transient failure: ' + e.getMessage());
}
retryLater();
}
private void retryLater() {
if (attempt >= MAX_ATTEMPTS) {
System.debug(LoggingLevel.ERROR, 'Retries exhausted for key ' + idempotencyKey);
return;
}
Integer delayMinutes = Math.min(10, (Integer) Math.pow(2, attempt - 1));
System.enqueueJob(
new RetryableCallout(payload, idempotencyKey, attempt + 1),
delayMinutes
);
}
}You start a request with System.enqueueJob(new RetryableCallout(json));. Every attempt for that request now sends the same Idempotency-Key.
The diagram shows the ambiguous timeout case. The server processes the first request, the response is lost, and the retry gets the stored result.
Other ways to stay safe
Not every API supports keys. You have other options:
- Use an external ID. Upserting by an external ID, such as an order number you generate, makes a repeat update the same record.
- Check before you create. Query the remote system for your reference value before retrying a POST. This costs an extra callout against your limits and still leaves a small race window.
- Store the key with the data. Save the key in a field on the Salesforce record, so a replay after exhausted retries reuses it.
Exercise
A teammate moves UUID.randomUUID().toString() into the execute method, so each attempt builds its own key. What goes wrong, and in which situation does the bug show up?
Show answer
Each retry sends a different key, so the server treats it as a new request. The bug shows up when a request times out after the server already processed it. The retry then creates a duplicate record, because the server cannot match it to the first attempt. The key must be generated once, before the first attempt, and passed to every retry.