---
title: "Consume Subscriptions API"
description: "API reference for consuming RavenDB data subscriptions, covering SubscriptionWorker options, batch handling, and error strategies."
url: "https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/api-overview"
version: "7.2"
language: "python"
---

# Consume Subscriptions API

> Client language: Python. Also available for [C#](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/api-overview.md), [Java](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/api-overview.java.md), [Node.js](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/api-overview.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - In this page:
>   - [Create the subscription worker](#create-the-subscription-worker)
>   - [`SubscriptionWorkerOptions`](#subscriptionworkeroptions)
>   - [Run the subscription worker](#run-the-subscription-worker)
>   - [`SubscriptionBatch[_T]`](#subscriptionbatch_t)
>   - [`SubscriptionWorker[_T]`](#subscriptionworker_t)

## Create the subscription worker

Create a subscription worker using `get_subscription_worker` or `get_subscription_worker_by_name`.

- Use the `get_subscription_worker` method to specify the subscription options while creating the worker.
- Use the `get_subscription_worker_by_name` method to create the worker using the default options.

```python
def get_subscription_worker(
  self, options: SubscriptionWorkerOptions, object_type: Optional[Type[_T]] = None, database: Optional[str] = None
) -> SubscriptionWorker[_T]: ...

def get_subscription_worker_by_name(
  self,
  subscription_name: Optional[str] = None,
  object_type: Optional[Type[_T]] = None,
  database: Optional[str] = None,
) -> SubscriptionWorker[_T]: ...
```

| Parameter | | |
| - | - | - |
| **options** | `SubscriptionWorkerOptions` | Options that affect how the worker interacts with the subscription. These options do not alter the definition of the subscription itself. |
| **object\_type** (Optional) | `Type[_T]` | Defines the object type (class) for the items that will be included in the received `SubscriptionBatch` object. |
| **database** (Optional) | `str` | The name of the database where the subscription task resides. If `None`, the default database configured in DocumentStore will be used. |
| **subscription\_name** (Optional) | `str` | The subscription's name. Used when the worker is generated without creating a `SubscriptionCreationOptions` instance, relying on the default values. |

| Return value | |
| - | - |
| `SubscriptionWorker` | The subscription worker that has been created.<br />Initially, it is idle and will only start processing documents when the `run` function is called. |

## `SubscriptionWorkerOptions`

When creating a worker with `SubscriptionWorkerOptions`, the only mandatory property is `subscription_name`.  
All other parameters are optional and will default to their respective default values if not specified.

| Member | Type | Description |
| - | - | - |
| **subscription\_name** | `str` | The name of the subscription to which the worker will connect. |
| **time\_to\_wait\_before\_connection\_retry** | `timedelta` | The time to wait before attempting to reconnect after a non-aborting failure during subscription processing. Default: 5 seconds. |
| **ignore\_subscriber\_errors** | `bool` | Determines if subscription processing is aborted when the worker's batch-handling code throws an unhandled exception.<br /><br />`True` – subscription processing will continue.<br /><br />`False` (Default) – subscription processing will be aborted. |
| **max\_docs\_per\_batch** | `int` | The maximum number of documents that the server will try to retrieve and send to the client in a batch. If the server doesn't find as many documents as specified, it will send the documents it has found without waiting. Default: 4096. |
| **close\_when\_no\_docs\_left** | `bool` | Determines whether the subscription connection closes when no new documents are available.<br /><br />`True` – The subscription worker processes all available documents and stops when none remain, at which point the `run` method throws a `SubscriptionClosedException`.<br />Useful for ad-hoc, one-time processing.<br /><br />`False` (Default) – The subscription worker remains active, waiting for new documents. |
| **send\_buffer\_size\_in\_bytes** | `int` | The size in bytes of the TCP socket buffer used for *sending* data.<br />Default: 32,768 bytes (32 KiB). |
| **receive\_buffer\_size\_in\_bytes** | `int` | The size in bytes of the TCP socket buffer used for *receiving* data.<br />Default: 4096 (4 KiB). |
| **strategy** | `SubscriptionOpeningStrategy`<br />(enum) | Configures how the server handles connection attempts from workers to a specific subscription task.<br />Learn more in [worker strategies](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/how-to-consume-data-subscription.python.md#worker-strategies).<br />Default: `OPEN_IF_FREE`. |

> **Note**
>
> Learn more about `SubscriptionOpeningStrategy` in [worker strategies](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/how-to-consume-data-subscription.python.md#worker-strategies).
>
> | `SubscriptionOpeningStrategy` | |
> | - | - |
> | `OPEN_IF_FREE` | Connect if no other worker is connected |
> | `WAIT_FOR_FREE` | Wait for currently connected worker to disconnect |
> | `TAKE_OVER` | Take over the connection |
> | `CONCURRENT` | Connect concurrently |

## Run the subscription worker

After [creating](#create-the-subscription-worker) a subscription worker, the subscription worker is still not processing any documents.  
To start processing, you need to call the `run` function of the [SubscriptionWorker](#subscriptionworker\[_t]).

The `run` function receives the client-side code as a function that will process the received document batches.

```python
def run(self, process_documents: Optional[Callable[[SubscriptionBatch[_T]], Any]]) -> Future: ...
```

| Parameter | | |
| - | - | - |
| **process\_documents** (Optional) | `[Callable[[SubscriptionBatch[_T]], Any]]` | Delegate to sync batch processing |

## `SubscriptionBatch[_T]`

| Member | Type | Description |
| - | - | - |
| **items** | `SubscriptionBatch[_T].Item` array | List of items in the batch |
| **number\_of\_items\_in\_batch** | `int` | Number of items in the batch |

```python
def number_of_items_in_batch(self) -> int:
  return 0 if self.items is None else len(self.items)
```

> **Note:** Subscription worker connectivity {#subscription-worker-connectivity}
>
> As long as there is no exception, the worker will continue addressing the same
> server that the first batch was received from.  
> If the worker fails to reach that node, it will try to
> [failover](https://docs.ravendb.net/7.2/client-api/configuration/load-balance/overview.md) to another node
> from the session's topology list.  
> The node that the worker succeeds connecting to, will inform the worker which
> node is currently responsible for data subscriptions.

```python
class Item(Generic[_T_Item]):
  """
  Represents a single item in a subscription batch results.
  This class should be used only inside the subscription's run delegate,
  using it outside this scope might cause unexpected behavior.
  """
```

```python
class SubscriptionBatch(Generic[_T]):

def __init__(self):
  self._result: Optional[_T_Item] = None
  self._exception_message: Optional[str] = None
  self._key: Optional[str] = None
  self._change_vector: Optional[str] = None
  self._projection: Optional[bool] = None
  self._revision: Optional[bool] = None
  self.raw_result: Optional[Dict] = None
  self.raw_metadata: Optional[Dict] = None
  self._metadata: Optional[MetadataAsDictionary] = None
```

| `SubscriptionBatch[_T].item` Member | Type | Description |
| - | - | - |
| **\_result** (Optional) | `_T_Item` | Current batch item |
| **\_exception\_message** (Optional) | `str` | Message of the exception thrown during current document processing in the server side |
| **\_key** (Optional) | `str` | Current batch item underlying document ID |
| **\_change\_vector** (Optional) | `str` | Current batch item underlying document change vector of the current document |
| **\_projection** (Optional) | `bool` | indicates whether the value id a projection |
| **raw\_result** (Optional) | `Dict` | Current batch item before serialization to `T` |
| **raw\_metadata** (Optional) | `Dict` | Current batch item underlying document metadata |
| **\_metadata** (Optional) | `MetadataAsDictionary` | Current batch item underlying metadata values |

> **Warning**
>
> Usage of `raw_result`, `raw_metadata`, and `_metadata` values outside of the document processing delegate
> is not supported.

## `SubscriptionWorker[_T]`

### Methods:

| Method | Return Type | Description |
| - | - | - |
| `close(bool wait_for_subscription_task = True)` | `void` | Aborts subscription worker operation ungracefully by waiting for the task returned by the `run` function to finish running. |
| `run` | `Future[None]` | Call `run` to begin the worker's batch processing.<br />Pass the batch processing delegates to this method<br />(see [above](#run-the-subscription-worker)). |

### Events:

| Event | Type\Return type | Description |
| - | - | - |
| **after\_acknowledgment** | `Callable[[SubscriptionBatch[_T]], None]` | Event invoked after each time the server acknowledges batch processing progress. |

| `after_acknowledgment` Parameters | | |
| - | - | - |
| **batch** | `SubscriptionBatch[_T]` | The batch process which was acknowledged |

| Return value | |
| - | - |
| `Future[None]` | The worker waits for the task to finish the event processing |

### Properties:

| Member | Type | Description |
| - | - | - |
| **current\_node\_tag** | `str` | The node tag of the current RavenDB server handling the subscription. |
| **subscription\_name** | `str` | The name of the currently processed subscription. |

## See also

- [What are Data Subscriptions](https://docs.ravendb.net/7.2/client-api/data-subscriptions/what-are-data-subscriptions.md)
- [How to Create a Data Subscription](https://docs.ravendb.net/7.2/client-api/data-subscriptions/creation/how-to-create-data-subscription.python.md)
- [How to Consume a Data Subscription](https://docs.ravendb.net/7.2/client-api/data-subscriptions/consumption/how-to-consume-data-subscription.python.md)
