Sub topic 3
gRPC and bidirectional streaming in brief
This chapter assumes you can read Python and know what an OAuth access token is. It also assumes you know roughly how HTTP request and response pairs work. You don't need prior gRPC experience. The goal is to build the working model that the later chapters rely on: what a gRPC call is, why Subscribe is a stream in both directions, and what that means for the code you write.
What gRPC is
gRPC is a remote procedure call framework. You call a function on a local object (a stub), and the library serializes your arguments, sends them to a server, and returns the deserialized result. Three pieces make this work:
- HTTP/2 is the transport. It multiplexes many independent streams over one TCP connection, supports flow control per stream, and lets either side send data at any time.
- Protocol Buffers (protobuf) is the message format. Messages are defined in a
.protofile and encoded as compact binary. - Generated stubs are client and server code produced from the
.protofile. You never build HTTP requests by hand.
The Salesforce Pub/Sub API is a gRPC service. Its endpoint is api.pubsub.salesforce.com:7443, and the connection is always TLS. A REST API puts the operation in the URL and verb. A gRPC API puts it in the service and method name, such as PubSub/Subscribe.
The four call shapes
Every gRPC method has one of four shapes. The shape depends on whether the client sends one message or many, and whether the server replies with one message or many.
| Shape | Client sends | Server sends | Pub/Sub API example |
|---|---|---|---|
| Unary | One message | One message | `GetTopic`, `GetSchema`, `Publish` |
| Server streaming | One message | Many messages | Not used by this API |
| Client streaming | Many messages | One message | Not used by this API |
| Bidirectional streaming | Many messages | Many messages | `Subscribe`, `PublishStream`, `ManagedSubscribe` |
Unary calls feel like ordinary function calls. Streaming calls keep one HTTP/2 stream open for as long as both sides want it. For a subscriber this is the point: the server pushes events as they happen, and no polling is needed.
Why Subscribe is bidirectional
You might expect Subscribe to be server streaming: send one request, then receive events forever. The Pub/Sub API makes it bidirectional because the client keeps talking after the first message.
The first FetchRequest names the topic and the replay position. Later FetchRequest messages tell the server how many more events the client is ready to receive, using num_requested. The server will not send more events than the client has asked for. This is application-level flow control layered on top of HTTP/2's own flow control. A later chapter covers it in detail. For now, remember that the client-to-server half of the stream stays open and keeps carrying requests.
The two directions are independent. The server can send a response while the client is still preparing its next request. Neither side waits for the other in lockstep.
How streaming looks in Python
In the Python grpcio library, the stub method for a bidirectional call takes an iterator of request messages and returns an iterator of response messages:
responses = stub.Subscribe(request_iterator, metadata=metadata)
for response in responses:
...The for loop blocks until the next response arrives. At the same time, gRPC pulls requests from your request iterator on a background thread. The library calls next() on your iterator whenever it is ready to send another message. If the iterator has nothing to yield, it blocks that background thread. The stream stays open, and nothing is sent.
This is why the subscriber from the spine uses a generator fed by a queue.Queue:
import queue
import pubsub_api_pb2 as pb2
pending = queue.Queue()
def requests():
while True:
yield pending.get()The main loop calls pending.put(...) whenever it wants to send a new FetchRequest. The generator wakes up and yields it. If the generator ever returns, gRPC half-closes the client side of the stream. That tells the server the client will send nothing more, and a Subscribe stream usually ends at that point. A subscriber that wants to run indefinitely must therefore never let this generator finish.
A minimal streaming skeleton
The following code opens a channel, starts a Subscribe stream, and handles the errors a long-lived stream can raise. It builds on the metadata helper from the authentication chapter.
import queue
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
ENDPOINT = "api.pubsub.salesforce.com:7443"
def run_stream(access_token, instance_url, tenant_id, topic_name):
metadata = (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
pending = queue.Queue()
pending.put(
pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=10,
)
)
def requests():
while True:
yield pending.get()
with grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
try:
for response in stub.Subscribe(requests(), metadata=metadata):
print("received", len(response.events), "events")
if response.events:
pending.put(
pb2.FetchRequest(
topic_name=topic_name,
num_requested=len(response.events),
)
)
except grpc.RpcError as err:
print("stream ended:", err.code(), err.details())The generated PubSubStub comes from pubsub_api.proto, which a later chapter covers. For now, notice three points.
- One channel, many calls. A
grpc.Channelis a long-lived connection object. Create it once and reuse it forGetTopic,GetSchema, andSubscribe. Creating a channel per call wastes TLS handshakes. - Metadata is per call. Authentication headers are not part of the message. You pass them in the
metadataargument of every call, as a tuple of lowercase key and value pairs. - Errors arrive as exceptions. A failed stream raises
grpc.RpcErrorfrom inside theforloop, not at the point where you callstub.Subscribe.
Status codes and deadlines
Every gRPC call ends with a status code, not an HTTP status. The codes you will meet most often when subscribing are:
| Code | Typical meaning for a subscriber |
|---|---|
| `UNAUTHENTICATED` | The access token is missing, expired, or invalid |
| `INVALID_ARGUMENT` | A bad topic name, replay ID, or `num_requested` value |
| `NOT_FOUND` | The topic does not exist |
| `UNAVAILABLE` | A transient network or server problem. Reconnecting is usually appropriate |
| `DEADLINE_EXCEEDED` | A deadline you set on the call passed before it finished |
| `CANCELLED` | One side cancelled the call, for example your own code closing the stream |
Each call can carry a deadline. In Python you set it with the timeout argument, in seconds. Deadlines suit unary calls like GetTopic, where you want a hard cap on waiting. For a Subscribe stream meant to run for hours, do not set a short timeout. The stream would be cut off when the deadline passes, and you would see DEADLINE_EXCEEDED.
topic = stub.GetTopic(pb2.TopicRequest(topic_name=topic_name), metadata=metadata, timeout=10)Long-lived connections and keepalives
A subscription can sit idle for a long time when a topic produces no events. Load balancers and firewalls often drop TCP connections that carry no traffic. gRPC supports HTTP/2 keepalive pings to prevent this. You enable them with channel options:
options = [
("grpc.keepalive_time_ms", 30000),
("grpc.keepalive_timeout_ms", 10000),
]
channel = grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials(), options=options)The option names are part of the gRPC core library. Servers can reject clients that ping too often, so pick conservative intervals. Separately from these transport pings, the Pub/Sub API sends its own empty FetchResponse messages on an idle stream, carrying a latest_replay_id but no events. The resilience chapter explains how to use them. Keep the two mechanisms distinct: transport keepalives keep the connection alive, while the empty responses tell you the subscription is alive.
Common mistakes
- Calling
Subscribewith a single message instead of an iterator. The method expects an iterable ofFetchRequest. Passing one message raises a type error. - Putting tokens in the message body. The headers belong in
metadata. The.protomessages have no field for them. - Creating a new channel for every event batch. Reuse the channel.
- Doing slow work inside the response loop. While your loop is busy, you are not pulling the next response, and you may also delay sending the next
FetchRequest. Keep the loop short, or hand events to a worker. - Treating
grpc.RpcErroras fatal.UNAVAILABLEand similar codes call for a reconnect, not a crash.
Exercise
In the Python subscriber, the main loop is blocked in for response in stub.Subscribe(...). Which thread pulls the next FetchRequest from your request generator, and what happens to the stream if that generator returns?
Show answer
gRPC pulls requests from the generator on a background thread, independent of the loop that reads responses. If the generator returns, the client half-closes its side of the stream, which tells the server the client will send no more requests, and a Subscribe stream usually ends.
Exercise
Why is Subscribe bidirectional rather than server streaming, and which field of FetchRequest makes the client's later messages useful?
Show answer
After the first request, the client keeps sending FetchRequest messages to tell the server how many more events it can accept. The num_requested field carries that count, so the server never sends more events than the client has asked for.
Exercise
You add timeout=30 to your Subscribe call and your subscriber stops after 30 seconds with a gRPC error. Which status code do you see, and what is the fix?
Show answer
You see DEADLINE_EXCEEDED. The timeout applies to the whole call, including a stream that is meant to stay open. Remove the timeout from Subscribe and use it only on unary calls such as GetTopic and GetSchema.