# How do external gRPC clients utilize custom headers for authentication and tracing during Pub/Sub API calls?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Pub/Sub API Headers, Tracing and Auth

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-external-grpc-clients-utilize-custom-headers-for-authentication-and-tracing-during-pub-sub-api-calls

## Answer

**Basics:** Pub/Sub API (endpoint `api.pubsub.salesforce.com:7443`) lets external systems publish and subscribe to platform events, change events and real-time events using gRPC with HTTP/2 and Avro-encoded payloads. gRPC metadata is the equivalent of HTTP headers.

**How it works:**
1. Get an OAuth access token and instance URL (for example with the JWT bearer flow).
2. Open a TLS channel to the Pub/Sub endpoint.
3. Attach the metadata on each call: `accesstoken: <token>`, `instanceurl: <https://MyDomain.my.salesforce.com>`, `tenantid: <18-char org ID>`.
4. Call `GetTopic` and `GetSchema` to learn the schema, then `Subscribe` with a `FetchRequest` (topic name, replay preset, number of events requested).
5. Decode Avro payloads, process, and request more events to keep flow control going.

**Advanced / deep dive:** For tracing, add your own metadata (for example `x-correlation-id` or a W3C `traceparent`) through gRPC interceptors so your side's logs and gateway link up. Do not assume Salesforce echoes or propagates them into event payloads (verify). For end-to-end tracing across systems, put a correlation ID in the event payload field. Renew tokens before they expire, because a call with an expired token fails with an authentication error. Flow control matters: the client controls how many events it requests, so a slow consumer will not be flooded. Use `ReplayPreset` `LATEST`, `EARLIEST` or `CUSTOM` with a stored replay ID. Managed subscriptions that store the replay position in Salesforce are available in newer releases (verify status).

**Code / config example:**
```python
import grpc
creds = grpc.ssl_channel_credentials()
channel = grpc.secure_channel('api.pubsub.salesforce.com:7443', creds)
metadata = (
    ('accesstoken', access_token),
    ('instanceurl', instance_url),
    ('tenantid', org_id),
    ('x-correlation-id', 'order-sync-7f3a'),   # custom, for your own tracing
)
# stub.Subscribe(request_iterator, metadata=metadata)
```

**Hidden gotchas & must-remember points:**
- Metadata keys in gRPC must be lowercase.
- Missing or wrong `tenantid` or `instanceurl` leads to authentication failures that look like token problems.
- Payloads are Avro, so you need the schema ID and `GetSchema`.
- Schema changes create new schema IDs, so cache by ID.
- The user must have permission on the event or object.
- Keep-alive and reconnect logic is the client's job.

**Best practice:** Wrap token refresh and metadata in one interceptor, and carry a correlation ID in the payload.

---
Source: ForceChallenges · last updated 2026-11-02
