Sub topic 14
Managed subscriptions and server-side replay tracking
This chapter assumes you have read the earlier chapters on Subscribe, num_requested, and replay IDs. You should be comfortable with the authentication metadata, the generated Python stubs, and decoding Avro payloads with a cached schema.
The problem managed subscriptions solve
With the standard Subscribe RPC, your code owns the checkpoint. You store the last processed replay ID somewhere durable, and on reconnect you pass it back as a CUSTOM replay preset. That works, but it has costs:
- You need a database, file, or cache for the checkpoint, and it must be reliable.
- Every subscriber instance needs its own logic for when to write the checkpoint.
- If the checkpoint store and your processing disagree, you resume from the wrong position.
A managed subscription moves the checkpoint to Salesforce. You create a subscription record in the org. It names a topic and a default starting position. When you connect, you refer to the subscription by ID or developer name. As you finish processing events, you tell the server how far you got. This is called committing a replay ID. After a disconnect, the server resumes from the last committed position, so your client does not need to store one.
The ManagedSubscribe RPC is the managed counterpart of Subscribe. It uses the same event format and the same flow control.
Standard versus managed subscriptions
| Aspect | `Subscribe` | `ManagedSubscribe` |
|---|---|---|
| Who stores the checkpoint | Your application | Salesforce |
| What you send to start | Topic name and replay preset | Subscription ID or developer name |
| Resume after disconnect | You pass `CUSTOM` and a replay ID | The server resumes from the last commit |
| Setup | None | Create a subscription record in the org |
| Progress signal | Implicit (you save the ID) | Explicit commit request |
| Flow control | `num_requested` | `num_requested` |
Creating a managed subscription
A managed subscription is a record of the ManagedEventSubscription type. You create it through the Tooling API, not through the Pub/Sub API. Its metadata has four fields that matter here:
topicName: the topic to subscribe to, such as/data/AccountChangeEvent.defaultReplay: where a new subscription starts, eitherLATESTorEARLIEST. It applies only until the first commit exists.state:RUNorSTOP. A stopped subscription does not deliver events.errorRecoveryReplay: where to restart if the saved position is no longer valid, for example because the event aged out of retention. The options are againLATESTorEARLIEST.
The following script creates one. It reuses the access token and instance URL you already obtained during authentication.
import requests
API_VERSION = "v64.0"
def create_managed_subscription(access_token, instance_url, developer_name, topic_name):
url = f"{instance_url}/services/data/{API_VERSION}/tooling/sobjects/ManagedEventSubscription"
body = {
"FullName": developer_name,
"Metadata": {
"label": developer_name,
"topicName": topic_name,
"defaultReplay": "LATEST",
"state": "RUN",
"errorRecoveryReplay": "LATEST",
},
}
headers = {"Authorization": f"Bearer {access_token}"}
response = requests.post(url, json=body, headers=headers, timeout=30)
response.raise_for_status()
return response.json()["id"]The returned id is the subscription ID. You can also connect using the developer name you chose in FullName. Use a name that says what the consumer does, for example Account_Changes_Sync. The name must be unique in the org.
The user whose token you use needs permission to manage this record type. If the POST returns a 403, check the user's permissions before anything else.
The ManagedSubscribe messages
ManagedSubscribe is a bidirectional stream like Subscribe. The messages are:
ManagedFetchRequestcarriessubscription_idordeveloper_name, plusnum_requestedand an optionalcommit_replay_id_request.CommitReplayRequestholds acommit_request_idthat you invent, and thereplay_idyou want to commit.ManagedFetchResponsecarriesevents,latest_replay_id,pending_num_requested, and an optionalcommit_response.CommitReplayResponseechoes thecommit_request_idandreplay_id. It also has anerrorfield and aprocess_time.
The first request on the stream must identify the subscription and say how many events you want. After that, each request can ask for more events, commit a position, or both.
A managed subscriber in Python
The code below follows the same shape as the subscribe function from the earlier chapter. It reuses decode_event for Avro decoding. The new parts are the subscription ID in the first request and the commit after each processed batch.
import queue
import uuid
import pubsub_api_pb2 as pb2
BATCH_SIZE = 10
def managed_subscribe(stub, metadata, subscription_id, handle_record):
pending = queue.Queue()
pending.put(
pb2.ManagedFetchRequest(
subscription_id=subscription_id,
num_requested=BATCH_SIZE,
)
)
def requests():
while True:
yield pending.get()
for response in stub.ManagedSubscribe(requests(), metadata=metadata):
if response.HasField("commit_response"):
commit = response.commit_response
if commit.HasField("error"):
print("commit failed:", commit.error.msg)
else:
print("committed replay id for request", commit.commit_request_id)
if not response.events:
continue
last_replay_id = None
for consumer_event in response.events:
record = decode_event(stub, metadata, consumer_event.event)
handle_record(record)
last_replay_id = consumer_event.replay_id
pending.put(
pb2.ManagedFetchRequest(
commit_replay_id_request=pb2.CommitReplayRequest(
commit_request_id=str(uuid.uuid4()),
replay_id=last_replay_id,
)
)
)
pending.put(pb2.ManagedFetchRequest(num_requested=len(response.events)))Notice what is missing: there is no stored replay ID and no ReplayPreset. A restart calls the same function with the same subscription ID.
Commit semantics and what they guarantee
A commit tells the server that you have finished everything up to and including that replay ID. Three points follow from this.
- Commit after processing, not before. If you commit first and crash during processing, the server will never redeliver those events. They are lost to your application.
- Delivery is at least once. If you crash after processing but before the commit is acknowledged, the server resumes from the older committed position. You will see some events again. Your handler must tolerate duplicates, for example by using the replay ID or a record key as an idempotency key.
- You do not need to commit every event. Committing once per batch, or on a timer, reduces traffic. The trade-off is that a crash replays up to one interval's worth of events.
The commit_request_id is how you match an acknowledgment to the request that caused it. Commit responses arrive on the same stream as event batches, so the loop must check for them, as the code above does. If you have several commits in flight, keep a dictionary from commit_request_id to the replay ID you expected.
A failed commit is not fatal by itself. The next successful commit covers the earlier events too, because a commit marks a position. Log the error, and keep going unless failures repeat.
Starting positions and recovery
A new subscription has no commit yet, so the server uses defaultReplay. LATEST means you get only events published after the first connection. EARLIEST means you get everything still in the retention window, which can be a large backlog.
errorRecoveryReplay applies when the saved position cannot be used. The usual cause is that you stayed disconnected longer than the retention period, so the event at your committed ID no longer exists. With EARLIEST, you restart from the oldest retained event. With LATEST, you skip ahead. Neither option recovers the lost events. If you cannot tolerate the gap, you need a separate reconciliation process, for example a query against the source objects.
When to choose which approach
Choose ManagedSubscribe when:
- You want several deployments or restarts to share one logical position without your own database.
- Your application is stateless, for example a container that is replaced often.
- You want fewer moving parts around checkpointing.
Choose Subscribe with your own replay IDs when:
- You need to commit the replay ID in the same transaction as your own writes. Storing the ID alongside your data in one database transaction gives you stronger consistency than a separate commit call.
- You need to start from an arbitrary replay ID that you control.
- You cannot depend on a Beta feature.
Troubleshooting
- The stream opens but no events arrive. Check that the subscription
stateisRUN, and that you sent a non-zeronum_requested. - Every restart replays old events. Your commits are not reaching the server or are failing. Inspect
commit_response.error. - The same event arrives twice. This is expected after a crash between processing and commit. Add idempotent handling.
- Authentication errors. The metadata headers are the same as for
Subscribe:accesstoken,instanceurl, andtenantid.
Exercise
Exercise
Your managed subscriber processes a batch of 10 events and crashes while handling event 7. You commit once per batch, after the whole batch is handled. After restart, which events does the server deliver, and what must your handler be able to do?
Show answer
The last commit was made before this batch, so the server resumes from there and redelivers all 10 events, including events 1 to 6 that you had already handled. The handler must be idempotent so that reprocessing events 1 to 6 causes no harm. Because the crash happened before the commit, no event was skipped.
Exercise
Why does the code commit before sending the next num_requested, and what would go wrong if it committed the replay ID of the first event in the batch instead of the last?
Show answer
Committing first records progress before more events arrive, which keeps the saved position close to the processed position. Committing the first event's ID would tell the server only that event is done. After a crash, the server would redeliver the rest of the batch even though they were processed, which increases duplicates but loses nothing. Committing a position beyond what you processed is the dangerous direction, because it skips events.