Sub topic 7
Decoding Avro payloads into usable records
This chapter assumes you can already authenticate and call GetTopic and GetSchema, as covered in the previous chapters. You should also be comfortable with Python dictionaries and bytes. By the end, you will be able to turn the raw payload bytes of an event into a Python dictionary, cache schemas correctly, and avoid the common decoding mistakes.
What the payload actually contains
Every event arrives inside a ProducerEvent message. Its main fields are:
id: a unique ID for the event.schema_id: the ID of the Avro schema that was used to write the payload.payload: the event data as Avro binary.headers: optional key-value metadata.
The payload is schemaless Avro. Avro files usually embed their schema in a header, but this payload does not. It holds only the encoded field values, one after another, with no field names, no type tags, and no schema. The bytes can't be interpreted without the right schema. GetSchema supplies that schema, and the schema_id on each event tells you which one to use.
This design keeps events small. It also means decoding is only as reliable as your schema lookup.
The decoding pipeline
The code below is the same pattern from the schema discovery chapter. It fetches each schema once per schema_id, parses it, and uses it to read the payload.
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)Three details matter here:
- Cache by
schema_id, not by topic name. A topic's schema can change over time, and each version has its own ID. A cache keyed by topic would eventually decode new events with an old schema. - Parse once.
fastavro.parse_schemadoes real work. Parsing it on every event wastes CPU on a busy stream. - Use
schemaless_reader. The plainfastavro.readerexpects an Avro container file with an embedded header. Given a Pub/Sub payload, it fails.
Trying the decoder without a Salesforce org
You can test decoding offline. This script encodes a record with a schema shaped like a platform event, then decodes it. It runs as shown after pip install fastavro.
import io
import fastavro
schema = fastavro.parse_schema({
"type": "record",
"name": "Order_Event__e",
"namespace": "com.sforce.eventbus",
"fields": [
{"name": "CreatedDate", "type": "long"},
{"name": "CreatedById", "type": "string"},
{"name": "Order_Number__c", "type": ["null", "string"], "default": None},
{"name": "Amount__c", "type": ["null", "double"], "default": None},
],
})
original = {
"CreatedDate": 1764589423000,
"CreatedById": "005xx0000012345AAA",
"Order_Number__c": "SO-1001",
"Amount__c": None,
}
buffer = io.BytesIO()
fastavro.schemaless_writer(buffer, schema, original)
payload = buffer.getvalue()
print(len(payload), "bytes")
decoded = fastavro.schemaless_reader(io.BytesIO(payload), schema)
print(decoded)
assert decoded == originalThe payload is only a few dozen bytes. The field names don't appear in it, which shows how much the schema carries.
Reading the decoded values
Salesforce schemas follow a few conventions that affect your code.
Nullable fields are unions
A custom field such as Order_Number__c is usually declared as ["null", "string"]. This is an Avro union, meaning the value is either null or a string. With fastavro, the decoded dictionary holds the plain value or None. It does not wrap the value in a type tag. Always handle None, because a field a publisher didn't set is still present in the dictionary.
Timestamps are numbers
Fields such as CreatedDate are declared as long. In the events described in this tutorial, the value is milliseconds since the Unix epoch. Convert it yourself if you need a datetime:
from datetime import datetime, timezone
def normalize(record):
out = dict(record)
created = out.get("CreatedDate")
if isinstance(created, int):
out["CreatedDate"] = datetime.fromtimestamp(created / 1000, tz=timezone.utc)
return outCheck the schema JSON for the topic you use. If a field carries a logicalType, fastavro may convert it for you. Don't assume a conversion that the schema doesn't declare.
Nested records and standard fields
Platform events carry standard fields, such as CreatedDate, CreatedById, and ReplayId, alongside your custom __c fields. Change Data Capture events add a nested ChangeEventHeader record, which a later chapter covers. Nested records decode into nested dictionaries.
Schema evolution and old events
Schemas change. Someone adds a field to a platform event, and the topic gets a new schema ID. Two situations follow from this:
- A live stream crosses a schema change. Events published before the change carry the old
schema_id, and later events carry the new one. Your cache handles this automatically, because the first event with an unseen ID triggers aGetSchemacall. - You replay old events. A subscription that starts from a stored replay ID may receive events written with several schema versions. Each event still carries its own
schema_id, so the same code decodes them correctly.
The rule is to decode every event with the schema named in that event. This is the writer schema. Don't decode it with the "current" schema from GetTopic.
If you want records in one fixed shape regardless of version, fastavro accepts a reader schema as a third argument. Avro then resolves the differences, filling in defaults for fields the writer didn't have:
record = fastavro.schemaless_reader(io.BytesIO(payload), writer_schema, reader_schema)This works only when the two schemas are compatible, and it depends on defaults existing for added fields. Most subscribers don't need it. They read the dictionary and use .get() for fields that may be missing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `fastavro.reader` raises an error about the file header | Used the container reader on a schemaless payload | Use `schemaless_reader` |
| Garbled strings, huge numbers, or `UnicodeDecodeError` | Decoded with a schema that did not write the payload | Look up the schema by the event's `schema_id` |
| `EOFError` or "read past end" style failures | Schema expects more fields than the payload contains | Same cause as above, or the payload was truncated |
| `KeyError` on a field you expect | Field missing from an older schema version | Use `record.get("Field__c")` |
| Unexpected `None` values | Nullable union field was not set by the publisher | Treat `None` as "not provided" |
| Repeated `GetSchema` calls for the same ID | Cache keyed incorrectly or recreated per event | Keep one module-level or per-client cache |
Design notes for a production decoder
- Fail loudly, but per event. If decoding one event raises, log the
schema_id, the eventid, and the replay ID, then decide whether to skip or stop. Silently dropping an event hides data loss. - Decode after you record position. Keep decoding separate from tracking the replay ID, so one malformed payload does not stop you from knowing how far you have read.
- Keep the cache thread-safe if you decode in workers. A plain dictionary is fine for one thread. With several, guard the fetch-and-store step with a lock, or you may call
GetSchematwice for the same ID. This is wasteful but harmless. - Avoid decoding on the stream thread if it is slow. Heavy post-processing delays your next
FetchRequest, which stalls delivery. A later chapter on flow control covers this.
Exercise
A subscriber replays events from three days ago. The topic's schema gained a new nullable field, Priority__c, two days ago. The code decodes every event using the schema returned by GetTopic at startup. What goes wrong, and what is the fix?
Show answer
Events written three days ago were encoded with the old schema, which has no Priority__c. Decoding them with the newer schema reads bytes in the wrong layout, so the output can be garbled or raise an error, with no guarantee of a clean failure. The fix is to decode each event with the schema identified by that event's own schema_id, fetching it with GetSchema and caching it by ID. Then the old events decode with the old schema and lack Priority__c, so downstream code should read that field with .get("Priority__c").
Exercise
Why does the cache in get_schema use schema_id as its key instead of the topic name?
Show answer
One topic can have several schema versions over its lifetime, and each version has a different schema_id. A topic-keyed cache would return a single schema for all events, which is wrong for any event written under a different version. A schema ID identifies one exact schema, so a cached entry never changes meaning.