---
title: "Consuming a data subscription"
description: "Consume a RavenDB data subscription with a client worker: create and run the worker, process document batches, set its strategy, and handle errors."
url: "https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription"
version: "7.2"
language: "python"
---

# Consuming a data subscription

> Client language: Python. Also available for [C#](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.md), [Java](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.java.md), [Node.js](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.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**
>
> - A **subscription worker** is the client-side component that consumes a subscription.
>
> - The worker connects to the server, receives a batch of documents, hands the batch to your processing code, and
>   when done, acknowledges its progress to the server so the server can keep track and provide the next batch.
>
> - This page explains how to create and run a subscription worker using the client API.
>
> - In this article:
>   - [Creating a subscription worker](#creating-a-subscription-worker)
>   - [Running the worker](#running-the-worker)
>   - [Node connection and failover](#node-connection-and-failover)
>   - [At-least-once delivery](#at-least-once-delivery)
>   - [Worker strategies](#worker-strategies)
>   - [Error handling](#error-handling)
>   - [Reading document metadata](#reading-document-metadata)
>   - [Examples](#examples)
>     - [Full exception handling with retries](#example-full-exception-handling-with-retries)
>     - [Setting the batch size](#example-setting-the-batch-size)
>     - [Processing documents in a session](#example-processing-documents-in-a-session)
>     - [Processing dynamic objects](#example-processing-dynamic-objects)
>     - [Reading a document's metadata](#example-reading-a-documents-metadata)
>     - [End when no documents are left](#example-end-when-no-documents-are-left)
>     - [Including documents in the batch](#example-including-documents-in-the-batch)
>     - [Standby workers on several machines](#example-standby-workers-on-several-machines)
>     - [Primary and secondary workers](#example-primary-and-secondary-workers)
>   - [Syntax](#syntax)

## Creating a subscription worker {#creating-a-subscription-worker}

Create a worker using the store's `subscriptions.get_subscription_worker` method (or
`get_subscription_worker_by_name` for default options), passing the document type together with the
subscription name or a [SubscriptionWorkerOptions](#classes) object.

```python
subscription_worker = store.subscriptions.get_subscription_worker_by_name(subscription_name, Order)
```

This constructs the worker but does not run it yet.

## Running the worker {#running-the-worker}

To start processing the documents the server sends, call the worker's `run` method, passing a
function that handles each batch:

```python
def process_batch(batch):
    # your batch-processing logic here
    ...

subscription_worker.run(process_batch)
```

From this point on, the worker receives and processes document batches, acknowledging each batch
so the server can keep track of the subscription's progress and provide the next batch if available.

The `run` method returns a `Future` that stays alive while the worker is processing. If processing is aborted,
the future completes with an exception.

## Node connection and failover {#node-connection-and-failover}

- The worker first contacts one of the database group's nodes. If this node does not run the subscription task,
  the node redirects the worker to the node that does.  
  The worker keeps using the node that runs the task as long as no error occurs.

- If the task is pinned to its mentor node, the worker is always redirected to the mentor node,
  so while the mentor node is down the worker cannot process the subscription.

- If the worker loses the connection and cannot reach the node again, the worker tries the database group's
  other nodes in turn. A node that does not run the task redirects the worker to the node that does.

## At-least-once delivery {#at-least-once-delivery}

The server advances a subscription's progress only when the worker acknowledges a batch.  
If a worker stops (or its connection fails) before acknowledging a batch, the server will re-send the
same batch the next time a worker connects to the subscription.

Delivery is therefore at-least-once: documents may be processed more than once, but none are skipped.
Make your processing idempotent to make sure that reprocessing a document has no unintended effect.

## Worker strategies {#worker-strategies}

A worker is configured with a strategy, set in the
[SubscriptionWorkerOptions](#classes)
`strategy` property, that decides whether the worker may connect to the subscription
and how it behaves toward a worker that is already connected:

- **`OPEN_IF_FREE`**  
  The server lets the worker connect only if no other worker is connected.  
  If another worker is already connected, the incoming worker throws a `SubscriptionInUseException`.
- **`WAIT_FOR_FREE`**  
  If the subscription is in use, the worker waits for the connected worker to disconnect,
  then takes its place.  
  This suits failover, where a standby worker waits to take over from the active one.
- **`TAKE_OVER`**  
  The incoming worker tries to take over the existing connection.  
  It succeeds if the connected worker does not itself use `TAKE_OVER`.
  - If the takeover succeeds, the worker that has been taken over throws a `SubscriptionInUseException`.
  - If the takeover fails, the incoming worker throws the exception instead.

## Error handling {#error-handling}

### Connection failures

When an error interrupts the worker's communication with the server, the worker tries to reconnect
(see [Node connection and failover](#node-connection-and-failover)).  
The worker keeps retrying even when the cluster has no leader to name the node responsible for the
subscription, until the period set in `max_erroneous_period` passes
(see [Reconnection and timeouts](#reconnection-and-timeouts)).

The worker stops without reconnecting in these cases:

- The subscription is in use by another worker, or another worker took it over
  (see [Worker strategies](#worker-strategies)).
- The subscription was disabled, or the worker's connection was dropped
  (see [Dropping connections](https://docs.ravendb.net/7.2/data-subscriptions/maintenance-operations.md#dropping-connections)).
- The worker failed to connect for longer than `max_erroneous_period`.
- An authorization error occurred.
- Your batch-processing code raised an exception, and `ignore_subscriber_errors` is not set
  (see [Errors while processing a batch](#errors-while-processing-a-batch)).
- The worker runs with `close_when_no_docs_left` and no documents are left
  (see [End when no documents are left](#example-end-when-no-documents-are-left)).

---

To follow the worker's attempts to reconnect, register handlers using these worker methods:

- **`add_on_unexpected_subscription_error`**  
  The handler is called when the worker hits an error it does not recognize (e.g., a dropped
  network connection), before the worker waits to reconnect.
- **`add_on_subscription_connection_retry`**  
  The handler is called each time the worker is about to reconnect, after the wait set in
  `time_to_wait_before_connection_retry`.

When the worker stops instead of reconnecting, neither handler is called, and the future returned
by `run` completes in error.

The following code registers both handlers and writes the error message that each handler receives to the console:

```python
# Called for an error the worker does not recognize, before the wait
subscription_worker.add_on_unexpected_subscription_error(
    lambda exception: print(f"Unexpected subscription error: {exception}")
)

# Called before each reconnection attempt, after the wait
subscription_worker.add_on_subscription_connection_retry(
    lambda exception: print(f"Reconnecting to the subscription after: {exception}")
)
```

### Errors while processing a batch

When your batch-processing code raises an exception, the worker's response depends on the
`ignore_subscriber_errors` option of the `SubscriptionWorkerOptions` object:

- **`False`** (default)  
  Processing stops. The worker wraps the exception in a `SubscriberErrorException` and rethrows
  it without acknowledging progress, so the future returned by `run` completes in error.
- **`True`**  
  The failed batch is acknowledged without a retry, and the worker continues with the next
  batches.

### Reconnection and timeouts

These `SubscriptionWorkerOptions` properties govern reconnection and connection timeouts:

- **`time_to_wait_before_connection_retry`**  
  How long the worker waits before each reconnect attempt.  
  Default: 5 seconds.
- **`max_erroneous_period`**  
  How long the worker may keep failing to reconnect, counted from the first failure since its last successful
  connection, before the worker stops retrying.  
  Default: 5 minutes.
- **`connection_stream_timeout`**  
  How long the worker waits for data from the server, or for a write to the server to complete,
  before the worker treats its connection to the server as broken and tries to reconnect.  
  Default: 30 seconds. Minimum: 15 seconds.

  > **Info**
  >
  > To set `connection_stream_timeout`, use Python client version 7.2.7 or later.

## Reading document metadata {#reading-document-metadata}

The `metadata` property of each batch item holds the metadata
of the item's document (see [Item](#classes)),
with properties set by RavenDB (e.g., `@collection` and `@last-modified`) and any property you set yourself (like `trace.id`,
which the worker in the example below reads from each item's document).

```python
def process_batch(batch):
    for item in batch.items:
        # Read a metadata property you set yourself
        # ('get' returns None if the metadata does not hold the property)
        trace_id = item.metadata.get("trace.id")
        if trace_id is not None:
            # your processing logic here
            ...

subscription_worker.run(process_batch)
```

Changing a document's metadata changes the document. If the changed document matches the subscription's query,
the subscription sends the document to the worker along with the changed metadata held in the item's `metadata` property.

> **Note**
>
> - When a subscription's query applies a [projection](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.python.md#processing-projected-objects),
>   the `metadata` property of each item holds the metadata **of the item's projected object**, not the metadata of the source document.
> - When a subscription sends document revisions, each item holds two revisions of a
>   document, each revision carrying its own metadata.  
>   The item's `metadata` property holds only a few properties RavenDB sets for the item itself, like `@id` and `@change-vector`,
>   **not** the metadata of either revision.

See [Example: Reading a document's metadata](#example-reading-a-documents-metadata)

## Examples {#examples}

### Example: Full exception handling with retries

In this example, the client handles the exceptions the worker may throw,
recreating the worker to resume processing when the error is recoverable.

```python
while True:
    options = SubscriptionWorkerOptions(subscription_name)

    # Allow a downtime of up to 2 hours, and wait 2 minutes before reconnecting
    options.max_erroneous_period = timedelta(hours=2)
    options.time_to_wait_before_connection_retry = timedelta(minutes=2)

    subscription_worker = store.subscriptions.get_subscription_worker(options, Order)

    try:
        # Before each reconnection attempt, write the error that caused it to the console
        subscription_worker.add_on_subscription_connection_retry(
            lambda exception: print(f"Reconnecting to the subscription after: {exception}")
        )

        def _process_documents_callback(batch):
            for item in batch.items:
                # Forcefully stop processing for a specific case,
                # and raise an exception to let external logic handle it
                if item.result.company == "companies/2-A":
                    # The exception raised here will be wrapped by `SubscriberErrorException`
                    raise UnsupportedCompanyException(
                        "Company Id can't be 'companies/2-A', you must fix this"
                    )
                process_order(item.result)

        # Pass the callback to run(), and wait for the future that run() returns,
        # so an exception raised while processing a batch reaches the except block
        subscription_worker.run(_process_documents_callback).result()

        # The future that run() returns completes normally if you close the worker
        break

    except Exception as e:
        print(f"Failure in subscription {subscription_name}: {e}")
        exception_type = type(e)

        # The following exceptions are not recoverable
        if exception_type in (
            DatabaseDoesNotExistException,
            SubscriptionDoesNotExistException,
            SubscriptionInvalidStateException,
            AuthorizationException,
        ):
            raise

        if exception_type is SubscriptionClosedException:
            # Subscription probably closed explicitly by admin
            break

        if exception_type is SubscriberErrorException:
            # For UnsupportedCompanyException we want to raise, otherwise continue processing
            if e.args[1] is not None and type(e.args[1]) is UnsupportedCompanyException:
                raise
            continue

        # Handle this depending on the subscription opening strategy
        if exception_type is SubscriptionInUseException:
            continue

        break

    finally:
        subscription_worker.close(False)
```

### Example: Setting the batch size

In this example, the worker sets the maximum number of documents the server sends in each batch.

```python
worker_w_batch = store.subscriptions.get_subscription_worker(
    SubscriptionWorkerOptions(subscription_name, max_docs_per_batch=20), Order
)

# Pass a function that takes a SubscriptionBatch[Order], with your logic in it
worker_w_batch.run(lambda batch: ...)
```

### Example: Processing documents in a session

In this example, the subscription sends to the worker `Orders` that have no shipping date.  
The worker sets each document's `ShippedAt` field and saves it back through a session.

> **Info**
>
> Open the session using `batch.open_session`, not `store.open_session`.

```python
# Create the subscription task on the server:
subscription_name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(query="from Orders as o where o.ShippedAt = null")
)

# Create the subscription worker that will consume the documents:
subscription_worker = store.subscriptions.get_subscription_worker_by_name(subscription_name, Order)

def _transfer_order_callback(batch):
    # Open a session using 'batch.open_session'
    with batch.open_session() as session:
        for order in (item.result for item in batch.items):
            transfer_order_to_shipment_company(order)  # call your custom method
            order.ShippedAt = datetime.utcnow()         # update the document field

        # Save the updated Order documents
        session.save_changes()

subscription_worker.run(_transfer_order_callback)
```

### Example: Processing dynamic objects

In this example, the subscription projects each `Order` into a dynamic shape, and the worker processes the
dynamic objects it receives.

```python
# Create the subscription task on the server:
subscription_name = "My dynamic subscription"
store.subscriptions.create_for_class(
    Order,
    SubscriptionCreationOptions(
        subscription_name,
        query="""
        from Orders as o
        select {
            dynamic_field: "Company: " + o.Company + " Employee: " + o.Employee
        }
        """,
    ),
)

# Create the subscription worker that will consume the documents:
subscription_worker = store.subscriptions.get_subscription_worker_by_name(subscription_name)

def _raise_notification_callback(batch):
    for item in batch.items:
        # Access the dynamic field in the document
        raise_notification(item.result["dynamic_field"])  # call your custom method

subscription_worker.run(_raise_notification_callback)
```

### Example: Reading a document's metadata

In this example, the application sets a `trace.id` metadata property in an `Order` document, and the worker reads this property from each order
the subscription sends.  
For an explanation of the metadata an item holds, see
[Reading document metadata](#reading-document-metadata).

#### Setting the metadata property

```python
with store.open_session() as session:
    order = session.load("orders/1-A", Order)

    # Set a metadata property of your own
    session.advanced.get_metadata_for(order)["trace.id"] = "1234567"

    # Saving the change makes the subscription send the order to the worker,
    # if the order matches the subscription's query
    session.save_changes()
```

#### Reading the metadata property in the worker

```python
subscription_worker = store.subscriptions.get_subscription_worker_by_name(subscription_name, Order)

def process_batch(batch):
    for item in batch.items:
        # 'get' returns None for orders whose metadata does not hold 'trace.id'
        trace_id = item.metadata.get("trace.id")
        if trace_id is not None:
            print(f"Order {item.key} has the trace ID {trace_id}")

subscription_worker.run(process_batch)
```

### Example: End when no documents are left

In this example, the worker runs until no new documents remain, which suits ad-hoc, single-use processing where
you need every matching document processed once.  
Set `close_when_no_docs_left` to `True`; the worker then throws a `SubscriptionClosedException` when
it finishes.

```python
# Create the subscription task on the server:
subscription_name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        query="""
        declare function getOrderLinesSum(doc) {
            var sum = 0;
            for (var i in doc.Lines) {
                sum += doc.Lines[i].PricePerUnit * doc.Lines[i].Quantity;
            }
            return sum;
        }

        from Orders as o
        where getOrderLinesSum(o) > 10000
        select {
            OrderId: id(o),
            Company: load(o.Company)
        }
        """
    )
)

# Create the subscription worker that will consume the documents:
high_value_orders_worker = store.subscriptions.get_subscription_worker(
    SubscriptionWorkerOptions(
        subscription_name,
        # Stop when there are no more documents left to send,
        # throwing a SubscriptionClosedException when it finishes
        close_when_no_docs_left=True,
    ),
    OrderAndCompany,
)

try:
    def _subscription_batch_callback(batch):
        for item in batch.items:
            send_thank_you_note_to_company(item.result)  # call your custom method

    high_value_orders_worker.run(_subscription_batch_callback).result()
except SubscriptionClosedException:
    # That's expected, no more documents to process
    ...
```

### Example: Including documents in the batch

In this example, the subscription sends to the worker every `Order` and includes in the batch
`Product` documents referenced in the order.  
When the worker accesses an included `Product`, the product's data has already arrived in the batch,
so the worker does not need to fetch the product from the server.

```python
# Create the subscription task on the server:
subscription_name = store.subscriptions.create_for_options(
    SubscriptionCreationOptions(
        # Include the referenced Product documents for each Order document
        query="from Orders include Lines[].Product"
    )
)

# Create the subscription worker that will consume the documents:
subscription_worker = store.subscriptions.get_subscription_worker_by_name(subscription_name, Order)

def _process_orders_and_products_callback(batch):
    # Open a session using 'batch.open_session' to access the Product documents
    with batch.open_session() as session:
        for order in (item.result for item in batch.items):
            for order_line in order.lines:
                # Calling load() will not generate a request to the server,
                # since the Product document that order_line["Product"] refers to was included in the batch
                product = session.load(order_line["Product"], Product)

                process_order_and_product(order, product)  # call your custom method

subscription_worker.run(_process_orders_and_products_callback)
```

### Example: Standby workers on several machines

In this example, the same worker code runs on several machines, all using the `WAIT_FOR_FREE` strategy.  
One worker connects to the subscription, and the other workers wait.  
If the connected worker disconnects (e.g., when its machine goes down), one of the waiting workers connects and
continues processing.  
Unlike in the [primary and secondary workers](#example-primary-and-secondary-workers)
example, a worker that reconnects after a failure does not take the connection back, but joins the waiting workers.

```python
worker = store.subscriptions.get_subscription_worker(
    # WAIT_FOR_FREE: wait and take over if the connected worker fails
    SubscriptionWorkerOptions(subscription_name, strategy=SubscriptionOpeningStrategy.WAIT_FOR_FREE),
    Order,
)
```

### Example: Primary and secondary workers

In this example, the two workers form an active-standby pair: the primary, using `TAKE_OVER`, establishes the
connection; the secondary, using `WAIT_FOR_FREE`, waits to take over if the primary fails.

The primary worker:

```python
while True:
    # Create a new worker for each attempt: a worker cannot run again once run() was called
    primary_worker = store.subscriptions.get_subscription_worker(
        SubscriptionWorkerOptions(subscription_name, strategy=SubscriptionOpeningStrategy.TAKE_OVER),
        Order,
    )

    try:
        primary_worker.run(lambda batch: ...).result()  # your logic
    except Exception:
        ...  # retry
    finally:
        primary_worker.close(False)
```

The secondary worker:

```python
while True:
    # Create a new worker for each attempt: a worker cannot run again once run() was called
    secondary_worker = store.subscriptions.get_subscription_worker(
        SubscriptionWorkerOptions(subscription_name, strategy=SubscriptionOpeningStrategy.WAIT_FOR_FREE),
        Order,
    )

    try:
        secondary_worker.run(lambda batch: ...).result()  # your logic
    except Exception:
        ...  # retry
    finally:
        secondary_worker.close(False)
```

## Syntax {#syntax}

### Methods

#### get\_subscription\_worker

Create a subscription worker through `store.subscriptions`.

```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 | Type | Description |
| - | - | - |
| **options** | `SubscriptionWorkerOptions` | Options that affect how the worker interacts with the subscription. They do not change the subscription's own definition. See the [Classes](#classes) below. |
| **subscription\_name** | `str` | The name of the subscription the worker connects to. |
| **object\_type** | `Type[_T]` | The document class the worker deserializes items into. |
| **database** | `str` | The database where the subscription task resides. If `None`, the document store's default database is used. |

| Return value | |
| - | - |
| `SubscriptionWorker` | The created worker. It is idle until you call `run`. |

#### run

Start the worker's batch processing. Pass the function that processes each received batch.

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

| Parameter | Type | Description |
| - | - | - |
| **process\_documents** | `Callable[[SubscriptionBatch[_T]], Any]` | Function for batch processing. |

| Return value | |
| - | - |
| `Future` | A future that stays alive while the worker is processing or trying to. If processing is aborted, the future completes with an exception. |

### Classes

#### SubscriptionWorkerOptions

When you create a worker using `SubscriptionWorkerOptions`, the only required property is
`subscription_name`; the rest fall back to their defaults.

| Property | Type | Description |
| - | - | - |
| **subscription\_name** | `str` | The name of the subscription the worker connects to. |
| **max\_docs\_per\_batch** | `int` | The maximum number of documents the server tries to send in a batch. If it finds fewer, it sends what it has without waiting. Default: 4096. |
| **send\_buffer\_size** | `int` | The size of the TCP socket buffer the worker uses to send data. Default: 32,768 bytes (32 KiB). |
| **receive\_buffer\_size** | `int` | The size of the TCP socket buffer the worker uses to receive data. Default: 32,768 bytes (32 KiB). |
| **ignore\_subscriber\_errors** | `bool` | Whether processing continues when your batch-handling code throws. `True` continues; `False` (default) aborts. |
| **close\_when\_no\_docs\_left** | `bool` | Whether the connection closes when no new documents remain. `True` processes all available documents and then throws a `SubscriptionClosedException` (useful for one-time processing); `False` (default) keeps the worker waiting for new documents. |
| **time\_to\_wait\_before\_connection\_retry** | `timedelta` | The wait before each reconnection attempt.<br />Default: 5 seconds. |
| **max\_erroneous\_period** | `timedelta` | How long the worker may keep failing to reconnect, counted from the first failure since its last successful connection, before the worker stops retrying.<br />Default: 5 minutes. |
| **connection\_stream\_timeout** | `timedelta` | How long the worker waits for data from the server, or for a write to the server to complete, before the worker treats its connection to the server as broken.<br />Default: 30 seconds. Minimum: 15 seconds.<br />To set `connection_stream_timeout`, use Python client version 7.2.7 or later. |
| **strategy** | `SubscriptionOpeningStrategy` | How the server handles this worker's connection attempt. Default: `OPEN_IF_FREE`. |

#### SubscriptionOpeningStrategy

The strategy that decides whether a worker may connect to a subscription. See
[Worker strategies](#worker-strategies).

```python
class SubscriptionOpeningStrategy(Enum):
    # Connect if no other worker is connected
    OPEN_IF_FREE = "OpenIfFree"

    # Take over the connection
    TAKE_OVER = "TakeOver"

    # Wait for the currently connected worker to disconnect
    WAIT_FOR_FREE = "WaitForFree"
```

#### SubscriptionBatch\[\_T]

The batch passed to your `run` function (see [Running the worker](#running-the-worker)).

| Property | Type | Description |
| - | - | - |
| **items** | `Item[]` | The items in the batch. |
| **number\_of\_items\_in\_batch** | `int` | The number of items in the batch. |
| **number\_of\_includes** | `int` | `1` if the server sent included documents with the batch, `0` if it did not. |

| Method | Return value | Description |
| - | - | - |
| **open\_session(options=None)** | `DocumentSession` | Opens a session that tracks the batch's documents and included documents.<br />Projected items and revisions are not tracked (see [Processing projected objects](https://docs.ravendb.net/7.2/data-subscriptions/creating-subscription/creating-subscription_api.python.md#processing-projected-objects)).<br />Pass `options` to open the session with the given [session options](https://docs.ravendb.net/7.2/client-api/session/opening-a-session.python.md#session-options). |

> **Note**
>
> - Do not set `database` or `request_executor` in the session options:
>   the session always uses the subscription's database and the node the worker is connected to.
>   Setting either of them throws an exception.
>
> - Set the transaction mode in the session options to `TransactionMode.SINGLE_NODE` explicitly.
>   Any other transaction mode throws an exception, and so does leaving the transaction mode unset.
>
> - The session does not fail over to other nodes. If the node the worker is connected to fails while your code uses
>   the session, the session's requests throw an exception, which reaches your batch-processing code
>   (see [Errors while processing a batch](#errors-while-processing-a-batch)).

#### Item

A single item in a subscription batch.

| Property | Type | Description |
| - | - | - |
| **result** | `_T` | The batch item. |
| **key** | `str` | The document ID of the item's underlying document. |
| **change\_vector** | `str` | The change vector of the item's underlying document. |
| **is\_projection** | `bool` | `True` when the item is a projection produced by the subscription query rather than a full document. |
| **is\_revision** | `bool` | `True` when the item is a document revision, for a subscription that streams revisions. |
| **raw\_result** | `Dict` | The item before deserialization. |
| **raw\_metadata** | `Dict` | The item's metadata, as a raw JSON object. |
| **metadata** | `MetadataAsDictionary` | The item's metadata, as a dictionary.<br />For an item that holds a document: the document's metadata.<br />For a projected item: the metadata of the projected object.<br />For a revision item: only a few properties RavenDB sets for the item.<br />See [Reading document metadata](#reading-document-metadata). |

> **Warning**
>
> Use these values only within the subscription's `run` function. Using them outside that scope may
> cause unexpected behavior.

The worker returned by `get_subscription_worker`.

**Methods**

| Method | Return type | Description |
| - | - | - |
| **close(wait\_for\_subscription\_task=True)** | `None` | Aborts the worker, optionally waiting for the future returned by `run` to finish. |
| **run(process\_documents)** | `Future` | Starts the worker's batch processing. See [run](#methods) above. |

**Events**

| Event | Type | Description |
| - | - | - |
| **add\_on\_subscription\_connection\_retry** | `Callable[[Exception], None]` | Fires each time the worker is about to reconnect, after the wait set in `time_to_wait_before_connection_retry`.<br />Receives the exception that caused the reconnection. |
| **add\_on\_unexpected\_subscription\_error** | `Callable[[Exception], None]` | Fires when the worker hits an error it does not recognize, before the worker waits to reconnect.<br />Receives the exception. |
| **add\_after\_acknowledgment** | `Callable[[SubscriptionBatch[_T]], None]` | Fires after the server acknowledges the progress of a processed batch. |

**Properties**

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