---
schema_version: "1"
id: b837938b85dabdde997f7919b4c0fc581242c9f50eeadee377311bb27b4fb694
title: Subscribe RPC Method
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/event-bus/pub-sub-api/references/subscribe-rpc.md
canonical_url: https://developer.salesforce.com/docs/platform/pub-sub-api/references/methods/subscribe-rpc.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 0dd7bbe14d671b48fab5134abe31bd8b77c8a3bd12cffcf06604f7fe260cdee7
products:
  - Pub/Sub API
  - Event Bus Docs
---
# Subscribe RPC Method

The `Subscribe` method uses bidirectional streaming. It’s pull-based, which means that it requests new events. This subscription model is in contrast to push-based subscription, in which the subscriber is a listener that waits for events to be sent. The Subscribe method offers flow control, which enables you to specify how many events to receive in a call based on the client’s event processing speed.

`rpc Subscribe (stream FetchRequest) returns (stream FetchResponse);`

A client can request the number of events it can process by setting the `num_requested` field in FetchRequest. The maximum value for `num_requested` is 100. The server returns the events in one or more FetchResponses. Each FetchResponse contains the number of events that are pending delivery in the `pending_num_requested` field. If a client requests more events before the server finishes the last requested amount, the server appends the new amount to the current batch of events it still needs to fetch and deliver. For more information about the pull subscription behavior, see [Pull Subscription and Flow Control](https://developer.salesforce.com/docs/platform/pub-sub-api/guide/flow-control.html). For more information about the fields in FetchRequest and FetchResponse, see the [Pub/Sub API proto file](https://github.com/forcedotcom/pub-sub-api/blob/main/pubsub_api.proto).

## Subscribe Keepalive Behavior

The Subscribe call stream stays open as long as there are pending events to be sent to the client. The number of pending events is based on the number of events the client requested in FetchRequests and the number of events delivered in FetchResponses.

This table summarizes how to keep a managed subscription stream open for each condition.

| Condition                                                                                                                                                                       | To keep a subscription stream alive                                                                                                                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Pending events to be sent to the client and there are still events in the event bus to be delivered (`pending_num_requested` in ManagedFetchResponse is greater than zero)      | The stream stays open.                                                                                                                                                                                                                   |
| No more pending events to be sent to the client (`pending_num_requested` in ManagedFetchResponse is equal to zero)                                                              | The client must send a new FetchRequest within 60 seconds from when the last FetchResponse was sent.                                                                                                                                     |
| Pending events to be sent to the client but no new events are available in the event bus to be delivered (`pending_num_requested` in ManagedFetchResponse is greater than zero) | The server keeps the stream open by sending keepalive messages within 270 seconds. A keepalive message indicates that the Pub/Sub API service is healthy and provides a new Replay ID that points to an advanced position in the stream. |

## Keepalive Messages Sent from the Server

If there are pending events to be sent to the client (`pending_num_requested` in FetchResponse is greater than zero) but no new events are available in the event bus, the server keeps the stream alive by sending keepalive messages within 270 seconds. The keepalive message is an empty batch FetchResponse with the latest `replay_id`. The returned `replay_id` can be the last event consumed in your client or an advanced position in the stream beyond the last consumed event. An advanced position in the stream is possible even if you didn’t receive events because the event bus combines streams from multiple orgs. No org-specific information or personally identifiable information is shared with other orgs.

For best performance results, we recommend that you save the `replay_id` from each empty FetchResponse and use it when resubscribing. That way, when you restart the subscription, you receive the next unprocessed events and not duplicate events. Saving the `replay_id` from each empty FetchResponse ensures that the `replay_id` is recent. An old `replay_id` refers to an earlier position in the stream than the `replay_id` that the keepalive message returns. Using the more recent `replay_id` ensures that the server doesn’t take too much time to seek the event in the event bus when the subscription restarts.

## Handling Errors

If an error occurs, the long-lived connection is stopped. Retry the `Subscribe` RPC method call to create a new long-lived connection. For more information, see [Handle Errors](/docs/platform/pub-sub-api/guide/handling-errors.html).

## Replaying an Event Stream

Platform events and change data capture events are retained in the event bus for 3 days. A client can subscribe at any position in the stream by providing a replay option in the first FetchRequest. Any subsequent FetchRequests with a new replay option are ignored. A client must call the `Subscribe` RPC again to restart the subscription at a new position in the stream. The replay option consists of a combination of `replay_preset` and `replay_id` values in the first FetchRequest received from a client.

This table describes the replay options and when to use each.

| `replay_preset` | Behavior                                                                                                                                                                                                                                                                                                       | When to Use                                                                                                                                                                                                                                                                                    |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LATEST`        | Default if no replay preset is specified. Subscribe from the tip of the stream.                                                                                                                                                                                                                                | Use when you’re interested only in new event messages and don’t need the earlier event messages stored in the event bus.                                                                                                                                                                       |
| `CUSTOM`        | Resubscribe after a specific `replay_id`. To use this option, also set the `replay_id` to the replay ID of the last keepalive message or the last processed event message, whichever was received last. Store replay ID values as bytes because replay IDs are opaque and not guaranteed to always be numbers. | Use to catch up on missed events after a certain event message, for example, after a connection failure.                                                                                                                                                                                       |
| `EARLIEST`      | Subscribe from the earliest retained events.                                                                                                                                                                                                                                                                   | Use to catch up on missed events and retrieve all stored events. Use this option after a client has been disconnected for more than 3 days and the last saved replay ID is no longer valid. Use `EARLIEST` sparingly because it can slow performance when retrieving a large number of events. |

**tip:** Instead of using the `replay_preset` options to retrieve missed events from Salesforce, you can use the [ManagedSubscribe RPC Method (Beta)](https://developer.salesforce.com/docs/platform/pub-sub-api/references/methods/managedsubscribe-rpc.md). With the `ManagedSubscribe` method, you can track the Replay ID of the last processed event by committing the Replay ID on the server. You don’t worry about managing a replay ID store on the client. Then when resubscribing, the subscription resumes after the stored Replay ID.

The first FetchRequest of the stream identifies the topic to subscribe to. If a subsequent FetchRequest provides `topic_name`, it must match what was provided in the first FetchRequest. Otherwise, the RPC sends an error with an `INVALID_ARGUMENT` status.

**See Also**

- [Java Quick Start for Publishing and Subscribing to Events](/docs/platform/pub-sub-api/guide/qs-java-quick-start.html)
- [Allocations](/docs/platform/pub-sub-api/guide/allocations.html)
- [Pull Subscription and Flow Control](/docs/platform/pub-sub-api/guide/flow-control.html)
- [ManagedSubscribe RPC Method](https://developer.salesforce.com/docs/platform/pub-sub-api/references/methods/managedsubscribe-rpc.md)
