Sub topic 10
Replay IDs and the retention window
This chapter assumes you can already publish an event and subscribe with a trigger or a Lightning Web Component (LWC). It also assumes you know what a CometD-style streaming subscription is at a high level. Here you will learn how Salesforce lets a subscriber go back in time. You will also learn where that ability ends.
What the event bus stores
A platform event is not deleted after delivery. After the event bus accepts an event, Salesforce stores it for 72 hours. This period is the retention window. During it, a subscriber that was offline, slow, or newly created can read events it missed.
Each stored event gets a replay ID. This is a value Salesforce assigns when the event is published. It has three properties:
- Replay IDs increase over time within an event channel, so a larger ID means a later event.
- They are not guaranteed to be consecutive. Never treat a gap as a lost event.
- They are opaque. Compare them for ordering if you must, but don't build business logic on their numeric value.
You can see the replay ID of each event in Apex as ReplayId and in a streaming client in the event metadata. A subscriber that records the last replay ID it processed has a bookmark. It can hand that bookmark back later and ask for everything after it.
The three replay options
When you subscribe through empApi, CometD, or Pub/Sub API, you choose where to start reading.
| Replay value | Meaning | Typical use |
|---|---|---|
| `-1` | Only events published after the subscription starts | Live UI updates where history does not matter |
| `-2` | All events still inside the retention window | Initial load or full recovery |
| A specific replay ID | Events published after that ID | Resuming from a saved bookmark |
Resuming from a specific ID does not redeliver the event with that ID. You get the events that came after it.
Using replay in a Lightning Web Component
The LWC example in the earlier subscribing chapter used -1. That is fine until the connection drops or the user navigates away. When the component loads again it starts at the tip and misses everything in between.
The next component tracks the last replay ID it has seen. It also keeps a flag so it can resubscribe from that point if empApi reports an error. It reads the replay ID from message.data.event.replayId.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class OrderShippedReplayListener extends LightningElement {
channelName = '/event/Order_Shipped__e';
subscription = null;
lastReplayId = -1;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
this.startSubscription(this.lastReplayId);
}
startSubscription(replayId) {
subscribe(this.channelName, replayId, (message) => {
this.lastReplayId = message.data.event.replayId;
const payload = message.data.payload;
console.log('Order shipped: ' + payload.Order_Number__c);
}).then((response) => {
this.subscription = response;
});
}
resubscribe() {
if (this.subscription) {
unsubscribe(this.subscription, () => {
this.subscription = null;
this.startSubscription(this.lastReplayId);
});
} else {
this.startSubscription(this.lastReplayId);
}
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Two details matter here. First, lastReplayId starts at -1, so the first subscription sees only new events. After the first event arrives it holds a real replay ID, so resubscribe() continues from there. Second, the field lives only in memory. If the page reloads, the bookmark is lost. A component that must survive reloads needs to store the ID somewhere durable, for example in a custom object field saved through Apex.
Replay in Apex triggers
An Apex trigger subscriber does not pass a replay value. Salesforce manages the trigger's position on the bus for you. It keeps a checkpoint of the last batch the trigger finished and resumes from there, as long as that position is still inside the retention window.
You can still read each event's replay ID in the trigger. This is useful for logging and for idempotency (making repeated processing harmless):
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
for (Order_Shipped__e evt : Trigger.new) {
System.debug('Processing ' + evt.Order_Number__c
+ ' with replay ID ' + evt.ReplayId);
}
}If a trigger is suspended, you control where it restarts. A trigger can end up suspended after repeated unhandled errors or retries. In Setup, open the Platform Event subscriptions view and resume it. You choose between two start points:
- Resume from where it stopped, which processes events that accumulated while it was suspended.
- Resume from the tip, which skips them and handles only events published from now on.
The choice is a decision about data. Resuming from where it stopped is safer for business-critical events, but it can mean a large backlog if the trigger was down for a long time. The next chapter covers resume checkpoints and retries, which keep a trigger from being suspended in the first place.
What happens at the edge of the window
Retention is a hard limit. Three situations show it.
- An offline subscriber returns within 72 hours. It resumes from its saved replay ID and receives everything it missed, in order.
- An offline subscriber returns after 72 hours. Events older than the window are gone. A saved replay ID can point to an event that no longer exists. The subscriber gets what remains, and the expired events cannot be recovered. You have a data gap.
- A trigger stays suspended past 72 hours. The same rule applies. Resuming from where it stopped cannot recover events that expired while it was suspended.
Because of this, an event stream should not be your system of record. If losing an event is unacceptable, write the business data to a record as well. Use the event to notify others that something happened. When a subscriber detects a gap, it can then reconcile against that record.
Detecting a gap
You cannot see a gap from replay ID arithmetic, since IDs are not consecutive. You detect one by comparing time or by business keys. Two practical approaches:
- Timestamp check. Store the
CreatedDateof the last processed event. On restart, if the offline time was more than 72 hours, assume events were lost and run a reconciliation job. - Sequence in the payload. Add your own counter field, such as
Sequence_Number__c, to the event definition. A subscriber that sees 41 and then 43 knows it missed one. This only works when a single publisher controls the counter.
Idempotent handling
Replay delivers events again. A -2 subscription, a resume from a bookmark saved before the last event was fully processed, and a trigger retry can all produce duplicates. Design handlers so that processing an event twice has the same result as processing it once.
A common pattern is to use a business key from the event as an external ID and upsert. In the earlier trigger, the task creation would produce duplicates on retry. This version uses the order number to avoid that:
trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
Set<String> subjects = new Set<String>();
for (Order_Shipped__e evt : Trigger.new) {
subjects.add('Follow up on order ' + evt.Order_Number__c);
}
Set<String> existing = new Set<String>();
for (Task t : [SELECT Subject FROM Task WHERE Subject IN :subjects]) {
existing.add(t.Subject);
}
List<Task> tasks = new List<Task>();
for (String subject : subjects) {
if (!existing.contains(subject)) {
tasks.add(new Task(Subject = subject, Status = 'Not Started'));
}
}
insert tasks;
}The query runs once for the whole batch, so the trigger stays bulk-safe. Matching on Subject is a simplification for this example. A production design would use a dedicated external ID field on a custom object.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Subscribing with `-1` after an outage | Events published during the outage are skipped | Save the last replay ID and resubscribe with it |
| Treating a replay ID gap as data loss | False alarms | Detect loss by time or by a payload sequence |
| Doing arithmetic on replay IDs | Breaks if the format changes | Pass IDs back unchanged |
| Assuming 72 hours is guaranteed forever | Silent loss after a long outage | Reconcile against a stored record |
| Non-idempotent handlers with `-2` | Duplicate records | Upsert on a business key |
Exercise
A component subscribed with replay ID -1 and was offline for 6 hours. A second component saved the replay ID of its last processed event and was offline for 5 days. What does each receive when it reconnects?
Show answer
The first component receives only events published after it reconnects. Passing -1 asks for new events, so the 6 hours of events are skipped. The second component asks for events after its saved ID, but the 72-hour retention window has passed, so events older than 72 hours are gone. It can receive only what is still stored, which leaves a gap that must be reconciled from stored records.
Exercise
Why is it unsafe to detect missed events by checking that each replay ID is exactly one greater than the previous one?
Show answer
Replay IDs are ordered but not guaranteed to be consecutive, so gaps are normal. To detect missing events, compare timestamps against the retention window or add your own sequence number to the event payload.