Sub topic 7
Decoding Avro payloads into usable records
This chapter assumes you can already open a gRPC channel, send the accesstoken, instanceurl, and tenantid metadata headers, and call GetTopic to get a schema ID. You also need to be comfortable with Python dictionaries and with pip install fastavro.
Why payloads are opaque bytes
Each event the Pub/Sub API sends is a ProducerEvent message. It has an id, a schema_id, and a payload. The payload is bytes. It is Avro binary data with no field names, no type tags, and no embedded schema. Without the schema, the bytes cannot be read.
Avro has two common encodings. The container file format embeds the schema in a header. The "schemaless" binary encoding contains only the values. The Pub/Sub API uses the schemaless encoding, so you must fetch the schema yourself and pass it to the reader.
The decoding flow
- Read
schema_idfrom the event. - If the schema is not in your cache, call
GetSchemawith that ID. - Parse the returned
schema_jsonand store the result. - Decode the payload with the cached schema.
The code
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:
info = stub.GetSchema(pb2.SchemaRequest(schema_id=schema_id), metadata=metadata)
schema_cache[schema_id] = fastavro.parse_schema(json.loads(info.schema_json))
return schema_cache[schema_id]
def decode_event(stub, metadata, producer_event):
schema = get_schema(stub, metadata, producer_event.schema_id)
return fastavro.schemaless_reader(io.BytesIO(producer_event.payload), schema)get_schema calls the server once per schema ID. A schema ID identifies one exact version of a schema, and that version does not change. This makes the cache safe, and the cache has no expiry. When a field is added to the event type, new events carry a new schema ID, and your code fetches the new schema the first time it sees that ID.
decode_event wraps the payload bytes in io.BytesIO because schemaless_reader reads from a file-like object. The result is a plain dict.
What the decoded record looks like
Field values follow the Avro types in the schema. Nullable fields are Avro unions such as ["null", "string"]. With fastavro in its default mode, a union value decodes to the bare value or to None, so you can test it with is None.
A few details commonly cause confusion:
- Timestamps often arrive as
longvalues holding milliseconds since the Unix epoch, not asdatetimeobjects. Convert them yourself. - Change Data Capture events nest their data. The changed fields sit under
ChangeEventHeaderand the record fields beside it. A later chapter covers this. - Some fields, such as compound addresses and large text, may arrive as nested records or bitmaps. Read the schema JSON when a value looks unfamiliar.
Common errors
| Symptom | Likely cause |
|---|---|
| `EOFError` or garbage values | You used the wrong schema, for example a schema ID from a different event type |
| `KeyError` on a field | The field is not in that schema version. Use `record.get("Field")` |
| A schema fetch on every event | The cache key is wrong, or the cache is rebuilt on each call |
| `ModuleNotFoundError` for `pubsub_api_pb2` | Stubs have not been generated from `pubsub_api.proto` |
Exercise
Your subscriber has been running for days when the org adds a custom field to an event type. Do you need to restart the subscriber or clear the schema cache to decode new events? Why or why not?
Show answer
No. New events carry a new schema ID. The cache has no entry for it, so get_schema calls GetSchema, parses the new schema, and caches it. Old schema IDs stay valid for events written with the earlier version.