Sub topic 11
Keepalives, errors, and reconnecting safely
This chapter assumes you can already open a Subscribe stream, decode Avro events, and store replay IDs, as covered in the earlier chapters. Here you will make that subscriber survive idle periods, errors, and dropped connections.
Keepalive messages
A Subscribe stream is long-lived. When no events arrive, the server still sends a FetchResponse now and then. It has an empty events list and a latest_replay_id. This message is a keepalive. It tells you the connection is healthy and gives you a position to save.
Handle keepalives like this:
- Do not send a new
FetchRequestfor them. No events were delivered, so yournum_requestedwindow did not shrink. - Do store
latest_replay_id. After a quiet period it lets you resume from a recent position instead of an old one. - Do not treat silence as a failure on its own. Set a generous client-side idle timeout, longer than the server's keepalive interval, before you decide a stream is dead.
Why streams end
A stream can end for several reasons:
- The network drops or a load balancer closes an idle connection.
- The access token expires or the session is invalidated.
- The server rejects your request, for example because the replay ID is no longer valid.
- The server restarts or is briefly unavailable.
In Python, an ended stream raises grpc.RpcError inside your for loop. Call error.code() to get the grpc.StatusCode. Treat the codes in two groups.
| Status code | Meaning | Action |
|---|---|---|
| `UNAVAILABLE`, `DEADLINE_EXCEEDED`, `INTERNAL` | Transient network or server problem | Reconnect with backoff |
| `UNAUTHENTICATED` | Token expired or revoked | Get a new token, then reconnect |
| `INVALID_ARGUMENT`, `NOT_FOUND`, `PERMISSION_DENIED` | The request itself is wrong | Stop and fix the cause. Retrying will fail again. |
Reconnecting from the last processed event
Reconnect from the replay ID of the last event you fully processed, not from LATEST. Starting at LATEST silently skips every event published while you were disconnected.
Save the replay ID after you process an event, not before. If your process crashes between processing and saving, you will receive that event again. This is at-least-once delivery, so make your handler idempotent, for example by keying writes on the event's replay ID or record ID.
The loop below follows that diagram. It reuses subscribe-style logic from the previous chapters. Here open_and_read is any function that opens the stream from a replay ID, handles events, and returns the newest replay ID it saw.
import random
import time
import grpc
TRANSIENT = {
grpc.StatusCode.UNAVAILABLE,
grpc.StatusCode.DEADLINE_EXCEEDED,
grpc.StatusCode.INTERNAL,
}
def run_forever(open_and_read, load_replay_id, save_replay_id, refresh_auth):
delay = 1
while True:
try:
replay_id = load_replay_id()
for new_id in open_and_read(replay_id):
save_replay_id(new_id)
delay = 1 # healthy traffic resets the backoff
except grpc.RpcError as err:
code = err.code()
if code == grpc.StatusCode.UNAUTHENTICATED:
refresh_auth()
elif code in TRANSIENT:
time.sleep(delay + random.random())
delay = min(delay * 2, 60)
else:
raiseHere open_and_read is a generator that yields each replay ID as events are processed. The delay doubles after each failure up to 60 seconds. The random jitter stops many subscribers from reconnecting at the same instant.
Exercise
Your subscriber was idle for ten minutes and then the stream failed with UNAVAILABLE. Which replay ID should you reconnect from, and which preset should you use?
Show answer
Reconnect with the CUSTOM replay preset and the last saved replay ID. That is the last processed event's ID, or the latestreplayid from the most recent keepalive. Do not use LATEST, because it would skip events published during the outage. Wait with exponential backoff before reconnecting.