Sub topic 9
Controlling delivery with num_requested
This chapter assumes you can already open a Subscribe stream and decode Avro payloads, as covered in the previous chapters. It also assumes you know that a gRPC bidirectional stream carries messages in both directions at the same time. Here you learn how the client tells the server how many events it is ready to receive, and what goes wrong when it gets that wrong.
Why the client controls the pace
Many messaging systems push events to a subscriber as fast as they arrive. The Pub/Sub API does not. It uses pull-style flow control over a streaming connection. The server sends events only when the client has asked for them.
The request is the num_requested field of FetchRequest. It acts like a credit balance:
- Each
FetchRequestadds itsnum_requestedvalue to the balance of events the server may send. - Each event the server delivers uses one credit.
- When the balance reaches zero, the server stops sending events, even if more are waiting.
- The stream stays open while the balance is zero. The server simply has nothing it is allowed to send.
This protects a slow consumer. If your handler writes each event to a database and that database slows down, you stop requesting more events. Unprocessed events then wait on the server, inside the retention window, instead of piling up in your process memory.
The first request and later requests
The first message you send on a Subscribe stream must say where to start and how many events you want. In the earlier code that meant topic_name, a replay_preset (or replay_id), and num_requested.
Later messages on the same stream only need to add credit. In practice you send num_requested again, and the example code also repeats topic_name, which is harmless.
import pubsub_api_pb2 as pb2
def first_request(topic_name, batch_size):
return pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=batch_size,
)
def more_credit(topic_name, count):
return pb2.FetchRequest(topic_name=topic_name, num_requested=count)The replay preset only matters on the first request. Sending a different one later does not rewind the stream. To change position, close the stream and open a new one.
Credit adds up
The server does not treat each FetchRequest as a replacement for the last one. It adds them together. Suppose you ask for 10 events and then, before any arrive, ask for 10 more. The server may now send up to 20.
The server reports its view of the balance in each FetchResponse through the pending_num_requested field. It is the number of events you have requested that the server has not yet delivered. When it reaches 0, the server will send nothing more until you ask again.
| Field | Where it appears | Meaning |
|---|---|---|
| `num_requested` | `FetchRequest` (client to server) | Credit to add to the balance |
| `events` | `FetchResponse` (server to client) | The batch delivered now, which can be shorter than requested |
| `pending_num_requested` | `FetchResponse` (server to client) | Credit still unspent after this response |
| `latest_replay_id` | `FetchResponse` (server to client) | The newest position the server has reached for this subscription |
A single FetchResponse does not have to contain num_requested events. The server may split a request across several responses, and it may send fewer events per response when the events are large. Do not assume one request produces one response. Count the events you actually receive.
A sequence of requests and responses
The diagram shows a subscriber that asks for 3 events at a time and refills after each batch.
The simple refill pattern
The simplest correct pattern is the one from the earlier subscribe function. After you finish handling a response, you request exactly as many events as you just handled. The balance stays roughly constant.
import queue
import pubsub_api_pb2 as pb2
BATCH_SIZE = 10
def subscribe(stub, metadata, topic_name, decode, replay_id=None):
pending = queue.Queue()
if replay_id is None:
pending.put(pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=BATCH_SIZE,
))
else:
pending.put(pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.CUSTOM,
replay_id=replay_id,
num_requested=BATCH_SIZE,
))
def requests():
while True:
yield pending.get()
last_replay_id = replay_id
for response in stub.Subscribe(requests(), metadata=metadata):
for consumer_event in response.events:
decode(consumer_event.event)
last_replay_id = consumer_event.replay_id
if response.events:
pending.put(pb2.FetchRequest(
topic_name=topic_name,
num_requested=len(response.events),
))
return last_replay_idTwo details matter here:
- The request generator blocks on
pending.get(). gRPC reads from the generator on a background thread, so the main loop can keep reading responses while the generator waits for the next request. - The refill happens after the events are handled, not before. If processing is slow, credit returns slowly, and the server slows down with you. This is the backpressure (a slow consumer limiting the producer) that the design is meant to provide.
Refilling by threshold instead
The simple pattern sends one request per response. If the server splits a request into many small responses, you send many small requests. A threshold pattern is often better. It waits until the server's pending balance drops low, then tops it back up to the target.
import queue
import pubsub_api_pb2 as pb2
TARGET = 50
LOW_WATER = 10
def subscribe_with_threshold(stub, metadata, topic_name, decode):
pending = queue.Queue()
pending.put(pb2.FetchRequest(
topic_name=topic_name,
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=TARGET,
))
def requests():
while True:
yield pending.get()
for response in stub.Subscribe(requests(), metadata=metadata):
for consumer_event in response.events:
decode(consumer_event.event)
if response.pending_num_requested <= LOW_WATER:
pending.put(pb2.FetchRequest(
topic_name=topic_name,
num_requested=TARGET - response.pending_num_requested,
))Here the client reads pending_num_requested to work out how much to add. The request brings the balance back to TARGET without overshooting. This sends fewer, larger requests and keeps the server supplied with work.
Choosing a batch size
There is no universal value. Consider these trade-offs:
- Small batches (1 to 10) limit memory use and the amount of work lost if the process crashes mid-batch. They cost more round trips and can leave the connection idle while the client waits for new credit.
- Large batches keep the pipe full and raise throughput. They hold more unprocessed events in memory and make a crash more costly, because events delivered but not yet recorded must be replayed.
- Event size changes the effective batch. Large events can arrive in smaller groups than you requested.
The API also enforces a maximum on how many events a single request can ask for. Check the current limit in the Salesforce Pub/Sub API documentation rather than relying on a number from a tutorial, because limits change between releases.
Start with a modest batch such as 10 to 50. Measure how long your handler takes per event, then raise the batch size only if the stream often sits idle waiting for credit.
Common errors
- Requesting zero events. If you send
num_requested=0at the start, the stream opens, no events flow, and nothing looks wrong. Always request at least 1 on the first message. - Forgetting to refill. The stream goes silent after your first batch is spent. Logs show no error, because the server is simply waiting for credit.
- Refilling before processing. If you add credit as soon as events arrive, a slow handler no longer slows the server. Events accumulate in memory, and a crash loses everything that was in flight.
- Counting responses instead of events. Adding one refill per response, with a fixed number, drifts out of step when responses vary in size. Use
len(response.events)orpending_num_requested. - Treating an empty response as a failure. The server also sends
FetchResponsemessages with no events as keepalives, and these carry alatest_replay_id. Do not add credit in response to them, since no credit was used.
Relationship to replay IDs
Flow control and replay interact. Events you have received but not finished processing are not safe to record as done. Store the replay_id of the last event you fully handled, not the last one you received. If the process dies, you resume from the stored value and the server resends the events you had not finished. The next chapter covers this in detail.
Exercise
A subscriber sends one FetchRequest with numrequested=20 and nothing else. It receives 20 events across several responses, and the final response shows pendingnum_requested=0. The topic then publishes 5 new events. The subscriber's code never prints them, and no error appears. What is happening, and how do you fix it?
Show answer
The credit balance is zero, so the server is not allowed to send more events. The stream is still open, which is why there is no error. The fix is to send another FetchRequest with numrequested greater than 0 after the first 20 events are handled, either with len(response.events) as in the simple refill pattern or with a threshold based on pendingnum_requested.
Exercise
You use a threshold pattern with TARGET=50 and LOWWATER=10. A response arrives with pendingnumrequested=8. What numrequested should the next FetchRequest carry, and why not simply 50?
Show answer
42, which is TARGET minus pendingnumrequested. Credit accumulates on the server, so sending 50 would raise the balance to 58, above your intended target, and let more unprocessed events build up in memory.