Sub topic 11
Keepalives, errors, and reconnecting safely
A Subscribe stream is a long-lived connection, so it will eventually end. The cause may be a network drop, a server restart, or an expired access token. This chapter covers how to tell a quiet stream from a dead one, how to read errors, and how to reconnect without losing or reprocessing events.
This chapter assumes you have read the earlier chapters on authentication, Avro decoding, num_requested flow control, and replay IDs. You should be comfortable with Python generators and try/except.
Keepalives: a quiet stream is not a dead stream
If a topic has no new events, the server still sends a FetchResponse about every 270 seconds. That message has an empty events list but carries latest_replay_id. It is the Pub/Sub API's application-level keepalive. It tells you the stream is alive and gives you a replay ID that is safe to store.
Two kinds of keepalive exist, and they do different jobs.
| Kind | Layer | What it does |
|---|---|---|
| Pub/Sub keepalive | Application (`FetchResponse` with no events) | Confirms the subscription is healthy and updates `latest_replay_id` |
| HTTP/2 keepalive ping | gRPC transport | Detects a half-open TCP connection that no longer carries data |
The application keepalive cannot help if the connection died silently. A firewall may drop idle flows without sending a reset, and your client then waits for a message that will never arrive. Setting gRPC channel options makes the client send pings and fail fast when the peer does not answer.
CHANNEL_OPTIONS = [
("grpc.keepalive_time_ms", 120000),
("grpc.keepalive_timeout_ms", 20000),
("grpc.keepalive_permit_without_calls", 1),
]With these options, the client pings after 120 seconds of silence and treats the connection as broken if no reply arrives within 20 seconds. The failure then surfaces as an UNAVAILABLE error on the stream.
Using keepalives to advance your stored position
A keepalive's latest_replay_id matters on a topic that rarely receives events. Suppose you stored replay ID A three days ago, and since then the topic has had no events for you. If you reconnect from A, the server must find A in its retention window. Storing the newer ID from each keepalive keeps your position fresh and lowers the chance of falling out of retention.
Only store latest_replay_id from a response whose events list is empty. When a response contains events, store the replay ID of the last event you actually processed. If you stored latest_replay_id there, you could skip events that were still waiting in your local processing.
Reading errors from a failed stream
When a stream fails, the for response in stub.Subscribe(...) loop raises grpc.RpcError. Two parts of the error matter.
error.code()returns agrpc.StatusCode, such asUNAVAILABLEorUNAUTHENTICATED.error.trailing_metadata()may carry Salesforce-specific details, including anerror-codeentry that names the exact failure. Log it every time. It is the fastest way to diagnose a problem later.
Use the status code to choose a recovery action.
| Status code | Typical cause | Action |
|---|---|---|
| `UNAVAILABLE` | Network drop, server restart, failed keepalive ping | Reconnect with backoff |
| `INTERNAL`, `UNKNOWN`, `ABORTED` | Transient server-side problem | Reconnect with backoff |
| `DEADLINE_EXCEEDED` | A timeout you set expired | Reconnect with backoff |
| `UNAUTHENTICATED` | Access token expired or revoked | Get a new token, then reconnect |
| `INVALID_ARGUMENT` | Bad topic name or an invalid or expired replay ID | Do not retry blindly; see below |
| `PERMISSION_DENIED`, `NOT_FOUND` | User lacks access, or the topic does not exist | Stop and fix the configuration |
A stream can also end without an error. The server may close it cleanly, and your for loop then exits normally. Treat that the same as UNAVAILABLE. A subscriber that quietly stops when the loop ends is a common bug.
Replay IDs that the server rejects
If you reconnect with a stored replay ID that has aged out of retention, the server rejects it. Retrying the same ID will fail forever. You have to choose a policy, and both options have a cost.
- Fall back to
LATEST. You skip everything missed during the outage, but the subscriber recovers on its own. - Stop and alert a person. This avoids silent data loss, but it needs someone to act.
For data you can rebuild by other means, such as a nightly sync, LATEST is often acceptable. For anything that must not be missed, stop, alert, and recover from the source system.
Reconnecting without loss or duplicates
The rules for a safe reconnect are short.
- Persist the replay ID only after you finish handling the event.
- On reconnect, start with
CUSTOMand the stored replay ID. - Build a new request queue for every new stream. The old generator is tied to the dead stream.
- Accept that you may see an event twice, and make the handler safe to repeat.
Rule 1 gives you at-least-once delivery. If your process crashes after handling an event but before saving its replay ID, the event comes again on restart. That is the right trade. The alternative, saving first, loses the event if the handler then fails. Every event carries an ID in its payload header, so a handler can record seen IDs, or make its writes idempotent, to absorb duplicates.
A complete reconnect loop
The code below combines the pieces. It takes a login function that returns a fresh access token, instance URL, and tenant ID, a store object that saves and loads the replay ID, a decode function from the Avro chapter, and a handle_event function.
import queue
import random
import time
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
ENDPOINT = "api.pubsub.salesforce.com:7443"
BATCH_SIZE = 10
INITIAL_DELAY = 1.0
MAX_DELAY = 60.0
CHANNEL_OPTIONS = [
("grpc.keepalive_time_ms", 120000),
("grpc.keepalive_timeout_ms", 20000),
("grpc.keepalive_permit_without_calls", 1),
]
RETRYABLE = {
grpc.StatusCode.UNAVAILABLE,
grpc.StatusCode.INTERNAL,
grpc.StatusCode.UNKNOWN,
grpc.StatusCode.ABORTED,
grpc.StatusCode.DEADLINE_EXCEEDED,
}
def auth_metadata(access_token, instance_url, tenant_id):
return (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
def first_request(topic_name, replay_id):
if replay_id is None:
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=BATCH_SIZE,
)
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.CUSTOM,
replay_id=replay_id,
num_requested=BATCH_SIZE,
)
def run_once(topic_name, login, store, decode, handle_event):
token, instance_url, tenant_id = login()
metadata = auth_metadata(token, instance_url, tenant_id)
pending = queue.Queue()
pending.put(first_request(topic_name, store.load()))
def requests():
while True:
yield pending.get()
with grpc.secure_channel(
ENDPOINT, grpc.ssl_channel_credentials(), options=CHANNEL_OPTIONS
) as channel:
stub = pb2_grpc.PubSubStub(channel)
for response in stub.Subscribe(requests(), metadata=metadata):
yield # signals "stream is healthy" to the caller
for consumer_event in response.events:
record = decode(stub, metadata, consumer_event.event)
handle_event(record)
store.save(consumer_event.replay_id)
if response.events:
pending.put(
pb2.FetchRequest(
topic_name=topic_name,
num_requested=len(response.events),
)
)
else:
store.save(response.latest_replay_id)
def run_forever(topic_name, login, store, decode, handle_event):
delay = INITIAL_DELAY
while True:
try:
for _ in run_once(topic_name, login, store, decode, handle_event):
delay = INITIAL_DELAY # a response arrived, so reset backoff
print("stream closed by server; reconnecting")
except grpc.RpcError as error:
code = error.code()
details = dict(error.trailing_metadata() or ())
print("stream error:", code, details.get("error-code"))
if code == grpc.StatusCode.INVALID_ARGUMENT:
raise # bad topic or replay ID: needs a human decision
if code not in RETRYABLE and code != grpc.StatusCode.UNAUTHENTICATED:
raise
# UNAUTHENTICATED is handled by calling login() again on the next pass.
time.sleep(delay + random.uniform(0, delay / 2))
delay = min(delay * 2, MAX_DELAY)Several details in this loop matter.
run_onceis a generator that yields once per response, sorun_forevercan reset the backoff only after the server has proved it is talking to us. Resetting at connection time would let a flapping server keep the delay at one second.login()runs on every attempt, so an expired token is replaced automatically.- The delay doubles up to 60 seconds, and random jitter spreads out reconnects when many subscribers lose the server at the same moment.
- The keepalive branch saves
response.latest_replay_id. An event branch saves each event's own replay ID after its handler returns. - Errors that need a human, such as
INVALID_ARGUMENTandPERMISSION_DENIED, are re-raised instead of retried.
The subscriber lifecycle
Common mistakes
- Reusing the request generator or queue across reconnects. The new stream then reads stale
FetchRequestmessages. - Saving the replay ID before the handler succeeds, which turns at-least-once into at-most-once.
- Resetting the backoff delay when the connection opens instead of when data arrives.
- Ignoring a clean end of the stream.
- Swallowing
error-codefrom trailing metadata, which leaves you with only a generic status code to debug.
Exercise
Your subscriber stored replay ID R after handling event 41. It crashed while handling event 42, before saving anything. After restart it reconnects with CUSTOM and R. What does it receive first, and what does this say about the handler's design?
Show answer
It receives event 42 again, because R marks the last event that finished processing. The handler must therefore be safe to run twice for the same event, for example by writing idempotently or by recording event IDs it has already seen. This is at-least-once delivery.
Exercise
A topic receives no events for ten minutes. You see two responses with empty events lists in that time. Is the stream broken, and what should you do with each response's latest_replay_id?
Show answer
The stream is healthy. Those responses are the roughly 270-second Pub/Sub keepalives. Save each latest_replay_id as your stored position, because no events are waiting in your processing. This keeps the stored ID recent and less likely to age out of retention.