# What error handling and idempotency strategies ensure robust processing of replayed streaming event messages?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Event Error Handling, Idempotent Consumers

Read it on the site: https://www.forcechallenges.com/interview-questions/what-error-handling-and-idempotency-strategies-ensure-robust-processing-of-replayed-streaming-event-messages

## Answer

**Basics:** Events can be delivered more than once (retries, reconnects, replay from an older ReplayId). If handling an event twice creates two orders, you have a bug. Idempotency means processing the same event repeatedly yields the same final state.

**How it works:**
1. Each event carries `ReplayId` (ordered, not guaranteed contiguous) and `EventUuid` (unique per event). Use EventUuid, or a business key from the payload, as the dedupe key.
2. Write results with **upsert on an External ID** so duplicates overwrite rather than insert.
3. In an Apex trigger subscriber, throw `EventBus.RetryableException` to have the platform redeliver the batch (documented retry cap is limited, around nine retries; verify), and call `EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId)` to record progress so a retry resumes after processed events.
4. On permanent failure, write the payload and error to an error log object (your own "dead letter") for manual or scheduled replay.
5. Handle ordering: use sequence numbers or timestamps and ignore stale updates.

**Advanced / deep dive:** Trigger batches may be up to 2,000 events. After retries are exhausted, the failed batch is not redelivered automatically, so your log is the only safety net. Trigger suspension can occur on repeated unhandled failures; resume from Setup > Platform Event triggers. External subscribers (Pub/Sub API, CometD) must persist the last committed ReplayId themselves. Events outside the 72-hour retention window cannot be replayed (version-dependent, verify). For fan-out, keep each trigger cheap and push heavy work to Queueable.

**Code / config example:**
```apex
trigger OrderEventTrigger on Order_Event__e (after insert) {
    Set<String> keys = new Set<String>();
    for (Order_Event__e e : Trigger.new) keys.add(e.Order_Key__c);
    Map<String, Order__c> existing = new Map<String, Order__c>();
    for (Order__c o : [SELECT Order_Key__c, Last_Event_Uuid__c FROM Order__c WHERE Order_Key__c IN :keys])
        existing.put(o.Order_Key__c, o);
    List<Order__c> upserts = new List<Order__c>();
    for (Order_Event__e e : Trigger.new) {
        Order__c o = existing.get(e.Order_Key__c);
        if (o != null && o.Last_Event_Uuid__c == e.EventUuid) continue; // already processed
        upserts.add(new Order__c(Order_Key__c = e.Order_Key__c, Status__c = e.Status__c, Last_Event_Uuid__c = e.EventUuid));
    }
    try { upsert upserts Order__c.Order_Key__c; }
    catch (DmlException ex) { throw new EventBus.RetryableException(ex.getMessage()); }
}
```

**Hidden gotchas & must-remember points:**
- Delivery is at-least-once; duplicates are normal.
- ReplayId gaps are normal; never rely on contiguity.
- There is no native dead-letter queue; build one.
- RetryableException retries are limited; plan for final failure.
- Retry in a trigger redelivers the batch, so partial work must be idempotent.
- Replay is limited to the retention window (72 hours).

**Best practice:** Dedupe by EventUuid or business key, upsert by External ID, checkpoint, and log permanent failures for replay.

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