Sub topic 8
Opening a Subscribe stream and reading events
This chapter assumes you can already authenticate and send the accesstoken, instanceurl, and tenantid metadata headers. It also assumes you know how to fetch and cache a topic's Avro schema with GetTopic and GetSchema. You should be comfortable with Python generators and have the stubs generated from pubsub_api.proto.
How Subscribe works
Subscribe is a bidirectional streaming RPC. The client sends a stream of FetchRequest messages. The server answers with a stream of FetchResponse messages. Each response holds a batch of events, plus a latest_replay_id that marks the server's position.
The first FetchRequest names the topic, says where to start, and says how many events you are ready to receive. Later requests only need topic_name and num_requested.
Choosing a starting point
The first request sets replay_preset. This chapter uses two values:
| Preset | Meaning | Extra field |
|---|---|---|
| `LATEST` | Only events published after the subscription starts | none |
| `CUSTOM` | Events after a stored position | `replay_id` |
A third preset, EARLIEST, starts at the oldest retained event. The Replay IDs chapter covers all presets in detail.
Feeding the request stream
The gRPC Python client takes an iterator of requests. A generator that blocks on a queue.Queue lets you send the first request now and push more later, from the same loop that reads responses.
import queue
import pubsub_api_pb2 as pb2
BATCH_SIZE = 10
def subscribe(stub, metadata, topic_name, replay_id=None):
pending = queue.Queue()
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,
)
pending.put(first)
def requests():
while True:
yield pending.get()
last_replay_id = replay_id
for response in stub.Subscribe(requests(), metadata=metadata):
for consumer_event in response.events:
record = decode_event(stub, metadata, consumer_event.event)
print(record)
last_replay_id = consumer_event.replay_id
if response.events:
pending.put(pb2.FetchRequest(topic_name=topic_name, num_requested=len(response.events)))
# Persist last_replay_id (or response.latest_replay_id) to durable storage here.decode_event is the Avro decoder from the previous chapter. The code relies on these steps:
- The first
FetchRequestgoes into the queue before the call starts, so the server gets a request immediately. - The
forloop reads eachFetchResponseas it arrives. - Each item in
response.eventsis aConsumerEvent. Itseventfield is theProducerEventthat holds the schema ID and the Avro payload. Itsreplay_ididentifies its position. - After processing a batch, the client asks for as many events as it just handled. This keeps the number of unprocessed events steady.
Empty responses
A response can arrive with no events. The server sends these as keepalives and uses them to report latest_replay_id. That is why the code only sends a new FetchRequest when response.events is non-empty. Sending num_requested for an empty batch would add credit you did not consume.
Common errors
- Hanging with no output. The server sends nothing until it receives a request with
num_requestedgreater than zero. Check that the first request was queued. - Missing metadata. Pass
metadata=on theSubscribecall. Without valid headers the stream fails with an authentication error. - Saving the replay ID too early. Persist it only after the event is fully handled. Otherwise a crash can skip an event.
- Decoding failures. An unknown
schema_idmeans the schema is not cached.decode_eventfetches it withGetSchemaon first use.
Exercise
In the Subscribe loop, why does the client send a new FetchRequest only when response.events is non-empty, and what should its num_requested be?
Show answer
Empty responses are keepalives and carry no events, so nothing was consumed. Requesting more would inflate the number of events the server may send. After a non-empty batch, set num_requested to len(response.events) so the count of outstanding events stays at the original batch size.