What architectural advantages does the gRPC-based Pub/Sub API offer over traditional CometD streaming APIs?
Answer
Basics: Streaming APIs push Salesforce events to external systems. The older approach is Streaming API with CometD (Bayeux protocol, HTTP/1.1, JSON). Pub/Sub API is the newer design: a single gRPC endpoint (api.pubsub.salesforce.com:7443) with generated clients in languages such as Java, Python, Go and Node.
How it works:
- Authenticate (OAuth) and send accesstoken, instanceurl and tenantid as gRPC metadata.
- GetTopic returns topic info and the schema ID; GetSchema returns the Avro schema.
- Subscribe: send a FetchRequest with topic_name, replay_preset (LATEST, EARLIEST, CUSTOM with replay_id) and num_requested; the server streams up to that many events.
- The client decodes Avro using the schema, tracks the replay ID, and sends more FetchRequests to request more events (pull-based flow control).
- Publish and PublishStream send events with a schema ID and Avro payload.
Advanced / deep dive: Advantages: binary compact payloads, HTTP/2 multiplexing, built-in back-pressure (the client asks for N events so a slow consumer is not overwhelmed), one API for publish and subscribe, schema evolution through schema IDs, and a modern, language-neutral toolchain. Managed subscriptions (where Salesforce tracks the replay position) exist; verify current availability. Events are retained for 72 hours, so a consumer offline longer must resync. Delivery allocations and publishing limits still apply by edition. CometD remains supported and is what lightning/empApi uses in LWC; choose Pub/Sub API for new external subscribers and keep empApi for UI. gRPC adds operational requirements: HTTP/2-capable proxies and load balancers.
Code / config example:
# Illustrative request flow (not literal client code)
Metadata: accesstoken=<token>, instanceurl=<url>, tenantid=<orgId>
FetchRequest {
topic_name: "/data/AccountChangeEvent"
replay_preset: CUSTOM
replay_id: <last stored replay id>
num_requested: 100
}
# Client: decode Avro payload with schema from GetSchema, persist replay_id, then send next FetchRequest