Sub topic 1
What the Pub/Sub API is and when to use it
The Salesforce Pub/Sub API lets an external program receive events from a Salesforce org, and publish events to it, over a single long-lived connection. This chapter explains what the API is, how it differs from the other ways to move events in and out of Salesforce, and how to decide whether it fits your project. Later chapters cover authentication, schemas, and the Subscribe call in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic Salesforce concepts: orgs, objects, and connected apps or external client apps.
- Comfort reading and writing Python.
- Familiarity with OAuth 2.0 access tokens.
- A general idea of publish/subscribe messaging.
You do not need to know gRPC or Avro yet. The next chapters introduce both.
What the API is
The Pub/Sub API is a gRPC interface to the Salesforce event bus. gRPC is a remote procedure call framework that runs over HTTP/2 and sends compact binary messages. The event bus is the part of Salesforce that stores and delivers events. Salesforce publishes the API at api.pubsub.salesforce.com:7443.
Through this API a client can:
- Subscribe to a topic and receive events as they happen.
- Publish events to a topic.
- Look up a topic and the schema that describes its events.
Event payloads are encoded in Avro, a compact binary format. Each payload is only readable with the schema it was written with, so a subscriber fetches the schema from the API and uses it to decode events.
The API exposes these remote procedures (RPCs):
| RPC | Purpose |
|---|---|
| `GetTopic` | Returns information about a topic, including whether you can subscribe and its schema ID |
| `GetSchema` | Returns the Avro schema for a schema ID |
| `Subscribe` | Opens a stream that delivers events to the client |
| `Publish` and `PublishStream` | Send events to a topic |
| `ManagedSubscribe` | Subscribes with replay position tracked by Salesforce |
This tutorial focuses on subscribing. The chapter on managed subscriptions covers ManagedSubscribe.
What you can receive
A topic is a named channel of events. The Pub/Sub API serves these kinds of topics:
- Platform events, defined by you as custom objects ending in
__e. A topic looks like/event/Order_Shipped__e. - Change Data Capture (CDC) events, which describe record creates, updates, deletes, and undeletes. A topic looks like
/data/AccountChangeEvent. There is also a combined channel,/data/ChangeEvents. - Real-time event monitoring events, such as
/event/LoginEventStream.
The next chapter looks at each kind more closely.
How events flow
A publisher might be an Apex trigger, a Flow, an external system, or Salesforce itself when a record changes. The publisher writes the event to the event bus. The bus keeps it for a limited time, and each subscriber reads it over its own stream.
Three properties of this model shape how you design a subscriber:
- Events are retained, not queued per subscriber. The bus keeps events for a retention window, which is up to three days for most event types. Any subscriber can read any retained event, so a client that was offline can catch up.
- Each event has a replay ID. A replay ID marks the event's position in the stream. A subscriber saves it and uses it to resume from a known place.
- The client asks for events. The subscriber tells the server how many events it is ready for, and the server sends no more than that. This is flow control, covered in its own chapter.
How it compares to other options
Salesforce has several ways to react to changes or send data out. The Pub/Sub API is one of them, and it is the one Salesforce recommends for new external integrations that consume events.
| Option | Transport and format | Typical use |
|---|---|---|
| Pub/Sub API | gRPC over HTTP/2, binary Avro | External systems consuming platform events or CDC, especially at higher volume |
| Streaming API (CometD) | Bayeux over long polling or WebSocket, JSON | Older integrations, and browser clients such as Lightning components using the `empApi` module |
| Apex triggers on events | Runs inside Salesforce | Logic that stays on the platform |
| Flow with event triggers | Runs inside Salesforce | Low-code reactions to events |
| Outbound messages | SOAP calls from Salesforce to an endpoint | Workflow-style push to a fixed URL |
| Event Relay | Salesforce pushes events to Amazon EventBridge | Delivery to AWS without running your own subscriber |
The main differences from CometD are the binary format, which makes payloads smaller, and HTTP/2 streaming. Also, the Pub/Sub API gives you explicit flow control through num_requested. CometD pushes events as they come and gives the client less control over pace.
The Pub/Sub API is a pull-style stream over a connection that your client opens. Salesforce does not call your server. This has a practical benefit: your subscriber can run behind a firewall with no inbound ports open, as long as it can make an outbound HTTPS-style connection to port 7443.
When to use it
The Pub/Sub API is a good fit when:
- The consumer lives outside Salesforce, such as a data pipeline, a microservice, or a search index updater.
- You need to resume after downtime without losing events, and the downtime is shorter than the retention window.
- You want to control the pace of delivery so a slow consumer is not overwhelmed.
- You are building something new and have no existing CometD code to preserve.
- You also need to publish events from outside Salesforce using the same API.
It is a poor fit when:
- The logic can run inside Salesforce. An Apex trigger or Flow is simpler and needs no external service, token handling, or reconnection code.
- Your consumer is a browser component. The
lightning/empApimodule is built for that case. - You need to store events for longer than the retention window. The bus is not an archive. You must write events to your own storage.
- Your environment cannot use gRPC. Some proxies and older networks do not handle HTTP/2 streaming well.
A first connection check
Before generating any stubs, you can confirm that your network allows a TLS connection to the API. This script needs only the grpcio package.
import grpc
ENDPOINT = "api.pubsub.salesforce.com:7443"
def can_reach_pubsub(timeout_seconds=10):
credentials = grpc.ssl_channel_credentials()
with grpc.secure_channel(ENDPOINT, credentials) as channel:
try:
grpc.channel_ready_future(channel).result(timeout=timeout_seconds)
return True
except grpc.FutureTimeoutError:
return False
if __name__ == "__main__":
print("reachable:", can_reach_pubsub())If this prints reachable: False, a firewall or proxy is likely blocking HTTP/2 traffic on port 7443. Fix that before debugging anything else. The check does not authenticate, so a True result says nothing about your credentials.
Common mistakes at this stage
- Treating the event bus as a durable store. Events expire. Design the subscriber to save what it needs.
- Assuming exactly-once delivery. After a reconnect you may see an event again, so make your handler safe to run twice on the same event. The resilience chapter returns to this.
- Choosing the API when on-platform automation would do. An external subscriber adds a service to deploy, monitor, and secure.
- Mixing up topic names. Platform events use
/event/and CDC uses/data/. A wrong prefix or a missing__esuffix gives an error fromGetTopic.
What comes next
The following chapters build a working subscriber step by step. You will look at topics and event types, then gRPC and the proto file. After that you will authenticate, discover the schema, decode Avro, and open the Subscribe stream.
Exercise
Your team needs to send every Account update to an external search index. The index is a service outside Salesforce, and it may be offline for a few hours during deployments. Would you choose the Pub/Sub API, and why? Name the topic you would subscribe to and the feature that lets the service catch up after downtime.
Show answer
Yes. The consumer is external, and the Pub/Sub API retains events on the bus (up to about three days for CDC), so an offline subscriber can resume without loss. Subscribe to the Change Data Capture topic /data/AccountChangeEvent. The service saves the replay ID of the last event it processed and, after downtime, starts a new Subscribe stream from that replay ID. An Apex trigger would not work well here because the search index is outside Salesforce.
Exercise
A colleague says the Pub/Sub API is a good place to archive events for a seven-year audit requirement. What is wrong with this plan?
Show answer
The event bus only retains events for a limited window, which is up to about three days for most event types. It is not long-term storage. The subscriber must write events to its own durable storage, such as a database or object store, to meet a seven-year requirement.