---
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: "csharp"
---

# Consuming a data subscription

> Client language: C#. Also available for [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), [Python](https://docs.ravendb.net/7.2/data-subscriptions/consuming-subscription.python.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)
>   - [Worker status](#worker-status)
>   - [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)
>     - [Processing a blittable object](#example-processing-a-blittable-object)
>     - [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.GetSubscriptionWorker` method, passing either the
subscription name or a [SubscriptionWorkerOptions](#classes) object.

```csharp
subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
```

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 the
logic that handles each batch:

```csharp
subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    // your batch-processing logic here
});
```

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 task that stays alive while the worker is processing. If processing is aborted,
this task completes with an exception.

> **Info:** Processing batches asynchronously
>
> Processing batches **synchronously** (by passing `Run` a synchronous function) may delay other operations your
> application is running.  
> When your batch-processing code performs an operation that waits for an external resource (e.g., saving changes
> to the server through the batch's session), the thread that runs your code is blocked until the operation
> completes, and other operations cannot use this thread meanwhile.  
> When many threads are blocked this way (e.g., when several workers wait at the same time), other operations may
> have to wait for a free thread.
>
> Processing batches **asynchronously** frees the thread while an operation that waits for an external resource
> is in progress, so other operations can use the thread.  
> To process batches asynchronously, pass `Run` an `async` function that awaits asynchronous methods
> (like the `LoadAsync` and `SaveChangesAsync` methods of a session opened with `batch.OpenAsyncSession`).  
> See, for instance, the **Async** tab of the
> [processing documents in a session](#example-processing-documents-in-a-session)
> example.
>
> Whether you process batches synchronously or asynchronously, the worker passes the next batch to your code only
> after your code finishes processing the current batch.

## 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.

[Concurrent subscriptions](https://docs.ravendb.net/7.2/data-subscriptions/concurrent-subscriptions.md#connection-failure-and-reassignment)
add another way a document can be reprocessed, by reassigning a dropped worker's documents to the
other workers.

## 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.

The following strategies allow only one worker connected at a time:

- **`OpenIfFree`**  
  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`.
- **`WaitForFree`**  
  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.
- **`TakeOver`**  
  The incoming worker tries to take over the existing connection.  
  It succeeds if the connected worker does not itself use `TakeOver`.
  - 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.

To let several workers consume the same subscription at the same time, use the `Concurrent` strategy.
See [Concurrent subscriptions](https://docs.ravendb.net/7.2/data-subscriptions/concurrent-subscriptions.md).

### First worker to connect sets the subscription mode

The first worker to connect sets whether the subscription runs in single-worker or concurrent mode,
and this mode holds until all workers disconnect:

- A subscription running concurrent workers admits only other concurrent workers. A worker that uses
  a single-worker strategy is rejected with `SubscriptionInUseException`.
- A subscription running a single-worker strategy admits no concurrent worker until the connected
  worker disconnects. A concurrent worker is rejected with `SubscriptionInUseException`.

## 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 it cannot reach any server, or when the cluster has no leader to
name the node responsible for the subscription, until the period set in `MaxErroneousPeriod` passes
(see [Reconnection and timeouts](#reconnection-and-timeouts)).

The worker stops without reconnecting in these cases:

- The subscription does not exist (e.g., it was deleted).
- The subscription is in use by another worker, or another worker took it over
  (see [Worker strategies](#worker-strategies)).
- The worker uses the `Concurrent` strategy on a sharded database, which does not support concurrent subscriptions
  (see [Unsupported features](https://docs.ravendb.net/7.2/sharding/subscriptions.md#unsupported-features)).
- 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 `MaxErroneousPeriod`.
- The subscription cannot run in its current state (e.g., a revisions subscription on a collection
  whose revisions are disabled).
- An authorization error occurred.
- The database does not exist.
- Your batch-processing code threw an exception, and `IgnoreSubscriberErrors` is not set
  (see [Errors while processing a batch](#errors-while-processing-a-batch)).
- The worker runs with `CloseWhenNoDocsLeft` and no documents are left
  (see [End when no documents are left](#example-end-when-no-documents-are-left)).

---

When the worker stops instead of reconnecting, the task returned by `Run` completes in error.  
To follow the worker's connection and reconnection attempts,
see [Worker status](#worker-status).

### Errors while processing a batch

When your batch-processing code throws an exception, the worker's response depends on the
`IgnoreSubscriberErrors` 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 task 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:

- **`TimeToWaitBeforeConnectionRetry`**  
  How long the worker waits before each reconnect attempt.  
  Default: 5 seconds.
- **`MaxErroneousPeriod`**  
  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.
- **`ConnectionStreamTimeout`**  
  How long the worker waits for data from the server, or for a write to the server to complete,
  before treating the connection as broken and trying to reconnect.  
  Default: 30 seconds. Cannot be set below 15 seconds.

```csharp
var options = new SubscriptionWorkerOptions(subscriptionName);

// Set the worker's timeout period
options.ConnectionStreamTimeout = TimeSpan.FromSeconds(45);
```

## Worker status {#worker-status}

### Status and state changes

To check the worker's current activity (e.g., whether the worker is connected to the server), read the worker's `Status` property.  
The `Status` property returns a [SubscriptionWorkerStatus](#classes) object,
whose `State` property holds one of the following states:

- **`NotStarted`**  
  The worker was created, but `Run` has not been called yet.
- **`Connecting`**  
  The worker is connecting to the subscription, at startup or before a reconnection.
- **`WaitingForDocuments`**  
  The worker is connected and waiting for the next batch.
- **`Processing`**  
  Your processing code is handling a batch.  
  This state lasts until the worker acknowledges the batch to the server.
- **`Retrying`**  
  The connection failed, and the worker is waiting to reconnect
  (see [Connection failures](#connection-failures)).
- **`Faulted`**  
  The worker stopped without reconnecting, and the task returned by `Run` completed in error.
- **`Stopped`**  
  The worker was disposed, or the cancellation token passed to `Run` was canceled.

Once the worker reaches `Faulted` or `Stopped`, the worker's state no longer changes.

When the state is `Retrying` or `Faulted`, the `Exception` property of the `SubscriptionWorkerStatus` object holds the failure
that caused the state.  
If the worker fails repeatedly, the `Exception` property holds the latest failure.  
The `FailingSinceUtc` property of the `SubscriptionWorkerStatus` object holds the time of the first failure since the worker's
last successful connection, or `null` while the worker is connected.

Read `Status` when your application needs the worker's state at a specific moment (e.g., when a health check runs).  
To be notified of every state change as soon as the change happens (e.g., to raise an alert when the worker starts retrying),
subscribe to the worker's `OnStateChanged` event.  
The event passes the worker and the worker's new status (a `SubscriptionWorkerStatus` object) to your handler.  
The worker does not continue until your handler returns, so avoid long-running or blocking work in the handler:
a handler that never returns keeps the worker from continuing.  
If the handler throws an exception, the worker catches the exception and continues.

```csharp
// FailingSinceUtc is null while the worker is connected, and is set while the worker is failing
SubscriptionWorkerStatus status = subscriptionWorker.Status;
if (status.FailingSinceUtc != null)
    Console.WriteLine($"Failing since {status.FailingSinceUtc}: {status.Exception?.Message}");

// Write each change of the worker's state to the console
subscriptionWorker.OnStateChanged += (worker, newStatus) =>
{
    Console.WriteLine($"Worker state: {newStatus.State}");
};
```

To monitor the subscription on the server side using Studio,
see [Monitoring a data subscription](https://docs.ravendb.net/7.2/data-subscriptions/monitoring.md).

### Worker events

> **Note**
>
> The worker's events are standard C# events: attach a handler to an event using `+=`, and detach the handler using `-=`
> (see [Subscribing to store events](https://docs.ravendb.net/7.2/client-api/how-to/subscribe-to-store-events.md), which shows both operations
> on the document store's events).  
> To detach a handler later, keep a reference to the handler when you attach it (e.g., use a named method rather than
> a lambda expression), since `-=` must receive the same handler.

To react to the worker's connections, failures, acknowledged batches, and disposal, subscribe to these worker events:

- **`OnEstablishedSubscriptionConnection`**  
  Fires each time the worker connects to the subscription, both the first time and after every reconnection.
- **`OnUnexpectedSubscriptionError`**  
  Fires when the worker hits an error it does not recognize (e.g., a dropped network connection),
  before the worker waits to reconnect.
- **`OnSubscriptionConnectionRetry`**  
  Fires each time the worker is about to reconnect, after the wait set in `TimeToWaitBeforeConnectionRetry`.
- **`AfterAcknowledgment`**  
  Fires after the server acknowledges the progress of a processed batch.  
  The handler receives the acknowledged batch and returns a `Task`.
  The worker passes the next batch to your code only after this task completes.
- **`OnDisposed`**  
  Fires after the worker is disposed.

When the worker stops instead of reconnecting, neither `OnUnexpectedSubscriptionError`
nor `OnSubscriptionConnectionRetry` fires.

The following code writes a message to the console on each connection, unrecognized error, and reconnection attempt:

```csharp
// Fires on the first connection and after every reconnection
subscriptionWorker.OnEstablishedSubscriptionConnection += () =>
{
    Console.WriteLine("Connected to the subscription");
};

// Fires for an error the worker does not recognize, before the wait
subscriptionWorker.OnUnexpectedSubscriptionError += exception =>
{
    Console.WriteLine($"Unexpected subscription error: {exception.Message}");
};

// Fires before each reconnection attempt, after the wait
subscriptionWorker.OnSubscriptionConnectionRetry += exception =>
{
    Console.WriteLine($"Reconnecting to the subscription after: {exception.Message}");
};
```

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

The `Metadata` property of each batch item holds the [metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.md)
of the item's document (see [SubscriptionBatch\<T>.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).

```csharp
subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    foreach (var item in batch.Items)
    {
        // Read a metadata property you set yourself
        // ('TryGetValue' returns false if the metadata does not hold the property)
        if (item.Metadata.TryGetValue("trace.id", out string traceId))
        {
            // your processing logic here
        }
    }
});
```

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 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.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](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md), 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)  
See [Reading a revision's metadata](https://docs.ravendb.net/7.2/data-subscriptions/revisions-support.md#reading-a-revision-s-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.

```csharp
while (true)
{
    // Create the worker:
    var options = new SubscriptionWorkerOptions(subscriptionName);

    // Configure the worker:
    // Allow a downtime of up to 2 hours,
    // and wait 2 minutes before reconnecting
    options.MaxErroneousPeriod = TimeSpan.FromHours(2);
    options.TimeToWaitBeforeConnectionRetry = TimeSpan.FromMinutes(2);

    subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(options);

    try
    {
        // Before each reconnection attempt, write the error that caused it to the console
        subscriptionWorker.OnSubscriptionConnectionRetry += exception =>
        {
            Console.WriteLine($"Reconnecting to the subscription after: {exception.Message}");
        };

        // Run the worker:
        await subscriptionWorker.Run(batch =>
        {
            foreach (var item in batch.Items)
            {
                // Forcefully stop subscription processing if the order's Company is "companies/2-A"
                // and throw an exception to let external logic handle the specific case
                if (item.Result.Company == "companies/2-A")
                {
                    // The custom exception thrown from here
                    // will be wrapped by `SubscriberErrorException`
                    throw new UnsupportedCompanyException(
                        "Company ID cannot be 'companies/2-A', please fix");
                }

                // Process the order document - provide your own logic
                ProcessOrder(item.Result);
            }
        }, cancellationToken);

        // The Run method will stop if the subscription worker is disposed,
        // exiting the while loop
        return;
    }
    catch (Exception e)
    {
        Console.WriteLine($"Failure in subscription {subscriptionName}: {e.Message}");

        // The following exceptions are not recoverable
        if (e is DatabaseDoesNotExistException ||
            e is SubscriptionDoesNotExistException ||
            e is SubscriptionInvalidStateException ||
            e is AuthorizationException)
            throw;

        if (e is SubscriptionClosedException)
            // Subscription probably closed explicitly by admin
            return;

        if (e is SubscriberErrorException se)
        {
            // For UnsupportedCompanyException we want to throw an exception,
            // otherwise, continue processing
            if (se.InnerException != null && se.InnerException is UnsupportedCompanyException)
            {
                throw;
            }

            // Call continue to skip the current while(true) iteration and try reconnecting
            // in the next one, allowing the worker to process future batches.
            continue;
        }

        // Handle this depending on the subscription opening strategy
        if (e is SubscriptionInUseException)
            continue;

        // Call return to exit the while(true) loop,
        // dispose of the worker (via finally), and stop the subscription.
        return;
    }
    finally
    {
        subscriptionWorker.Dispose();
    }
}
```

### Example: Setting the batch size

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

```csharp
var workerWBatch = store.Subscriptions.GetSubscriptionWorker<Order>(
    new SubscriptionWorkerOptions(subscriptionName)
    {
        MaxDocsPerBatch = 20
    });

var subscriptionRuntimeTask = workerWBatch.Run(x =>
{
    // your custom logic
});
```

### 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.OpenSession` or `batch.OpenAsyncSession`, not `store.OpenSession` or `store.OpenAsyncSession`.

#### Sync

```csharp
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
    Query = @"from Orders as o where o.ShippedAt = null"
});

// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    // Open a session using 'batch.OpenSession'
    using (var session = batch.OpenSession())
    {
        foreach (var order in batch.Items.Select(x => x.Result))
        {
            TransferOrderToShipmentCompany(order); // call your custom method
            order.ShippedAt = DateTime.UtcNow;     // update the document field
        }

        // Save the updated Order documents
        session.SaveChanges();
    }
});
```

#### Async

```csharp
// Create the subscription task on the server:
var subscriptionName = await store.Subscriptions.CreateAsync(new SubscriptionCreationOptions()
{
    Query = @"from Orders as o where o.ShippedAt = null"
});

// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
// Pass an async function, so the thread is not blocked while your code awaits the server
var subscriptionRuntimeTask = subscriptionWorker.Run(async batch =>
{
    // Open an asynchronous session using 'batch.OpenAsyncSession'
    using (var session = batch.OpenAsyncSession())
    {
        foreach (var order in batch.Items.Select(x => x.Result))
        {
            TransferOrderToShipmentCompany(order); // call your custom method
            order.ShippedAt = DateTime.UtcNow;     // update the document field
        }

        // Save the updated Order documents
        await session.SaveChangesAsync();
    }
});
```

### 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.

```csharp
// Create the subscription task on the server:
var subscriptionName = "My dynamic subscription";
store.Subscriptions.Create(new SubscriptionCreationOptions<Order>()
{
    Name = subscriptionName,
    Projection = order =>
        new { DynamicField = "Company: " + order.Company + " Employee: " + order.Employee }
});

// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    foreach (var item in batch.Items)
    {
        // Access the dynamic field in the document
        dynamic field = item.Result.DynamicField;

        // Call your custom method
        ProcessItem(field);
    }
});
```

### Example: Processing a blittable object

In this example, the worker processes documents as low-level blittable objects.

> **Warning**
>
> Working with blittable objects directly can help in extreme high-performance scenarios, but is
> risky because it uses unmanaged memory directly.

```csharp
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
    Projection = x => new
    {
        x.Employee
    }
});

// Create the subscription worker that will consume the documents:
var subscriptionWorker =
    // Specify `BlittableJsonReaderObject` as the generic type parameter
    store.Subscriptions.GetSubscriptionWorker<BlittableJsonReaderObject>(subscriptionName);

var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    foreach (var item in batch.Items)
    {
        // Access the Employee field within the blittable object
        var employeeField = item.Result["Employee"].ToString();

        ProcessItem(employeeField); // call your custom method
    }
});
```

### 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

```csharp
using (var session = store.OpenSession())
{
    var order = session.Load<Order>("orders/1-A");

    // Set a metadata property of your own
    session.Advanced.GetMetadataFor(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.SaveChanges();
}
```

#### Reading the metadata property in the worker

```csharp
var worker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);

var subscriptionRuntimeTask = worker.Run(batch =>
{
    foreach (var item in batch.Items)
    {
        // 'TryGetValue' returns false for orders whose metadata does not hold 'trace.id'
        if (item.Metadata.TryGetValue("trace.id", out string traceId))
        {
            Console.WriteLine($"Order {item.Id} has the trace ID {traceId}");
        }
    }
});
```

### 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 `CloseWhenNoDocsLeft` to `true`; the worker then throws a `SubscriptionClosedException` when
it finishes.

```csharp
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create<Order>(
    new SubscriptionCreationOptions<Order>
    {
        Filter = order => order.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 10000,
        Projection = order => new OrderAndCompany
        {
            OrderId = order.Id,
            Company = RavenQuery.Load<Company>(order.Company)
        }
    });

// Create the subscription worker that will consume the documents:
var highValueOrdersWorker = store.Subscriptions.GetSubscriptionWorker<OrderAndCompany>(
    new SubscriptionWorkerOptions(subscriptionName)
    {
        // Here we set the worker to stop when there are no more documents left to send
        // Will throw SubscriptionClosedException when it finishes its job
        CloseWhenNoDocsLeft = true
    });

try
{
    await highValueOrdersWorker.Run(batch =>
    {
        foreach (var item in batch.Items)
        {
            SendThankYouNoteToCompany(item.Result); // call your custom method
        }
    });
}
catch (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.

#### Sync

```csharp
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new 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:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
    // Open a session using 'batch.OpenSession' to access the Product documents
    using (var session = batch.OpenSession())
    {
        foreach (var order in batch.Items.Select(x => x.Result))
        {
            foreach (var orderLine in order.Lines)
            {
                // Calling Load will not generate a request to the server,
                // since orderLine.Product was included in the batch
                var product = session.Load<Product>(orderLine.Product);

                ProcessOrderAndProduct(order, product); // call your custom method
            }
        }
    }
});
```

#### Async

```csharp
// Create the subscription task on the server:
var subscriptionName = await store.Subscriptions.CreateAsync(new 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:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
// Pass an async function, so the thread is not blocked while your code awaits the server
var subscriptionRuntimeTask = subscriptionWorker.Run(async batch =>
{
    // Open an asynchronous session using 'batch.OpenAsyncSession' to access the Product documents
    using (var session = batch.OpenAsyncSession())
    {
        foreach (var order in batch.Items.Select(x => x.Result))
        {
            foreach (var orderLine in order.Lines)
            {
                // Calling LoadAsync will not generate a request to the server,
                // since orderLine.Product was included in the batch
                var product = await session.LoadAsync<Product>(orderLine.Product);

                ProcessOrderAndProduct(order, product); // call your custom method
            }
        }
    }
});
```

### Example: Standby workers on several machines

In this example, the same worker code runs on several machines, all using the `WaitForFree` 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.

```csharp
var worker = store.Subscriptions.GetSubscriptionWorker<Order>(
    new SubscriptionWorkerOptions(subscriptionName)
    {
        // WaitForFree: wait and take over if the connected worker fails
        Strategy = SubscriptionOpeningStrategy.WaitForFree
    });
```

### Example: Primary and secondary workers

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

The primary worker:

```csharp
while (true)
{
    // Create a new worker for each attempt: a worker cannot run again once Run was called
    var primaryWorker = store.Subscriptions.GetSubscriptionWorker<Order>(
        new SubscriptionWorkerOptions(subscriptionName)
        {
            Strategy = SubscriptionOpeningStrategy.TakeOver
        });

    try
    {
        await primaryWorker.Run(x =>
        {
            // your logic
        });
    }
    catch (Exception)
    {
        // retry
    }
    finally
    {
        primaryWorker.Dispose();
    }
}
```

The secondary worker:

```csharp
while (true)
{
    // Create a new worker for each attempt: a worker cannot run again once Run was called
    var secondaryWorker = store.Subscriptions.GetSubscriptionWorker<Order>(
        new SubscriptionWorkerOptions(subscriptionName)
        {
            Strategy = SubscriptionOpeningStrategy.WaitForFree
        });

    try
    {
        await secondaryWorker.Run(x =>
        {
            // your logic
        });
    }
    catch (Exception)
    {
        // retry
    }
    finally
    {
        secondaryWorker.Dispose();
    }
}
```

## Syntax {#syntax}

### Methods

#### GetSubscriptionWorker

Create a subscription worker through `store.Subscriptions`.

```csharp
SubscriptionWorker<dynamic> GetSubscriptionWorker(
    string subscriptionName, string database = null);

SubscriptionWorker<dynamic> GetSubscriptionWorker(
    SubscriptionWorkerOptions options, string database = null);

SubscriptionWorker<T> GetSubscriptionWorker<T>(
    string subscriptionName, string database = null) where T : class;

SubscriptionWorker<T> GetSubscriptionWorker<T>(
    SubscriptionWorkerOptions options, string database = null) where T : class;
```

| Parameter | Type | Description |
| - | - | - |
| **subscriptionName** | `string` | The name of the subscription the worker connects to. |
| **options** | `SubscriptionWorkerOptions` | Options that affect how the worker interacts with the subscription. They do not change the subscription's own definition. |
| **database** | `string` | The database where the subscription task resides. If `null`, 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 delegate that processes each received batch.

```csharp
Task Run(Action<SubscriptionBatch<T>> processDocuments,
    CancellationToken ct = default(CancellationToken));

Task Run(Func<SubscriptionBatch<T>, Task> processDocuments,
    CancellationToken ct = default(CancellationToken));
```

| Parameter | Type | Description |
| - | - | - |
| **processDocuments** | `Action<SubscriptionBatch<T>>` | Delegate for synchronous batch processing. |
| **processDocuments** | `Func<SubscriptionBatch<T>, Task>` | Delegate for asynchronous batch processing. |
| **ct** | `CancellationToken` | A token used to halt the worker. |

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

### Classes

#### SubscriptionWorkerOptions

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

```csharp
public sealed class SubscriptionWorkerOptions
{
    public string SubscriptionName { get; }
    public int MaxDocsPerBatch { get; set; }
    public int SendBufferSizeInBytes { get; set; }
    public int ReceiveBufferSizeInBytes { get; set; }
    public bool IgnoreSubscriberErrors { get; set; }
    public bool CloseWhenNoDocsLeft { get; set; }
    public TimeSpan TimeToWaitBeforeConnectionRetry { get; set; }
    public TimeSpan ConnectionStreamTimeout { get; set; }
    public TimeSpan MaxErroneousPeriod { get; set; }
    public SubscriptionOpeningStrategy Strategy { get; set; }
}
```

| Property | Type | Description |
| - | - | - |
| **SubscriptionName** | `string` | The name of the subscription the worker connects to. |
| **MaxDocsPerBatch** | `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. |
| **SendBufferSizeInBytes** | `int` | The size of the TCP socket buffer the worker uses to send data. Default: 32,768 bytes (32 KiB). |
| **ReceiveBufferSizeInBytes** | `int` | The size of the TCP socket buffer the worker uses to receive data. Default: 32,768 bytes (32 KiB). |
| **IgnoreSubscriberErrors** | `bool` | Whether processing continues when your batch-handling code throws. `true` continues; `false` (default) aborts. |
| **CloseWhenNoDocsLeft** | `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. |
| **TimeToWaitBeforeConnectionRetry** | `TimeSpan` | The wait before each reconnection attempt.<br />Default: 5 seconds. |
| **ConnectionStreamTimeout** | `TimeSpan` | How long the worker waits for data from the server, or for a write to the server to complete, before treating the connection as broken.<br />Default: 30 seconds. Minimum: 15 seconds. |
| **MaxErroneousPeriod** | `TimeSpan` | 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. |
| **Strategy** | `SubscriptionOpeningStrategy` | How the server handles this worker's connection attempt. Default: `OpenIfFree`. |

#### SubscriptionOpeningStrategy

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

```csharp
public enum SubscriptionOpeningStrategy
{
    // Connect if no other worker is connected
    OpenIfFree,

    // Take over the connection
    TakeOver,

    // Wait for the currently connected worker to disconnect
    WaitForFree,

    // Connect concurrently
    Concurrent
}
```

#### SubscriptionBatch\<T>

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

| Property | Type | Description |
| - | - | - |
| **Items** | `List<SubscriptionBatch<T>.Item>` | The items in the batch. |
| **NumberOfItemsInBatch** | `int` | The number of items in the batch. |
| **LastSentChangeVectorInBatch** | `string` | The change vector of the last item in the batch.<br />The worker acknowledges the batch to the server with this value, so do not change it. |

| Method | Return value | Description |
| - | - | - |
| **OpenSession()** | `IDocumentSession` | 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.md#processing-projected-objects)). |
| **OpenSession(SessionOptions options)** | `IDocumentSession` | Opens a session with the given [session options](https://docs.ravendb.net/7.2/client-api/session/opening-a-session.md#session-options). |
| **OpenAsyncSession()** | `IAsyncDocumentSession` | The asynchronous version of `OpenSession()`. |
| **OpenAsyncSession(SessionOptions options)** | `IAsyncDocumentSession` | The asynchronous version of `OpenSession(SessionOptions options)`. |

> **Note**
>
> - Do not set `Database` or `RequestExecutor` in the session options:
>   the session always uses the subscription's database and the node the worker is connected to.
>   Setting either of them, or a transaction mode other than `SingleNode`, throws an exception.
>
> - 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)).
>
> - You can open only one session per batch. A second call to `OpenSession` or `OpenAsyncSession` throws an exception.

#### SubscriptionBatch\<T>.Item

A single item in a subscription batch.

```csharp
public struct Item
{
    public T Result { get; internal set; }
    public string ExceptionMessage { get; internal set; }
    public string Id { get; internal set; }
    public string ChangeVector { get; internal set; }
    public bool Projection { get; internal set; }
    public bool Revision { get; internal set; }
    public BlittableJsonReaderObject RawResult { get; internal set; }
    public BlittableJsonReaderObject RawMetadata { get; internal set; }
    public IMetadataDictionary Metadata { get; internal set; }
}
```

| Property | Type | Description |
| - | - | - |
| **Result** | `T` | The batch item. If `T` is `BlittableJsonReaderObject`, no deserialization takes place. |
| **ExceptionMessage** | `string` | The exception message thrown while processing the document on the server side. |
| **Id** | `string` | The document ID of the item's underlying document. |
| **ChangeVector** | `string` | The change vector of the item's underlying document. |
| **Projection** | `bool` | `true` when the item is a projection produced by the subscription query rather than a full document. |
| **Revision** | `bool` | `true` when the item is a document revision, for a subscription that streams revisions. |
| **RawResult** | `BlittableJsonReaderObject` | The item before deserialization to `T`. |
| **RawMetadata** | `BlittableJsonReaderObject` | The item's metadata, as a raw JSON object. |
| **Metadata** | `IMetadataDictionary` | 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 this struct only within the subscription's `Run` delegate. Using it outside that scope may
> cause unexpected behavior.

The worker returned by `GetSubscriptionWorker`.

**Methods**

| Method | Return type | Description |
| - | - | - |
| **Dispose()** | `void` | Aborts the worker, waiting for the task returned by `Run` to finish. |
| **DisposeAsync()** | `ValueTask` | The asynchronous version of `Dispose()`. |
| **Dispose(bool waitForSubscriptionTask)** | `void` | Aborts the worker, letting you choose whether to wait for the `Run` task. |
| **DisposeAsync(bool waitForSubscriptionTask)** | `ValueTask` | The asynchronous version of `Dispose(bool waitForSubscriptionTask)`. |
| **Run (overloads)** | `Task` | Starts the worker's batch processing. See [Run](#methods) above. |

**Events**

| Event | Type | Description |
| - | - | - |
| **AfterAcknowledgment** | `AfterAcknowledgmentAction` | Fires after the server acknowledges the progress of a processed batch. |
| **OnSubscriptionConnectionRetry** | `Action<Exception>` | Fires each time the worker is about to reconnect, after the wait set in `TimeToWaitBeforeConnectionRetry`.<br />Receives the exception that caused the reconnection. |
| **OnUnexpectedSubscriptionError** | `Action<Exception>` | Fires when the worker hits an error it does not recognize, before the worker waits to reconnect.<br />Receives the exception. |
| **OnEstablishedSubscriptionConnection** | `Action` | Fires each time the worker connects to the subscription, both the first time and after every reconnection. |
| **OnStateChanged** | `'Action&lt;''AbstractSubscriptionWorker&lt;''SubscriptionBatch&lt;T&gt;, T&gt;, SubscriptionWorkerStatus&gt;'` | Fires on every change of the worker's state.<br />Receives the worker and the worker's new status. |
| **OnDisposed** | `'Action&lt;''AbstractSubscriptionWorker&lt;''SubscriptionBatch&lt;T&gt;, T&gt;&gt;'` | Fires after the worker is disposed. |

> **Note**
>
> `AfterAcknowledgmentAction` is defined as:
>
> ```csharp
> public delegate Task AfterAcknowledgmentAction(SubscriptionBatch<T> batch);
> ```

**Properties**

| Property | Type | Description |
| - | - | - |
| **CurrentNodeTag** | `string` | The node tag of the RavenDB server currently handling the subscription. |
| **SubscriptionName** | `string` | The name of the subscription being processed. |
| **Status** | `SubscriptionWorkerStatus` | The worker's current status (see [Status and state changes](#status-and-state-changes)). |
| **WorkerId** | `string` | The worker ID. |

#### SubscriptionWorkerStatus

The worker's status, returned by the worker's `Status` property and passed to `OnStateChanged` handlers.
See [Status and state changes](#status-and-state-changes).

```csharp
public sealed class SubscriptionWorkerStatus
{
    public SubscriptionWorkerState State { get; }
    public Exception Exception { get; }
    public DateTime SinceUtc { get; }
    public DateTime? FailingSinceUtc { get; }
}
```

| Property | Type | Description |
| - | - | - |
| **State** | `SubscriptionWorkerState` | The worker's current state. |
| **Exception** | `Exception` | The failure that caused the `Retrying` or `Faulted` state, or `null` in other states.<br />If the worker fails repeatedly, this property holds the latest failure. |
| **SinceUtc** | `DateTime` | The time the worker entered the current state. |
| **FailingSinceUtc** | `DateTime?` | The time of the first failure since the worker's last successful connection, or `null` while the worker is connected. |

#### SubscriptionWorkerState

The stages of a worker's activity. See [Status and state changes](#status-and-state-changes).

```csharp
public enum SubscriptionWorkerState
{
    // Run has not been called yet
    NotStarted,
    // Connecting to the subscription, at startup or before a reconnection
    Connecting,
    // Connected and waiting for the next batch
    WaitingForDocuments,
    // Processing a batch, until the worker acknowledges the batch to the server
    Processing,
    // The connection failed, and the worker is waiting to reconnect
    Retrying,
    // Stopped without reconnecting, and the task returned by Run completed in error
    Faulted,
    // Disposed, or the cancellation token passed to Run was canceled
    Stopped
}
```
