Sub topic 12
Subscribing to Change Data Capture events
This chapter assumes you can already open a Subscribe stream, decode Avro payloads with a cached schema, and track replay IDs, as covered in the earlier chapters. Change Data Capture (CDC) is the second kind of event you can receive from the Pub/Sub API, after platform events. The transport is the same. What changes is the topic name, the payload shape, and some rules you must follow to interpret the data correctly.
What Change Data Capture publishes
Change Data Capture is a Salesforce feature that publishes an event each time a record is created, updated, deleted, or undeleted. You don't define the event schema. Salesforce generates it from the object's fields. Your subscriber receives a stream of record changes without polling the REST API or running a SOQL query on a timer.
CDC events differ from platform events in four ways:
- You don't publish them. Salesforce publishes them when a transaction commits.
- You must turn them on per object. In Setup, open Change Data Capture and move the objects you want to the selected list. An object that isn't selected has no topic to subscribe to.
- Every payload starts with a
ChangeEventHeaderrecord that describes the change. - An update event carries only the fields that changed, not the whole record.
CDC events are retained for the same replay window as other high-volume events (72 hours at the time of writing). Check your org's current limits, because allocations vary by edition and add-on licenses.
Topic names for change events
The topic name follows a fixed pattern. Pass it as topic_name in TopicRequest and FetchRequest.
| What you want | Topic name |
|---|---|
| Changes to one standard object, such as Account | `/data/AccountChangeEvent` |
| Changes to one custom object `Invoice__c` | `/data/Invoice__ChangeEvent` |
| Changes to every selected object | `/data/ChangeEvents` |
| Changes to the objects in a custom channel | `/data/MyChannel__chn` |
The all-objects topic /data/ChangeEvents is convenient, but events for different objects have different schemas. Your decoder must then look up the schema by the schema_id on each event, which the caching code from the Avro chapter already does. A per-object topic gives you one schema and simpler handler code. A custom channel lets you group several objects into one stream and subscribe to just that group.
Call GetTopic on the name before you subscribe. If the object isn't enabled for CDC, the call fails, which tells you about the Setup problem before you look for a stream problem.
How a change becomes an event
Events are published after the commit. A rolled-back transaction produces no event. Events within one transaction share a transactionKey and carry a sequenceNumber, so you can reassemble the order of changes inside it.
The ChangeEventHeader
After decoding, the record has a ChangeEventHeader field and then the object's own fields. These are the header fields you will use most:
| Field | Meaning |
|---|---|
| `entityName` | The object that changed, such as `Account`. Needed when you use the all-objects topic. |
| `recordIds` | A list of IDs. One event can describe the same change to several records. |
| `changeType` | `CREATE`, `UPDATE`, `DELETE`, `UNDELETE`, or a `GAP_` variant. |
| `changedFields` | The fields whose values changed, in bitmap form. |
| `nulledFields` | Fields that were set to null, in bitmap form. |
| `diffFields` | Long text fields that changed, in bitmap form. |
| `changeOrigin` | How the change was made, for example through an API client. |
| `commitUser` | The ID of the user who made the change. |
| `commitTimestamp` | When the transaction committed, in milliseconds since the Unix epoch. |
| `transactionKey` | Identifies the transaction. |
| `sequenceNumber` | Position of this change within the transaction. |
Always treat recordIds as a list, even when it holds one item. A bulk update of 200 accounts can arrive as one event with 200 IDs.
Bitmap-encoded field lists
In the Pub/Sub API, changedFields, nulledFields, and diffFields are not lists of field names. They are lists of strings that encode a bitmap. A top-level entry looks like "0x0A". Each bit position matches the position of a field in the event's Avro schema, with the lowest bit meaning the first field. The bit is 1 if that field changed.
So you need the schema, and the same schema version that produced the event. The cached schema from GetSchema serves this purpose. Compound fields such as Address or Name add extra entries that describe which nested parts changed. These entries start with the parent field's index followed by a dash, for example "2-0x03". The next example reads only the top-level entry and skips the nested ones.
def decode_bitmap(schema, bitmap_strings):
"""Return top-level field names whose bits are set.
schema is a parsed Avro record schema (a dict with a "fields" list).
Entries for nested compound fields (such as "2-0x03") are skipped.
"""
names = []
for entry in bitmap_strings:
if not entry.startswith("0x"):
continue
bits = int(entry, 16)
for index, field in enumerate(schema["fields"]):
if (bits >> index) & 1:
names.append(field["name"])
return names
def handle_change(record, schema):
header = record["ChangeEventHeader"]
change_type = header["changeType"]
entity = header["entityName"]
ids = header["recordIds"]
if change_type.startswith("GAP_"):
print(f"{change_type} on {entity}: refetch {ids} from the API")
return
if change_type == "UPDATE":
changed = decode_bitmap(schema, header["changedFields"])
cleared = decode_bitmap(schema, header["nulledFields"])
values = {name: record.get(name) for name in changed}
print(f"UPDATE {entity} {ids}: set {values}, cleared {cleared}")
else:
print(f"{change_type} {entity} {ids}")
if __name__ == "__main__":
demo_schema = {
"type": "record",
"name": "AccountChangeEvent",
"fields": [
{"name": "ChangeEventHeader", "type": "string"},
{"name": "Name", "type": ["null", "string"]},
{"name": "Industry", "type": ["null", "string"]},
{"name": "Phone", "type": ["null", "string"]},
],
}
demo_record = {
"ChangeEventHeader": {
"entityName": "Account",
"recordIds": ["001000000000001AAA"],
"changeType": "UPDATE",
"changedFields": ["0x0A"],
"nulledFields": ["0x04"],
"diffFields": [],
},
"Name": "Acme Corp",
"Industry": None,
"Phone": "555-0100",
}
handle_change(demo_record, demo_schema)The demo header sets 0x0A, binary 1010, so bits 1 and 3 are set. Those are Name and Phone. The null bit 0x04 is bit 2, which is Industry. The output is:
UPDATE Account ['001000000000001AAA']: set {'Name': 'Acme Corp', 'Phone': '555-0100'}, cleared ['Industry']In your subscriber, call get_schema(stub, metadata, consumer_event.event.schema_id) next to decode_event, then pass both the record and the schema to handle_change.
Distinguishing "not changed" from "set to null"
An update event holds a null for every field that did not change, because the Avro fields are optional unions. A null value alone therefore means nothing. Use the bitmaps to decide:
- If the field is in
changedFields, the new value is in the payload. - If the field is in
nulledFields, the new value is null. - If the field is in neither, the field did not change. Ignore its value.
A handler that copies every non-null field into a local database misses the nulling case. A handler that copies every field overwrites good data with nulls. Only the bitmaps let you tell the cases apart.
Gap events and overflow events
Occasionally Salesforce can't produce a full change event, for example after an internal error. It publishes a gap event instead, with a type such as GAP_UPDATE or GAP_DELETE. A gap event has the header and record IDs but no field values. A GAP_OVERFLOW event stands in for a transaction that changed too many records to describe individually.
A gap event means your copy of the data may be stale. Handle it by refetching the affected records from the REST API, or by running a full resync for an overflow. Don't silently skip it.
Common errors
- Subscribing before enabling the object. The topic doesn't exist until you select the object in Setup. Check with
GetTopic. - Using the wrong suffix on a custom object. The topic for
Invoice__cis/data/Invoice__ChangeEvent. Writing/data/Invoice__cChangeEventfails. - Reading
recordIds[0]only. You lose every other record in a batched event. - Decoding bitmaps against the wrong schema. If you cache by topic name instead of by schema ID, a schema change after a field is added shifts the bit positions. Cache by
schema_id. - Treating nulls as deletions. Use
nulledFields, as above. - Assuming one event per record change. Events can batch, and a record changed several times in one transaction can appear in several events.
Exercise
A subscriber on /data/ContactChangeEvent receives an UPDATE event where Email is null in the payload, and the header shows changedFields = ["0x04"] and nulledFields = []. The schema's field list is ChangeEventHeader, FirstName, LastName, Email. Was the email cleared? Which field does the changedFields bitmap actually point to?
Show answer
Bit 2 of 0x04 (binary 100) is set, which is the field at index 2, LastName. Email is index 3 and is in neither bitmap, so it did not change. Its null value only means "not included". The email was not cleared, because a cleared field would appear in nulledFields.