Sub topic 10
Replay IDs: resuming from a known position
This chapter assumes you can already open a Subscribe stream, decode Avro payloads, and use num_requested for flow control, as covered in earlier chapters. You should also be comfortable with Python and with the idea that a subscriber can crash or lose its connection at any time.
Why a subscriber needs a position
Platform events and Change Data Capture (CDC) events are published to a topic, and Salesforce keeps them for a limited time. A subscriber that only listens live loses every event published while it was disconnected. A replay ID lets the subscriber say where it stopped, so the server can resume from there.
Each event delivered on a Subscribe stream arrives as a ConsumerEvent. It carries the decoded-later event (the payload and schema ID) and a replay_id. Four properties of the replay ID matter for design:
- It is a
bytesvalue that the server generates. Treat it as opaque. Do not parse it, compare it numerically, or assume that consecutive events have consecutive IDs. - It identifies a position within one topic. An ID from one topic is meaningless on another.
- It is valid only while the event is still inside the retention window. After that, the ID points to data the server no longer has.
- Resuming with a given ID delivers the events published after that position. The event with that ID is not sent again.
Replay presets
The first FetchRequest on a stream chooses where to start with its replay_preset field.
| Preset | Starting point | Typical use |
|---|---|---|
| `LATEST` | Only events published after the subscription starts | First run of a live-only consumer |
| `EARLIEST` | The oldest event still retained | Backfilling the full retention window |
| `CUSTOM` | The event after the supplied `replay_id` | Resuming after a restart or disconnect |
replay_id is read only when the preset is CUSTOM. Later FetchRequest messages on the same stream are used to request more events with num_requested. The server ignores any preset in them, so you do not need to resend one.
Choosing the starting request
The code below builds the first request from whatever the store returns. It keeps the start-position decision in one function, so the rest of the subscriber does not need to know which case applies.
import pubsub_api_pb2 as pb2
BATCH_SIZE = 10
def first_fetch_request(topic_name, stored_replay_id, backfill=False):
"""Return the first FetchRequest for a new stream.
stored_replay_id is bytes or None.
backfill chooses EARLIEST over LATEST when nothing is stored.
"""
if stored_replay_id is not None:
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.CUSTOM,
replay_id=stored_replay_id,
num_requested=BATCH_SIZE,
)
preset = pb2.ReplayPreset.EARLIEST if backfill else pb2.ReplayPreset.LATEST
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=preset,
num_requested=BATCH_SIZE,
)Persisting the replay ID
The replay ID is only useful if it survives a process restart. Store it somewhere durable, keyed by topic, and keep the raw bytes. The following store uses SQLite from the standard library, so it runs as written.
import sqlite3
class ReplayStore:
def __init__(self, path="replay.db"):
self.db = sqlite3.connect(path)
self.db.execute(
"CREATE TABLE IF NOT EXISTS replay ("
"topic TEXT PRIMARY KEY, replay_id BLOB NOT NULL)"
)
self.db.commit()
def load(self, topic):
row = self.db.execute(
"SELECT replay_id FROM replay WHERE topic = ?", (topic,)
).fetchone()
return bytes(row[0]) if row else None
def save(self, topic, replay_id):
self.db.execute(
"INSERT INTO replay (topic, replay_id) VALUES (?, ?) "
"ON CONFLICT(topic) DO UPDATE SET replay_id = excluded.replay_id",
(topic, replay_id),
)
self.db.commit()In production you might use a database table shared across workers, a key-value store, or an object in cloud storage. The requirements are the same: a durable write, one value per topic (or per topic and consumer), and bytes stored without conversion to text that could alter them.
When to save: the processing order
Where the save happens in your loop decides what a crash costs you.
- Save before processing. A crash after saving but before finishing the work skips that event on restart. This is at-most-once delivery.
- Save after processing. A crash after finishing the work but before saving replays that event on restart. This is at-least-once delivery.
Most subscribers choose at-least-once and make the handler idempotent, so processing the same event twice has the same effect as processing it once. A common approach is to use a unique key from the event, such as the ReplayId in the event header for platform events or the record ID plus a change timestamp for CDC, and ignore keys already handled.
def run(stub, metadata, topic_name, store, handle):
stored = store.load(topic_name)
first = first_fetch_request(topic_name, stored)
# ... put `first` on the request queue as in the Subscribe chapter ...
for response in stub.Subscribe(request_iterator, metadata=metadata):
for consumer_event in response.events:
record = decode_event(stub, metadata, consumer_event.event)
handle(record) # must be idempotent
store.save(topic_name, consumer_event.replay_id)
# request the same number of events just processedSaving after every event is simple, but it costs one durable write per event. If that is too slow, save once per response batch, using the replay ID of the last event in the batch. The price is a larger replay window after a crash, up to one batch of duplicates. Your handler already tolerates duplicates, so this is a safe trade.
Advancing the position on quiet topics
A FetchResponse has a latest_replay_id field in addition to its list of events. The server also sends responses with an empty event list periodically (keepalives). These carry a latest_replay_id that marks the newest position the server has reached for your subscription, even when no event reached you.
This matters on a topic with filtered or sparse traffic. If your stored ID is old and nothing new arrives for hours, the stored position can age out of the retention window even though your subscriber has been healthy and connected all along. Saving latest_replay_id from empty responses keeps your stored position fresh.
def handle_response(response, topic_name, store, handle, stub, metadata):
for consumer_event in response.events:
record = decode_event(stub, metadata, consumer_event.event)
handle(record)
store.save(topic_name, consumer_event.replay_id)
if not response.events and response.latest_replay_id:
store.save(topic_name, response.latest_replay_id)Only do this when the response has no events. When events are present, the last handled event's ID is the correct checkpoint, because latest_replay_id may be ahead of events you have not yet processed.
Edge cases and failure modes
- Expired replay ID. If the stored ID is older than the retention window, the server cannot honor it. The stream fails with a gRPC error rather than silently skipping ahead. Catch it, decide whether a gap is acceptable, and then start again with
EARLIEST(to take what remains) orLATEST(to accept the loss). Log the gap so it can be investigated. - Invalid or corrupted ID. An ID that was edited, truncated, or taken from a different topic is rejected. Store the bytes unchanged.
- Gaps in a CDC stream. Change Data Capture can emit gap events when Salesforce cannot generate the full change. A gap event is a signal to refetch the affected records, not a replay problem.
- Two consumers, one stored ID. If two workers share a topic and one store row, they overwrite each other's progress. Give each independent consumer its own key, or use a single active consumer.
- First run with
LATEST. Events published between the moment you decide to start and the moment the stream opens are missed. If that gap matters, start withEARLIESTand filter by timestamp, or use a stored position from a prior run.
Summary
A replay ID is an opaque, topic-specific position. Start with CUSTOM and a stored ID when you have one, otherwise LATEST or EARLIEST. Save the ID after processing, make handlers idempotent, keep the position fresh with latest_replay_id on empty responses, and plan for an expired ID.
Exercise
Your subscriber saves the replay ID at the start of each event handler, before doing the work. The process crashes halfway through handling an event. What happens on restart, and which change gives at-least-once behavior?
Show answer
On restart the subscriber resumes after the saved ID, which belongs to the event that was only half handled, so that event is never delivered again and its work is lost (at-most-once). To get at-least-once behavior, save the replay ID after the handler finishes, and make the handler idempotent so a repeated event does no harm.
Exercise
A topic receives almost no traffic. Your subscriber has been connected for five days and last saved the replay ID of an event from five days ago. Why might the next restart fail, and what field helps prevent it?
Show answer
The stored replay ID is older than the retention window, so the server can no longer resume from it. Saving latest_replay_id from empty (keepalive) responses keeps the stored position recent even when no events arrive.