# What robust error handling and retry strategies should architects implement for mission-critical inbound integrations?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Error Handling, Retry Mechanisms

Read it on the site: https://www.forcechallenges.com/interview-questions/what-robust-error-handling-and-retry-strategies-should-architects-implement-for-mission-critical-inbound

## Answer

**Basics:** Integrations fail: timeouts, 5xx errors, rate limits, record locks, bad data. Without a strategy, data silently disappears or duplicates. Inbound means external systems calling Salesforce (Apex REST, REST API, Platform Event subscribers), so you control the response; outbound retries are the caller's job.

**How it works:**
1. Validate input early and return precise status codes: 400 or 422 for bad data (not retryable), 409 for conflicts, 429 or 503 with `Retry-After` for throttling, 500 for unexpected errors.
2. Catch exceptions, and write the failed payload, error and correlation ID to an error object (for example `Integration_Error__c`).
3. Callers retry only on retryable codes (REQUEST_LIMIT_EXCEEDED, UNABLE_TO_LOCK_ROW, 5xx, timeouts) using exponential backoff with jitter.
4. After N attempts, park the message for manual review (dead-letter) and notify.
5. Operations must be idempotent so retries are safe.

**Advanced / deep dive:** Apex has no sleep, so implement delay using Queueable chaining with `System.enqueueJob(job, delayMinutes)` (0 to 10 minutes) or scheduled Apex. A critical trap: if the transaction fails, your error-log DML rolls back too. Log through a **Platform Event with Publish Immediately** behavior or from a separate Queueable, or capture the error with `Database` partial-save methods so the transaction still commits. For batch inbound loads use `Database.insert(records, false)` and process `SaveResult`. Platform event triggers can retry with `EventBus.RetryableException`, which re-delivers the batch up to the limit (verify the current count). Add a circuit breaker so you stop hammering a failing endpoint, monitor with dashboards, and alert via custom notifications, email or Slack.

**Code / config example:**
```apex
public class RetryCallout implements Queueable, Database.AllowsCallouts {
    private String body; private Integer attempt;
    private static final Integer MAX_ATTEMPTS = 5;
    public RetryCallout(String body, Integer attempt) { this.body = body; this.attempt = attempt; }
    public void execute(QueueableContext qc) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:ERP_NC/orders'); req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json'); req.setBody(body);
        try {
            HttpResponse res = new Http().send(req);
            Integer sc = res.getStatusCode();
            if (sc >= 200 && sc < 300) return;
            if ((sc == 429 || sc >= 500) && attempt < MAX_ATTEMPTS) {
                Integer delay = Math.min(10, (Integer) Math.pow(2, attempt)); // minutes
                System.enqueueJob(new RetryCallout(body, attempt + 1), delay);
            } else {
                insert new Integration_Error__c(Payload__c = body, Status_Code__c = sc);
            }
        } catch (CalloutException e) {
            if (attempt < MAX_ATTEMPTS) System.enqueueJob(new RetryCallout(body, attempt + 1), 1);
            else insert new Integration_Error__c(Payload__c = body, Message__c = e.getMessage());
        }
    }
}
```

**Hidden gotchas & must-remember points:**
- Error-log records inserted before an unhandled exception are rolled back.
- Do not retry permanent errors (validation failures); you will loop forever.
- The delay in `System.enqueueJob` is capped at 10 minutes.
- Retries without idempotency create duplicates.
- Locking errors are transient; serialize or reorder loads.
- Long text fields for payloads can hit size limits; truncate or store as files.

**Best practice:** Separate retryable from permanent errors, make everything idempotent, bound retries, and always keep a reviewable dead-letter record with alerting.

---
Source: ForceChallenges · last updated 2026-11-02
