Sub topic 8
Opening a Subscribe stream and reading events
This chapter covers the Subscribe RPC: how to open the stream, what you send, what comes back, and how to read events in a loop. It assumes you can already do the following:
- Authenticate and build the
accesstoken,instanceurl, andtenantidmetadata. - Call
GetTopicandGetSchema. - Decode an Avro payload with
fastavro. - Read generated gRPC stubs in Python.
Flow control and replay get their own chapters. Here you only need enough of both to keep a stream running.
What Subscribe is
Subscribe is a bidirectional streaming RPC. The client sends a stream of FetchRequest messages, and the server sends a stream of FetchResponse messages. The two directions are independent. The server does not send one response per request. It sends events whenever it has some and you have unused capacity.
In Python, a bidirectional call takes an iterator of requests and returns an iterator of responses. You write a generator for the request side and loop over the response side.
The messages you use
The fields below come from pubsub_api.proto. Check your copy of the file, because the API can add fields over time.
| Message | Field | Meaning |
|---|---|---|
| `FetchRequest` | `topic_name` | Topic to subscribe to, such as `/event/Order_Shipped__e`. Required on the first request. |
| `FetchRequest` | `replay_preset` | `LATEST`, `EARLIEST`, or `CUSTOM`. Used on the first request. |
| `FetchRequest` | `replay_id` | Opaque bytes. Used only with `CUSTOM`. |
| `FetchRequest` | `num_requested` | How many more events the server may send. |
| `FetchResponse` | `events` | A list of `ConsumerEvent`. May be empty. |
| `FetchResponse` | `latest_replay_id` | The newest position the server knows for this stream. |
| `FetchResponse` | `rpc_id` | Identifier for this call. Useful in logs and support cases. |
| `ConsumerEvent` | `event` | A `ProducerEvent` with `id`, `schema_id`, and `payload`. |
| `ConsumerEvent` | `replay_id` | The position of this specific event. |
A replay ID is opaque. Store it as raw bytes and send it back unchanged. Do not parse it, compare it, or do arithmetic on it.
The first request
The first FetchRequest sets up the subscription. It must name the topic and the start position.
LATESTdelivers only events published after the stream opens.EARLIESTstarts at the oldest event still retained.CUSTOMstarts after the event whosereplay_idyou supply.
Later requests on the same stream only need num_requested. Salesforce ignores the other fields on those requests, so leave them unset.
Reading the stream
The code below is a complete subscriber. It builds on the auth_metadata, get_schema, and decode_event functions from earlier chapters. Put those in the same module or import them.
import queue
import threading
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
ENDPOINT = "api.pubsub.salesforce.com:7443"
BATCH_SIZE = 10
_STOP = object()
def request_stream(first_request, pending):
"""Yield the first request, then whatever the reader queues."""
yield first_request
while True:
item = pending.get()
if item is _STOP:
return
yield item
def subscribe(stub, metadata, topic_name, replay_id=None, stop=None):
pending = queue.Queue()
stop = stop or threading.Event()
if replay_id is None:
first = pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=BATCH_SIZE,
)
else:
first = pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.CUSTOM,
replay_id=replay_id,
num_requested=BATCH_SIZE,
)
last_replay_id = replay_id
call = stub.Subscribe(request_stream(first, pending), metadata=metadata)
try:
for response in call:
for consumer_event in response.events:
record = decode_event(stub, metadata, consumer_event.event)
handle(record)
last_replay_id = consumer_event.replay_id
if response.events:
pending.put(
pb2.FetchRequest(
topic_name=topic_name,
num_requested=len(response.events),
)
)
if stop.is_set():
break
finally:
pending.put(_STOP)
call.cancel()
return last_replay_id
def handle(record):
print(record)
def main(access_token, instance_url, tenant_id, topic_name):
metadata = auth_metadata(access_token, instance_url, tenant_id)
with grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
subscribe(stub, metadata, topic_name)How the loop works
request_streamis the request generator. gRPC pulls from it on a background thread. It yields the first request at once, then blocks on the queue until the reader has something to send.- The
for response in callloop runs on your thread. Each iteration is oneFetchResponse. - For every event, the code decodes the payload, hands the record to
handle, and only then remembers its replay ID. The replay ID advances after processing, not before. If the process dies mid-event, you resume at that event instead of skipping it. - After a batch, the code asks for as many events as it just consumed. The server's allowance stays roughly constant, and a slow
handlefunction slows delivery. - The
finallyblock ends the request generator and cancels the call, so no thread is left waiting on the queue.
Empty responses are keepalives
A FetchResponse with an empty events list is normal. The server sends these periodically while the topic is quiet, and they carry a current latest_replay_id. They have three uses:
- They prove the connection is alive.
- They let you advance your stored position even when no events matched, so a resume after a quiet period starts near the head of the topic instead of far back.
- They are a safe place to refresh checkpoints.
The loop above does not send a FetchRequest for them, because there is nothing to replenish. If you saved latest_replay_id from every response, you would also record positions for keepalives. That is safe only when you have fully processed every event that came before it. Handling events in order within a single thread guarantees this.
Common errors
- Invalid or missing topic. The stream fails with a gRPC error such as
INVALID_ARGUMENTorNOT_FOUND. Check the topic name prefix:/event/for platform events and/data/for change events. - Metadata errors. A wrong
instanceurl,tenantid, or expired token producesUNAUTHENTICATED. Refresh the token and reconnect. You cannot patch metadata on an open call. - Passing a replay ID with the wrong preset.
replay_idis only read whenreplay_presetisCUSTOM. WithLATEST, the ID is ignored and you silently skip any events published while you were offline. - Blocking the generator thread. Never do slow work inside
request_stream. It should only read from the queue. - Decoding in the wrong place. If
GetSchemais called inside the response loop for an unseenschema_id, that call adds latency to the stream. It is fine, because the cache means you pay once per schema ID. - Iterating after cancel. Calling
call.cancel()ends the iterator with aCANCELLEDerror in some code paths. Treat it as expected when you cancelled it yourself.
Running it and checking the result
Publish a test event from the org. For a platform event, you can do this from Apex or Developer Console with EventBus.publish. A running subscriber prints the decoded record as a dict. A typical record has fields such as ReplayId, CreatedDate, CreatedById, and your custom fields. The ReplayId inside the payload is not the same as the replay_id on the ConsumerEvent. Use the one on ConsumerEvent to resume the stream.
If nothing prints, check these in order:
- The stream opened without a gRPC error.
- You used
LATESTand published after the stream opened. num_requestedis greater than zero.- The topic's
can_subscribeflag fromGetTopicis true.
Exercise
Your subscriber uses LATEST, crashes, and restarts ten minutes later. Events published in the gap never reach it. What two changes to the code make the restart lossless, and where in the loop should the stored value be updated?
Show answer
Save the replay_id of each ConsumerEvent to durable storage after that event has been processed. On restart, load it and call subscribe with replay_id=..., so the first request uses CUSTOM instead of LATEST. Update the stored value after handle(record) returns, not before. That way a crash during handling replays the event rather than skipping it.
Exercise
A FetchResponse arrives with an empty events list. Should the subscriber send a new FetchRequest, and why?
Show answer
No. The response is a keepalive and consumed none of the allowance granted by num_requested, so there is nothing to replenish. Sending more requests would only raise the amount of unprocessed capacity the server can fill.