Sub topic 13
Event retention and delivery limits
This chapter assumes you can already open a Subscribe stream, decode Avro payloads, and store replay IDs, as covered in the earlier chapters. It explains the limits that decide whether a stored replay ID is still usable and how much a subscriber can receive. Each of these limits shapes subscriber design.
Why limits matter to a subscriber
A subscriber that runs forever on a quiet topic can look correct and still fail the first time it is down for a long weekend. Three kinds of limit cause most surprises:
- Retention: how long the event bus keeps an event after publication.
- Delivery: how many events the org will push to Pub/Sub API clients in a period.
- Concurrency and size: how many clients can connect, and how large events and fetch requests can be.
Salesforce changes the exact numbers by edition, license, and release. The values below are the ones documented at the time of writing. Check the current Pub/Sub API and platform event limits pages before you size a production system.
Retention: the 72-hour window
The event bus stores high-volume platform events and Change Data Capture (CDC) events for 72 hours (3 days). A replay ID is only useful while the event it points to is still inside that window. After that, the event is gone and the replay ID is stale.
There are two consequences:
- If a subscriber is down for less than the window, it can resume from its last stored replay ID and receive every event it missed, in order.
- If a subscriber is down for longer than the window, the events from the gap are lost to it. Reconnecting with the old replay ID can fail with an error, or the server may not be able to give you a complete history.
Retention is measured from when the event was published, not from when you last connected. A checkpoint that was fresh when you saved it ages every hour that the subscriber is offline.
The first diagram shows the startup decision that follows from this.
What the replay presets mean for retention
| Preset | Starts at | Retention behavior |
|---|---|---|
| `LATEST` | The tip of the stream, so only new events | Not affected by retention. You get nothing from the past. |
| `EARLIEST` | The oldest event still retained | Returns up to 72 hours of history, which can be a lot of events. |
| `CUSTOM` | The event after the replay ID you send | Valid only while that event is still retained. |
EARLIEST is useful for a first run on a topic where you want everything the bus still has. It also counts every event it delivers against your delivery allocation, so use it deliberately.
Handling a stale or rejected replay ID
A replay ID can fail in two ways. It can be too old, which means it fell out of the window. It can also be malformed, for example if you truncated the bytes or saved it as text and changed it. The server answers with a gRPC error on the stream, and the stream ends.
Handle this explicitly. Silently falling back to LATEST hides data loss, so log the gap and run a recovery step. For CDC, the recovery is usually a query against the source objects, such as records with LastModifiedDate after your last checkpoint time. For platform events, the publisher or a system of record has to supply the missing data, because the bus no longer has it.
The code below stores a checkpoint with a timestamp, then decides how to start. It assumes the subscribe function from the earlier chapter. Pass the result of choose_start as its replay_id, where None means LATEST.
import sqlite3
import time
import grpc
RETENTION_SECONDS = 72 * 3600
SAFETY_MARGIN_SECONDS = 6 * 3600
class CheckpointStore:
def __init__(self, path="checkpoints.db"):
self.db = sqlite3.connect(path)
self.db.execute(
"CREATE TABLE IF NOT EXISTS checkpoint ("
"topic TEXT PRIMARY KEY, "
"replay_id TEXT NOT NULL, "
"saved_at REAL NOT NULL)"
)
def save(self, topic, replay_id):
# Replay IDs are opaque bytes. Store them as hex so they round-trip exactly.
with self.db:
self.db.execute(
"INSERT OR REPLACE INTO checkpoint VALUES (?, ?, ?)",
(topic, replay_id.hex(), time.time()),
)
def load(self, topic):
row = self.db.execute(
"SELECT replay_id, saved_at FROM checkpoint WHERE topic = ?",
(topic,),
).fetchone()
if row is None:
return None, None
return bytes.fromhex(row[0]), row[1]
def choose_start(store, topic):
"""Return (replay_id, needs_backfill). A replay_id of None means LATEST."""
replay_id, saved_at = store.load(topic)
if replay_id is None:
return None, False
age = time.time() - saved_at
if age > RETENTION_SECONDS - SAFETY_MARGIN_SECONDS:
print(f"Checkpoint is {age / 3600:.1f}h old. Events may have expired.")
return None, True
return replay_id, False
def is_replay_rejection(error):
return isinstance(error, grpc.RpcError) and error.code() in (
grpc.StatusCode.INVALID_ARGUMENT,
grpc.StatusCode.FAILED_PRECONDITION,
)Two details in this code matter. The check uses the time you saved the checkpoint, which approximates the age of the last event you processed. It is only an estimate, which is why the code subtracts a safety margin. The is_replay_rejection helper is deliberately broad. Read error.details() in your logs and narrow the check once you know which status codes your org returns.
Delivery limits
Subscribing is not free. Salesforce tracks how many events it delivers to clients in a rolling 24-hour period and limits that number by edition and add-on licenses.
- Each event delivered to each subscriber counts. Two subscribers on the same topic count twice.
- Events re-delivered after a reconnect count again.
- Events that arrive during an
EARLIESTreplay count like any other event.
For CDC, one record change produces one event, but a bulk operation such as a data load of 200,000 records produces a large burst. A burst that exhausts the allocation can leave your subscriber with errors until the period rolls over, while the events themselves remain in the 72-hour window.
You can reduce delivery volume in these ways:
- Subscribe to a specific entity channel, such as
/data/AccountChangeEvent, instead of the all-entities channel/data/ChangeEvents. - Use CDC enrichment and channel filtering options on the Salesforce side, so fields and records you do not need are never delivered.
- Run one subscriber that fans out internally, instead of several subscribers on the same topic.
- Avoid unnecessary
EARLIESTreplays.
Concurrency, size, and request limits
These limits apply to the connection rather than to the whole org.
| Limit | What it means for you |
|---|---|
| Concurrent clients | The org caps how many clients can be subscribed at once, shared with other streaming APIs. Extra clients are refused. |
| One topic per `Subscribe` stream | Open one stream per topic. Multiplexing topics on a single stream is not supported. |
| Maximum `num_requested` per `FetchRequest` | The server caps how many events one request can ask for. The documented cap is 100. A larger value gets you the capped amount. |
| Event size | Published events have a size limit, and very large CDC changes can arrive with truncated or omitted fields, flagged in the change header. |
| Stream idle time | When no events are available, the server sends keepalive responses with an empty `events` list, so do not treat those as errors. |
The concurrency limit is the one that bites during deployments. If your rolling restart starts a new subscriber before the old one has disconnected, both count against the limit for a short time. Stop the old stream first, or leave headroom.
Designing around the limits
Several design choices follow from the limits above:
- Checkpoint often, and only after processing. A checkpoint after every batch bounds how many events you re-process after a crash. Saving before processing risks losing events instead.
- Make handlers idempotent. Reconnects re-deliver events, so processing the same replay ID twice must be safe.
- Alert on checkpoint age. A subscriber that has been offline for 48 hours is already two thirds of the way to data loss. Monitoring checkpoint age gives you time to act before the window closes.
- Keep a recovery path. For CDC, that means a query-based backfill. For platform events, it means a documented answer to "what do we do if events are gone".
- Budget deliveries. Estimate peak events per day, multiply by the number of subscribers, and compare with your allocation. Include bulk jobs in the estimate.
Exercise
A subscriber for /data/AccountChangeEvent stores a replay ID after each batch. It crashes on Friday evening and is not restarted until Tuesday morning, about 90 hours later. What happens if it reconnects with CUSTOM and the stored replay ID, and what should the startup logic do instead?
Show answer
The stored replay ID points to an event older than the 72-hour retention window, so the server may reject it, or events from the gap will be missing. Retrying with the same replay ID will not help. The startup logic should compare the checkpoint age with the retention window, detect that it is too old, log the gap, backfill the missed changes from the source (for example by querying Accounts with LastModifiedDate after the checkpoint time), and then subscribe from LATEST.
Exercise
Two services subscribe to the same CDC channel, and a nightly job changes 150,000 records. Why might the org's delivery allocation be a concern, and name two ways to reduce the load?
Show answer
Each event delivered to each subscriber counts against the 24-hour delivery allocation, so the job produces roughly 300,000 deliveries, and any reconnect or replay adds more. To reduce it, subscribe to a specific entity channel instead of /data/ChangeEvents, use channel filtering or enrichment settings so unneeded events are not sent, or run a single subscriber that forwards events to the second service.