# How can developers architect a robust dead letter queue or retry pattern for permanently failed asynchronous jobs?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Error Handling

Read it on the site: https://www.forcechallenges.com/interview-questions/how-can-developers-architect-a-robust-dead-letter-queue-or-retry-pattern-for-permanently-failed-asynchronous

## Answer

**Basics:** Salesforce has no built-in dead letter queue for async Apex. If a job fails, the work is simply lost unless you recorded it. A dead letter queue is a place where failed work is stored with its payload and error so someone or something can inspect or replay it.

**How it works:** (1) Wrap work in try/catch and attach a Finalizer to queueables, since a Finalizer runs even when the job dies from an uncatchable limit exception. (2) In the failure path, write a record to a custom object such as `Async_Failure__c` (job type, payload JSON, error message, retry count, status, next retry time). (3) A scheduled job or the Finalizer itself re-enqueues eligible rows. (4) After N attempts mark the row Dead and notify admins by custom notification or email. For batch, use `Database.RaisesPlatformEvents` and a trigger on `BatchApexErrorEvent` to capture the failed scope Ids.

**Advanced / deep dive:** Distinguish transient errors (lock contention, timeouts, 5xx, rate limits) from permanent ones (validation, bad data) and only retry the former. Use exponential backoff with `System.enqueueJob(job, delayMinutes)` (0 to 10 minutes) or scheduled retries for longer waits. Make processing idempotent: use external Ids and upserts, so replays do not duplicate. Because a failing transaction rolls back its own log inserts, write the log from a Finalizer (separate transaction) or via a platform event published immediately. Finalizers can enqueue only a limited number of follow-up jobs and have a cap on consecutive retries of the same job; verify exact numbers in current documentation. Protect against retry storms with a circuit breaker (stop retrying when the downstream system is down). Consider Platform Events with durable replay (retained 72 hours) or an external queue if volumes are high. Index the failure table and archive old rows.

**Code / config example:**
```apex
public class RetryFinalizer implements Finalizer {
    private String payload; private Integer attempt;
    public RetryFinalizer(String payload, Integer attempt) { this.payload = payload; this.attempt = attempt; }
    public void execute(FinalizerContext fc) {
        if (fc.getResult() == ParentJobResult.SUCCESS) return;
        if (attempt < 3) {
            System.enqueueJob(new MyWorkJob(payload, attempt + 1), Math.min(10, attempt * 2)); // backoff
        } else {
            insert new Async_Failure__c(Payload__c = payload, Status__c = 'Dead',
                Error__c = String.valueOf(fc.getException()).left(1000));
        }
    }
}
// In MyWorkJob.execute: System.attachFinalizer(new RetryFinalizer(payload, attempt));
```

**Hidden gotchas & must-remember points:**
- Logs inserted in the failing transaction roll back with it; log from a Finalizer or an immediately published event.
- Uncatchable limit exceptions bypass try/catch but still trigger Finalizers and `BatchApexErrorEvent`.
- Retrying permanent failures forever wastes async quota.
- Replays must be idempotent.
- Delay is only 0 to 10 minutes per enqueue; use scheduled jobs for longer waits.
- Finalizer retry counts are capped; verify in current release notes.

**Best practice:** Log every failure with its payload, retry only transient errors with backoff and a cap, and alert on dead items.

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