How do ReplayID values ensure reliable message replaying and fault recovery during event subscriber disconnects?
Answer
Basics: Subscribers disconnect for many reasons: deployments, network issues, outages. ReplayId is the bookmark. When subscribing you choose a replay option: -1 means only new events from now (the tip), -2 means all events still stored, and a specific number means events after that ID.
How it works:
- The event bus assigns each event a ReplayId (ascending, not necessarily contiguous).
- The client processes the event, then durably stores its ReplayId (database, not memory).
- After a disconnect, the client resubscribes with the stored ReplayId.
- Salesforce replays retained events with a higher ReplayId, then continues live. In Pub/Sub API the equivalents are replay presets LATEST, EARLIEST and CUSTOM (with a replay_id).
Advanced / deep dive: Retention: high-volume platform events and Change Data Capture events are retained for 72 hours; PushTopic and Generic Streaming events for 24 hours; legacy standard-volume platform events also had 24 hours (retiring; verify against your release). Anything older is gone, so a subscriber down longer than the window must reconcile by querying the source data. Semantics are at-least-once: a crash between processing and saving the ReplayId produces duplicates on resume, so processing must be idempotent. Store the ReplayId after successful processing, not before. ReplayIds are specific to a channel and org (sandbox refresh or a different org yields different values). Apex triggers on events manage position automatically; use EventBus.TriggerContext.currentContext().setResumeCheckpoint(replayId) to control retries and checkpoints. LWC lightning/empApi subscribe accepts a replayId. Use a stale-checkpoint alert: if the stored ReplayId is older than the retention window, trigger a full resync.
Code / config example: