Sub topic 15
Testing and troubleshooting a subscriber
This chapter covers how to test a Pub/Sub API subscriber without a live org, and how to find the cause when a live one misbehaves. It assumes you have read the earlier chapters on authentication, the Subscribe RPC, flow control, replay IDs, and reconnection. You should be comfortable with pytest-style tests and with reading gRPC errors in Python.
Why subscribers are hard to debug
A subscriber is a long-lived process. When it fails, the symptom is often silence: no output and no error. That silence has several possible causes:
- The credentials are wrong.
- The topic has no events.
- The flow-control window is closed.
- The stream has dropped.
Good testing narrows the search before you ever connect to an org. Good troubleshooting works through the layers in order: transport, authentication, topic, delivery, and decoding.
Testing without an org
Most subscriber logic does not need the network. The parts worth testing on their own are:
- Decoding a payload with a schema.
- Handling a response, including keepalives.
- Updating the replay ID checkpoint.
- Classifying errors.
To make that possible, keep gRPC calls at the edges. Functions that take a response object and a schema are easy to test. Functions that open channels are not.
Round-trip a payload with fastavro
fastavro.schemaless_writer produces the same kind of binary payload the server sends. Because of that, you can build realistic fake events from a schema you define in the test.
import io
from types import SimpleNamespace
import fastavro
SCHEMA = fastavro.parse_schema({
"type": "record",
"name": "OrderEvent",
"namespace": "com.example",
"fields": [
{"name": "OrderNumber__c", "type": "string"},
{"name": "Amount__c", "type": ["null", "double"], "default": None},
],
})
def encode(record):
buf = io.BytesIO()
fastavro.schemaless_writer(buf, SCHEMA, record)
return buf.getvalue()
def decode(payload, schema):
return fastavro.schemaless_reader(io.BytesIO(payload), schema)
def make_response(records, replay_start=1, latest=b"latest"):
events = [
SimpleNamespace(
replay_id=str(replay_start + i).encode(),
event=SimpleNamespace(schema_id="abc", payload=encode(rec)),
)
for i, rec in enumerate(records)
]
return SimpleNamespace(events=events, latest_replay_id=latest)
def handle_response(response, schema, checkpoint):
"""Decode each event, then advance the checkpoint. Returns the records."""
records = []
for consumer_event in response.events:
records.append(decode(consumer_event.event.payload, schema))
checkpoint["replay_id"] = consumer_event.replay_id
if not response.events:
checkpoint["replay_id"] = response.latest_replay_id
return records
def test_roundtrip():
rec = {"OrderNumber__c": "A-1", "Amount__c": 12.5}
assert decode(encode(rec), SCHEMA) == rec
def test_events_advance_checkpoint():
checkpoint = {}
response = make_response([{"OrderNumber__c": "A-1", "Amount__c": None}])
records = handle_response(response, SCHEMA, checkpoint)
assert records[0]["OrderNumber__c"] == "A-1"
assert checkpoint["replay_id"] == b"1"
def test_keepalive_uses_latest_replay_id():
checkpoint = {"replay_id": b"1"}
handle_response(make_response([], latest=b"99"), SCHEMA, checkpoint)
assert checkpoint["replay_id"] == b"99"The last test covers a case people often skip. A keepalive is a response with no events, and it still carries latest_replay_id. If your handler assumes response.events is never empty, it will either crash or ignore the keepalive.
Test schema drift
Schemas change when an admin adds a field to a platform event or custom object. Add a test that decodes with a schema containing an extra nullable field, and confirm your handler uses record.get(...) for optional fields. Fetching a schema per schema ID, as in the earlier chapter, keeps old and new events decodable side by side. Do not cache one schema for the whole topic.
Testing against a real org
A sandbox or scratch org gives you the end-to-end check. Run the subscriber, then publish an event from a second process. Publishing through the REST API is the quickest way:
import requests
API_VERSION = "v62.0"
def publish_test_event(instance_url, access_token, event_api_name, fields):
url = f"{instance_url}/services/data/{API_VERSION}/sobjects/{event_api_name}"
resp = requests.post(
url,
json=fields,
headers={"Authorization": f"Bearer {access_token}"},
timeout=30,
)
resp.raise_for_status()
return resp.json()
if __name__ == "__main__":
import os
print(publish_test_event(
os.environ["SF_INSTANCE_URL"],
os.environ["SF_ACCESS_TOKEN"],
"Order_Event__e",
{"OrderNumber__c": "TEST-1", "Amount__c": 10.0},
))Adjust the API version to one your org supports. A successful response includes "success": true. That tells you the event was published, but not that your subscriber can see it.
Use these checks to tell which side is at fault:
- Start the subscriber with
LATEST, then publish. ALATESTsubscriber only sees events published after the stream opens, so publishing first produces nothing. - Stop the subscriber, publish three events, then restart it from the stored replay ID. All three should arrive once each. This exercises the resume path that matters in production.
- Kill the network, or the process, mid-stream. Confirm the restart resumes without gaps.
Triage order
Work from the bottom layer up. Each check rules out everything beneath it.
Reading errors
gRPC errors surface in Python as grpc.RpcError. The status code and details are the first things to read. The error also carries trailing metadata, and Salesforce puts further detail there. Log all three.
import grpc
RETRYABLE = {
grpc.StatusCode.UNAVAILABLE,
grpc.StatusCode.DEADLINE_EXCEEDED,
grpc.StatusCode.INTERNAL,
}
def explain(err: grpc.RpcError) -> str:
trailers = dict(err.trailing_metadata() or ())
return f"{err.code().name}: {err.details()} trailers={trailers}"
def classify(err: grpc.RpcError) -> str:
code = err.code()
if code == grpc.StatusCode.UNAUTHENTICATED:
return "refresh_token_then_retry"
if code in RETRYABLE:
return "reconnect_with_backoff"
return "fail"A reconnect loop should call explain before it decides what to do. Without that log line, an INVALID_ARGUMENT caused by a stale replay ID looks the same as a network blip.
Common symptoms and causes
| Symptom | Likely cause | What to check |
|---|---|---|
| Connection hangs or resets | Proxy or firewall blocks gRPC or HTTP/2 | Endpoint `api.pubsub.salesforce.com:7443`, outbound TLS, proxy settings |
| `UNAUTHENTICATED` | Expired access token, wrong instance URL, wrong tenant ID | Header names `accesstoken`, `instanceurl`, `tenantid`, token age |
| `NOT_FOUND` on topic | Misspelled topic or missing prefix | Names like `/event/Order_Event__e` or `/data/AccountChangeEvent` |
| `PERMISSION_DENIED` | The user lacks access to the event or object | Object and event permissions for the integration user |
| Stream open, no events | Started at `LATEST`, or nothing published | Publish a test event after the stream opens |
| Events stop after N | `num_requested` never replenished | Send a new `FetchRequest` after each batch |
| Error on resume | Replay ID expired or invalid | Retention window, stored ID bytes unchanged |
| Decode error or garbage values | Wrong schema for the event | Use the event's own `schema_id` |
| Duplicates after restart | Checkpoint saved before processing, or after a crash | Save after processing, and make handlers idempotent |
For NOT_FOUND and PERMISSION_DENIED, call GetTopic directly. It is the cheapest way to separate a topic problem from a Subscribe problem, because it fails before any stream exists. It also tells you whether can_subscribe is true.
Stream open, nothing arriving
This is the most common report, and it has four usual causes:
- The preset is
LATESTand the event was published earlier. - Your first
FetchRequestwas never sent. In the generator pattern, the queue must be seeded before the loop starts. - The window is exhausted. If you ask for 10 events and never send another
FetchRequest, the server stops after 10. - The topic name is valid, but nothing is publishing to it. For Change Data Capture topics, the object must be selected for change events.
Log each FetchRequest you send and each response size. Two log lines are usually enough to show which of these you are in.
Resume failures
Replay IDs are opaque bytes. If you store one as text and decode it differently, or trim it, the server rejects it. Store the raw bytes, or base64 them for text storage, and decode exactly the same way. A replay ID older than the retention window also fails. In that case, fall back to a policy you chose in advance, either EARLIEST or LATEST, and log that you did so, because skipping events silently is data loss.
Observability worth adding
A few log fields turn a mystery into a short search:
- The topic name and the replay preset or replay ID used when opening the stream.
- Each
num_requestedvalue sent. - Event count and
latest_replay_idper response. - The time since the last response. A long gap on a quiet topic is normal, because keepalives still arrive. No responses at all, not even keepalives, means the stream is stalled.
- Reconnect count and the reason for each reconnect.
A short pre-release checklist
- Unit tests cover decoding, keepalive handling, checkpoint order, and error classification.
- A sandbox run shows events arriving after publish, and none missed across a restart.
- A test with an expired token shows a refresh and a successful reconnect.
- Logs show enough to answer "what did we ask for, and what did we get back?"
Exercise
A subscriber started with the LATEST preset logs "stream opened" but never prints an event. The REST call that publishes the event returned success. Name two checks, in order, that you would make.
Show answer
First, confirm the event was published after the stream opened, because LATEST skips earlier events. Republish and watch. Second, confirm the first FetchRequest was sent with a numrequested greater than zero, and that new FetchRequests are sent after each batch. If both pass, call GetTopic to verify the topic name and that cansubscribe is true.
Exercise
Why should a unit test for your response handler include a response with an empty events list?
Show answer
A keepalive arrives as a response with no events but with a latestreplayid. The handler must cope with the empty list and can use latestreplayid to advance the checkpoint. Without the test, a crash or ignored checkpoint on keepalives goes unnoticed until production.