Sub topic 13
Subscribing from External Systems with Pub/Sub API
Apex triggers, flows, and Lightning Web Components all run inside Salesforce. An external system, such as a data warehouse loader, a middleware service, or a microservice, needs another way to receive events. Pub/Sub API is that way. This chapter explains how it works, how to consume events from it, and where it fails.
This chapter assumes you have read the earlier chapters on defining platform events, replay IDs, and the retention window. It also assumes you can run a small Python script and have an OAuth-capable connected app or external client app in your org.
What Pub/Sub API is
Pub/Sub API is a gRPC API. gRPC is a remote procedure call framework that runs over HTTP/2 and sends messages as Protocol Buffers (protobuf). Three properties matter for subscribers:
- One long-lived stream. The client opens a bidirectional stream and Salesforce pushes events down it. You do not poll.
- Avro payloads. Each event arrives as binary Avro. Avro is a compact serialization format that needs a schema to decode. The event carries a
schema_id, and you fetch the schema separately. - Client-controlled flow. The server sends only as many events as the client has asked for.
The same API also publishes events and subscribes to change data capture and other event channels. This chapter covers subscribing to a platform event.
| Concern | CometD (empApi, Streaming API) | Pub/Sub API |
|---|---|---|
| Protocol | Bayeux over HTTP long polling | gRPC over HTTP/2 |
| Payload | JSON | Binary Avro, schema fetched separately |
| Replay ID type | Number | Opaque bytes |
| Backpressure | None, the server pushes | Client requests a number of events |
| Typical use | Browser components, simple clients | Server-side integrations, high volume |
Use empApi for Lightning components, because it handles authentication and the session for you. Use Pub/Sub API for server-side consumers.
The conversation between client and Salesforce
A subscriber makes a few calls in a fixed order.
The numbered steps in practice:
- Authenticate with OAuth and get an access token. The server-side flows (JWT bearer or client credentials) suit unattended services.
- Connect to
api.pubsub.salesforce.com:7443over TLS. - Send three pieces of metadata with every call:
accesstoken,instanceurl, andtenantid. The tenant ID is the 18-character org ID. - Open the
Subscribestream and send aFetchRequestthat names the topic. For a platform event the topic is/event/Order_Shipped__e. - Read
FetchResponsemessages from the stream. Fetch the Avro schema for each newschema_id, cache it, and decode the payload. - Record the replay ID of the last event you finished processing.
Choosing where to start: replay presets
The FetchRequest includes a replay preset. It tells Salesforce where in the event stream to begin.
| Preset | Behavior |
|---|---|
| `LATEST` | Only events published after the subscription starts. |
| `EARLIEST` | Every event still in the retention window. |
| `CUSTOM` | Events after the replay ID you supply in `replay_id`. |
A production consumer normally starts with CUSTOM and the replay ID it saved last. It falls back to LATEST only on its first run. Events stay available for 72 hours for standard-volume and high-volume platform events, so a consumer that is down for longer than that loses events it never saw. Check the current retention figure for your edition in the platform events developer guide before you size an outage budget.
Flow control
The client states how many events it is willing to receive in num_requested. The server stops sending when that count is used up. When your client has processed a batch, it sends another FetchRequest with a new count. The topic name and replay settings in later requests are ignored. Only the count matters.
This is backpressure. A slow consumer does not get flooded, and events wait in the bus until it asks for them. Keep num_requested modest, for example 10 to 100, so that a crash does not leave a large batch of unprocessed events in memory.
When no events are available, Salesforce still sends a FetchResponse with an empty events list and a current latest_replay_id. This is a keepalive. Treat it as a heartbeat. It also tells you the stream is alive and gives you a replay ID you can store.
A working subscriber
First download pubsub_api.proto from the forcedotcom/pub-sub-api repository on GitHub. Then generate the Python stubs and install the libraries:
pip install grpcio grpcio-tools avro
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. pubsub_api.protoThe following script subscribes to Order_Shipped__e, decodes each event, and tracks the replay ID. It takes the token, instance URL, and org ID from environment variables.
import io
import os
import queue
import avro.io
import avro.schema
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
TOPIC = "/event/Order_Shipped__e"
BATCH = 10
metadata = (
("accesstoken", os.environ["SF_ACCESS_TOKEN"]),
("instanceurl", os.environ["SF_INSTANCE_URL"]),
("tenantid", os.environ["SF_ORG_ID"]),
)
schemas = {} # schema_id -> parsed Avro schema
def get_schema(stub, schema_id):
if schema_id not in schemas:
info = stub.GetSchema(pb2.SchemaRequest(schema_id=schema_id), metadata=metadata)
schemas[schema_id] = avro.schema.parse(info.schema_json)
return schemas[schema_id]
def decode(stub, consumer_event):
schema = get_schema(stub, consumer_event.event.schema_id)
decoder = avro.io.BinaryDecoder(io.BytesIO(consumer_event.event.payload))
return avro.io.DatumReader(schema).read(decoder)
def request_stream(requests):
while True:
yield requests.get() # blocks until the main loop asks for more
def main():
last_replay_id = None # load your saved value here; None means first run
requests = queue.Queue()
first = pb2.FetchRequest(topic_name=TOPIC, num_requested=BATCH)
if last_replay_id:
first.replay_preset = pb2.ReplayPreset.CUSTOM
first.replay_id = last_replay_id
else:
first.replay_preset = pb2.ReplayPreset.LATEST
requests.put(first)
with grpc.secure_channel(
"api.pubsub.salesforce.com:7443", grpc.ssl_channel_credentials()
) as channel:
stub = pb2_grpc.PubSubStub(channel)
for response in stub.Subscribe(request_stream(requests), metadata=metadata):
for ce in response.events:
payload = decode(stub, ce)
print("Order shipped:", payload["Order_Number__c"])
last_replay_id = ce.replay_id # persist this durably in real code
if not response.events:
last_replay_id = response.latest_replay_id
# Ask for another batch once this one is handled.
requests.put(pb2.FetchRequest(topic_name=TOPIC, num_requested=BATCH))
if __name__ == "__main__":
main()Two details in this script matter. The request generator blocks on a queue, which keeps the stream open for the lifetime of the process. If it returned, the stream would close. The replay ID is raw bytes, so store it as bytes (for example in a database blob column) and do not convert it to a number.
Failure modes and gotchas
- Duplicate delivery. If your process crashes after handling an event but before saving the replay ID, it restarts from the older ID and sees the event again. Make processing idempotent. A natural key from the payload, such as
Order_Number__c, works for this. - Replay ID saved too early. If you save the ID before the work finishes and then crash, you lose the event. Save after the work succeeds.
- Expired replay ID. If the consumer is offline past the retention window, a
CUSTOMreplay ID may refer to events that no longer exist, and the stream fails. Detect that error, alert someone, and decide whether to resynchronize from the source data and then resume fromLATEST. - Expired access token. The stream authenticates when it opens. A token that expires later can produce an authentication error that ends the stream. Refresh the token and reconnect with your saved replay ID.
- Schema changes. Adding a field to the event gives later events a new
schema_id. Caching schemas by ID, as the script does, handles this. Caching a single schema for the whole run does not. - Subscription counts. Each event has a limit on concurrent subscribers across CometD and Pub/Sub API. Many unneeded consumer processes can exhaust it. See the allocations chapter for the limits.
Choosing Pub/Sub API
Choose Pub/Sub API when the consumer is a server-side process outside Salesforce, when you need backpressure, or when payload size and throughput matter. Choose empApi for a browser component. Choose a trigger or flow when the work belongs inside Salesforce. If one external consumer needs many different event types, subscribe to each topic on its own stream.
Exercise
Your external consumer processes an event, then crashes before it saves the replay ID. After restart it resumes with CUSTOM and the last saved replay ID. What happens to that event, and what design property protects you?
Show answer
Salesforce delivers the event again, because the saved replay ID is older than the event. The consumer must be idempotent, so processing the same event twice has the same result as processing it once, for example by keying writes on a unique field such as OrderNumber_c. Saving the replay ID only after processing succeeds gives at-least-once delivery. Saving it before processing would risk losing the event instead.
Exercise
A consumer sends FetchRequest with num_requested set to 5 and then does nothing more. Fifty events are waiting. How many arrive, and what must the client do to receive the rest?
Show answer
Only 5 events arrive, because the server never sends more than the client has requested. The client must send further FetchRequest messages on the same stream with a new num_requested value, normally after it finishes processing the current batch.