Sub topic 14
Managed subscriptions and server-side replay tracking
This chapter assumes you have read the earlier chapters on the Subscribe RPC, num_requested flow control, and replay IDs. You should be comfortable with the generated Python stubs and the authentication metadata.
The problem managed subscriptions solve
With Subscribe, your code owns the replay position. You save replay_id to a database or file and pass it back as ReplayPreset.CUSTOM after a restart. If you lose that storage, you lose your place.
A managed subscription moves that bookkeeping to Salesforce. You create a subscription record in the org that names a topic. Your client then calls the ManagedSubscribe RPC and tells the server which events it has finished processing. The server stores the position.
Managed subscription support was released in beta. Check the current Pub/Sub API documentation and your copy of pubsub_api.proto before relying on the field names below.
How it differs from Subscribe
| Concern | Subscribe | ManagedSubscribe |
|---|---|---|
| Where the replay position lives | Your storage | Salesforce |
| Starting point | Replay preset or stored replay ID in each request | Set once in the subscription definition |
| Saving progress | You write the replay ID yourself | You send a commit request over the stream |
| Request type | `FetchRequest` | `ManagedFetchRequest` |
| Identifies the stream by | Topic name | Subscription ID or developer name |
Creating the subscription
A managed subscription is a ManagedEventSubscription record. You create it through the Tooling API, not through gRPC. Its main fields are:
DeveloperNameandLabel, which identify the subscription.TopicName, such as/data/AccountChangeEvent.DefaultReplay, eitherLATESTorEARLIEST. It applies only when the subscription has no stored position.State, eitherRUNorSTOP.
Subscribing and committing
The first request on the stream names the subscription and asks for events. After you process events, you send a commit request carrying the replay ID of the last event you finished. The server stores that ID. On reconnect, delivery resumes after the last committed ID.
import uuid
import queue
import pubsub_api_pb2 as pb2
BATCH_SIZE = 10
def managed_subscribe(stub, metadata, developer_name, handle):
pending = queue.Queue()
pending.put(pb2.ManagedFetchRequest(
developer_name=developer_name,
num_requested=BATCH_SIZE,
))
def requests():
while True:
yield pending.get()
for response in stub.ManagedSubscribe(requests(), metadata=metadata):
for consumer_event in response.events:
handle(consumer_event.event) # raise here to skip the commit
if response.events:
last = response.events[-1]
pending.put(pb2.ManagedFetchRequest(
developer_name=developer_name,
num_requested=len(response.events),
commit_replay_id_request=pb2.CommitReplayRequest(
commit_request_id=str(uuid.uuid4()),
replay_id=last.replay_id,
),
))
if response.HasField("commit_response"):
print("committed:", response.commit_response.replay_id)The commit request also carries num_requested, so one message both commits progress and opens the flow-control window for more events.
Common errors and trade-offs
- Committing before processing. A crash then loses events silently. Commit only after the handler succeeds.
- Assuming commits are instant. A commit is acknowledged asynchronously through
commit_response. A crash before the acknowledgment can replay events, so handlers must tolerate duplicates. - Expecting
DefaultReplayto rewind. It sets the starting point only for a subscription with no stored position. - Ignoring retention. The server tracks your position, but it cannot deliver events that have aged out of the retention window.
- Running several clients on one subscription. One position cannot serve independent consumers. Create a separate subscription for each application.
Use Subscribe when you need your own offset storage, for example to commit in the same database transaction as your writes. Use ManagedSubscribe when you want less state to maintain and Salesforce-side tracking is enough.
Exercise
Your handler writes each event to a database and then returns. Where in the ManagedSubscribe loop should you send the commit request, and why?
Show answer
Send it after the handler returns successfully, using the replay ID of the last event processed. If you commit first and the process crashes during handling, the server has already recorded those events as done and will not redeliver them. Committing afterward means a crash causes duplicates instead of loss, which an idempotent handler can absorb.