Sub topic 3
Replay IDs: resuming from a known position
Assume you know Python, OAuth access tokens, gRPC streaming, and basic publish/subscribe messaging. This chapter focuses on reliable recovery after a disconnect.
Store the last processed replay ID
A replay ID is an opaque position supplied with each delivered event. Store it only after your application successfully processes the event. Preserve its original bytes; do not convert it to an integer or alter its encoding.
On the first connection, choose LATEST to receive new events or EARLIEST to read retained events. After a disconnect, use CUSTOM with the stored replay ID.
import pubsub_api_pb2 as pb2
def initial_request(topic_name, replay_id=None):
if replay_id is None:
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=10,
)
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.CUSTOM,
replay_id=replay_id,
num_requested=10,
)A subscriber should process an event, persist its replay ID, and then request more events. If it crashes before persistence, it may receive that event again. Therefore, event processing should be idempotent: processing the same event twice should not create an incorrect result.
Reconnect after errors
Keepalive traffic helps detect a broken connection, but it does not prevent every stream error. When the stream ends, reconnect with the last successfully persisted replay ID. Use bounded backoff so repeated failures do not create a tight loop.
CDC events and delivery limits
Change Data Capture, or CDC, publishes record-change events on CDC topics. The same replay, flow-control, and reconnect rules apply. Retention is limited, so a subscriber that remains offline too long may request a replay ID that Salesforce no longer retains. Delivery quotas, requested-batch limits, and concurrent-stream limits also affect subscriber design. Check the limits for your event type and API version.
Managed subscriptions
Managed subscriptions let Salesforce track a subscription’s replay position instead of requiring your application to store it. They can simplify recovery, but they depend on the managed-subscription RPCs and behavior supported by your pubsub_api.proto version. Confirm acknowledgement, retention, and operational limits before choosing them.
Test and troubleshoot
Test a normal stream, a forced disconnect, a process restart, duplicate delivery, an expired replay ID, and a malformed payload. Log topic name, schema ID, replay position, error code, and retry delay. Never log access tokens.
Exercise
Which replay ID should a subscriber persist?
Show answer
The replay ID of the last event that it processed successfully, stored in its original form.