Sub topic 9
Replay IDs and the retention window
This chapter assumes you can already subscribe to a change event channel, either from a Lightning web component with empApi or from an external client. It also assumes you know what a change event contains. Here you will learn how a subscriber resumes where it stopped, and how long Salesforce keeps events available for that.
What a replay ID is
Every event published to the event bus is stored with a replay ID. This is an identifier that Salesforce assigns when the event is published. Replay IDs increase over time within a channel, so a larger ID means a later event. Three rules matter in practice:
- Treat the replay ID as an opaque marker. Salesforce does not promise that IDs are consecutive, so never compute "the next ID" or detect missing events by looking for holes in the sequence.
- A replay ID is only meaningful for the org and channel that produced it. An ID saved from a sandbox is not valid in production, and an ID from
/data/AccountChangeEventshould not be used on another channel. - The Pub/Sub API returns the replay ID as bytes. CometD and
empApireturn it as a number. Store whatever your client gives you without converting it.
A subscriber that saves the replay ID of the last event it fully processed can reconnect later and ask for everything after that point. That saved value is a checkpoint.
The retention window
Salesforce keeps change events on the event bus for 72 hours (three days). Within that window a subscriber can replay stored events. After 72 hours an event is gone, and no replay ID can bring it back.
The window has three consequences for design:
- A subscriber that is offline for less than 72 hours can catch up with no loss.
- A subscriber that is offline for more than 72 hours has a permanent hole in its data. It must rebuild its state by another route, usually a bulk query of the affected records.
- Retention applies to the event, not to the checkpoint. Your stored replay ID can still exist in your database after the event it points to has expired.
The 72-hour figure is the published value at the time of writing. Check the current Salesforce documentation for your org's edition before you build on it.
Choosing where to start
When you subscribe, you choose a starting position. The three choices are the same in every client, but the names differ.
| Intent | CometD and `empApi` | Pub/Sub API | What you receive |
|---|---|---|---|
| Only new events | `-1` | `LATEST` | Events published after you subscribe |
| Everything retained | `-2` | `EARLIEST` | All events in the 72-hour window, then new events |
| Resume from a checkpoint | The saved replay ID | `CUSTOM` plus the replay ID | Events published after that ID, then new events |
Resuming from a checkpoint is exclusive. You get events after the ID you pass, not the event with that ID. This is why you store the ID of the last event you finished, not the one you want next.
The component from the earlier chapter used -1. That is fine for a UI that only needs live updates, because a user who opens the page does not care what happened yesterday. An integration that copies data to another system cannot use -1, since every disconnect would silently lose changes.
Saving and using checkpoints
The usual loop for an external subscriber has four steps:
- Read the saved checkpoint from durable storage, such as a database table keyed by org and channel.
- Subscribe with that checkpoint, or with
-2orEARLIESTon the first run. - For each event, apply the change to the target system.
- After the change is committed in the target, save the event's replay ID.
The order of steps 3 and 4 matters. If you save the checkpoint first and the process crashes before applying the change, the event is lost. If you apply first and crash before saving, the event is delivered again on restart.
That second case means delivery is at least once. Your handler must tolerate duplicates. For change events, a stable key is the pair transactionKey and sequenceNumber from the ChangeEventHeader, or the record ID together with commitNumber. Applying the same update twice should leave the target unchanged.
Because the Pub/Sub API can also send keepalive messages that carry the latest replay ID but no events, you can advance your checkpoint on those messages too. That keeps the checkpoint inside the retention window on quiet channels. Without it, a channel that sees no changes for four days leaves you holding a four-day-old checkpoint, even though nothing was missed.
A restart decision as code
Before subscribing, a client has to decide whether its saved checkpoint is still usable. The helper below makes that decision from the checkpoint and the time it was last confirmed. It runs on Node.js with no dependencies.
const RETENTION_MS = 72 * 60 * 60 * 1000;
// Leave a safety margin so a slow restart does not cross the boundary.
const SAFETY_MS = 6 * 60 * 60 * 1000;
function chooseStart(checkpoint, now = Date.now()) {
if (!checkpoint) {
return { replayId: -2, reconcile: true, reason: 'first run' };
}
const age = now - checkpoint.savedAt;
if (age > RETENTION_MS - SAFETY_MS) {
return { replayId: -2, reconcile: true, reason: 'checkpoint may have expired' };
}
return { replayId: checkpoint.replayId, reconcile: false, reason: 'resume' };
}
const hour = 60 * 60 * 1000;
const now = Date.now();
console.log(chooseStart(null, now));
console.log(chooseStart({ replayId: 4200, savedAt: now - 5 * hour }, now));
console.log(chooseStart({ replayId: 4200, savedAt: now - 70 * hour }, now));The three calls print a first-run result, a resume result, and an expiry warning. When reconcile is true, the client should also run a full or incremental data sync, because starting at -2 only recovers what is still retained. It cannot recover what has already aged out.
Replay in a Lightning web component
An empApi subscriber can also use -2 or a saved ID. The message.data.event.replayId field holds the ID of each delivered event. The component below keeps the latest value in memory so it can resubscribe from that point after an error.
import { LightningElement } from 'lwc';
import { subscribe, unsubscribe, onError } from 'lightning/empApi';
export default class AccountChangeResume extends LightningElement {
subscription = null;
channelName = '/data/AccountChangeEvent';
lastReplayId = -1;
connectedCallback() {
onError((error) => {
console.error('empApi error', JSON.stringify(error));
});
this.start(this.lastReplayId);
}
start(replayId) {
subscribe(this.channelName, replayId, (message) => {
this.lastReplayId = message.data.event.replayId;
const header = message.data.payload.ChangeEventHeader;
console.log(this.lastReplayId, header.changeType, header.recordIds);
}).then((response) => {
this.subscription = response;
});
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}An in-memory value disappears when the page closes, so this component only resumes within one page session. A component that must survive a page reload needs to write the ID to a record or another store that the user's session can reach. Most integrations avoid that and use an external service with proper storage.
How the decision flows
Edge cases and common errors
- Expired or invalid replay ID. Clients react differently. The Pub/Sub API reports an error for an ID it cannot honor. CometD behavior depends on the ID and the client library. Test this case in a sandbox, and do not rely on the server to tell you that data was lost.
- Gap events. Salesforce may send a gap event when it cannot deliver full change details, for example after an internal error. A saved replay ID does not fix that, so the next chapter covers how to reconcile.
- One checkpoint for many channels. Each channel has its own sequence. Keep one checkpoint per channel, or per custom channel if you use one.
- Checkpoint saved too early. Saving on receipt instead of after processing turns a crash into permanent data loss.
- Replaying
-2on every start. This works but reprocesses up to three days of events each time. It is slow and relies entirely on idempotent handlers. - Clock-based assumptions. Compare the saved time with when the event was committed, not with your local clock alone. The
commitTimestampin the header is the better reference.
Summary
A replay ID marks a position in a channel. A checkpoint is the replay ID you saved after finishing an event. You resume from a checkpoint within the 72-hour retention window, and you fall back to -2 plus reconciliation when the checkpoint is missing or too old. Save the checkpoint after the work is committed, accept that duplicates can happen, and make your handler idempotent.
Exercise
A subscriber saves each replay ID as soon as the event arrives, then writes the change to a database. The process crashes after saving the ID but before the database write. What happens on restart, and how do you fix the design?
Show answer
On restart the subscriber resumes after the saved ID, so the event whose write never completed is skipped and that change is lost. Fix it by saving the replay ID only after the database write is committed. This means a crash can cause the same event to be delivered twice, so the write must be idempotent, for example by keying on transactionKey and sequenceNumber.
Exercise
An integration was down for 80 hours. Its stored checkpoint is valid in format. Can it resume from that checkpoint and get every missed change? What should it do?
Show answer
No. The retention window is 72 hours, so events from the first 8 hours of the outage no longer exist on the event bus. Resuming from the checkpoint, or starting at -2 or EARLIEST, recovers only what is still retained. The integration should also run a reconciliation, such as querying the affected objects for records modified since the checkpoint time, and then continue with normal replay.