Sub topic 2
Finding a Topic's Schema and Reading Events
Assume you can authenticate with an OAuth access token and use generated Python gRPC stubs from pubsub_api.proto. You also need basic Avro knowledge. Avro is a format that stores data with a separate schema describing each field.
Finding a topic's schema
Call GetTopic with the topic name. The response tells you whether the topic supports subscriptions and provides its schema ID. Use GetSchema with that ID to retrieve the schema JSON.
import io
import json
import fastavro
import pubsub_api_pb2 as pb2
schema_cache = {}
def get_schema(stub, metadata, schema_id):
if schema_id not in schema_cache:
response = stub.GetSchema(
pb2.SchemaRequest(schema_id=schema_id),
metadata=metadata,
)
schema_cache[schema_id] = fastavro.parse_schema(
json.loads(response.schema_json)
)
return schema_cache[schema_id]
def decode_event(stub, metadata, consumer_event):
schema = get_schema(stub, metadata, consumer_event.event.schema_id)
return fastavro.schemaless_reader(
io.BytesIO(consumer_event.event.payload),
schema,
)Cache parsed schemas by ID. This avoids an API request for every event and supports topics whose schema changes over time.
> callout note > Decode an event with the schema ID carried by that event. Do not assume that every event uses the topic's first schema forever.
Opening a Subscribe stream
Subscribe is a bidirectional gRPC stream. Your client sends FetchRequest messages while the server sends event responses. Start at LATEST for new events, or use CUSTOM with a stored replay ID.
import queue
import pubsub_api_pb2 as pb2
pending = queue.Queue()
pending.put(pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=10,
))
def requests():
while True:
yield pending.get()
for response in stub.Subscribe(requests(), metadata=metadata):
for item in response.events:
record = decode_event(stub, metadata, item.event)
print(record)
last_replay_id = item.replay_idControlling delivery
num_requested is flow control: it grants the server permission to deliver that many events. After processing a response, request the same number again. Persist each replay ID after successful processing so a reconnect can resume safely.
Exercise
Why should a subscriber request more events only after processing the current batch?
Show answer
This keeps the flow-control window aligned with the consumer's capacity and reduces unprocessed events in memory.