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

# Consuming a data subscription

> Client language: Node.js. 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), [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)
>     - [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 [subscription worker options](#classes) object.

```javascript
const subscriptionWorker = documentStore.subscriptions.getSubscriptionWorker(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, attach a handler to the worker's `batch` event.
Attaching the first `batch` listener starts the worker:

```javascript
subscriptionWorker.on("batch", (batch, callback) => {
    try {
        // your batch-processing logic here

        // Call callback() when done, so the worker acknowledges the batch
        callback();
    } catch (err) {
        callback(err);
    }
});
```

From this point on, the worker receives and processes document batches. Call `callback()` after
processing each batch so the server can keep track of the subscription's progress and provide the
next batch if available; call `callback(err)` to report a processing failure.

## 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.nodejs.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
[subscription worker options](#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 fails with 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 fails with a `SubscriptionInUseException`.
  - If the takeover fails, the incoming worker fails with 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.nodejs.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 subscription was disabled, or the worker's connection was dropped
  (see [Dropping connections](https://docs.ravendb.net/7.2/data-subscriptions/maintenance-operations.nodejs.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)).

To follow the worker's connection and reconnection attempts,
see [Worker status](#worker-status).

---

#### The worker's `error` event

- When the worker stops instead of reconnecting, the worker emits an `error` event.  
  The `error` event's handler receives an error that names the reason for stopping
  (e.g., a `SubscriptionDoesNotExistException` when the subscription was deleted).
- Always handle the worker's `error` event.

  > **Warning**
  >
  > If the worker stops on an error while its `error` event has no handler, Node.js will end your application's process,
  > and the worker's `end` event will not fire.

### Errors while processing a batch

When your batch-processing code throws an exception (or calls `callback(err)`), the worker's response
depends on the `ignoreSubscriberErrors` option:

- **`false`** (default)  
  Processing stops. The worker wraps the exception in a `SubscriberErrorException` and emits it
  through the `error` event, without acknowledging progress.
- **`true`**  
  The failed batch is acknowledged without a retry, and the worker continues with the next
  batches.

### Reconnection and timeouts

These worker options govern reconnection and connection timeouts:

- **`timeToWaitBeforeConnectionRetry`**  
  How long the worker waits before each reconnect attempt, in milliseconds.  
  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, in milliseconds.  
  Default: 5 minutes.
- **`connectionStreamTimeout`**  
  How long the worker's connection with the server may go without sending or receiving data
  before the worker treats the connection as broken and tries to reconnect, in milliseconds.  
  Default: 30 seconds. Cannot be set below 15 seconds.

## 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"`**  
  No handler was attached to the worker's `batch` event yet, so the worker has not started.
- **`"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 emitted the error through its `error` event.
- **`"Stopped"`**  
  The worker was disposed.

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

When the state is `"Retrying"` or `"Faulted"`, the `error` property of the `SubscriptionWorkerStatus` object holds the failure
that caused the state.  
If the worker fails repeatedly, the `error` 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),
attach a handler to the worker's `stateChanged` event.  
The event passes the worker's new status (a `SubscriptionWorkerStatus` object) and the worker to your handler.  
The worker calls your handler synchronously and does not continue until the handler returns, so avoid long-running work
in the handler.  
If the handler throws an error, the worker catches the error and continues.

```javascript
// failingSinceUtc is null while the worker is connected, and is set while the worker is failing
const status = subscriptionWorker.status;
if (status.failingSinceUtc) {
    console.log("Failing since " + status.failingSinceUtc + ": " + status.error?.message);
}

// Write each change of the worker's state to the console
subscriptionWorker.on("stateChanged", (newStatus, worker) => {
    console.log("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**
>
> Attach a handler to a worker event using the worker's `on` method, and detach the handler using the worker's `off` method.  
> To detach a handler later, keep a reference to the handler when you attach it (e.g., use a named function rather than
> an inline arrow function), since `off` must receive the same handler.

To react to the worker's connections, failures, acknowledged batches, and end, attach handlers to these worker events:

- **`onEstablishedSubscriptionConnection`**  
  Fires each time the worker connects to the subscription, both the first time and after every reconnection.
- **`unexpectedSubscriptionError`**  
  Fires when the worker hits an error it does not recognize (e.g., a dropped network connection),
  before the worker waits to reconnect.
- **`connectionRetry`**  
  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.
- **`end`**  
  Fires when the worker stops processing batches.  
  If the worker stopped on an error, `end` fires after the `error` event.

When the worker stops instead of reconnecting, neither `unexpectedSubscriptionError` nor `connectionRetry` fires.

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

```javascript
// Fires on the first connection and after every reconnection
subscriptionWorker.on("onEstablishedSubscriptionConnection", () => {
    console.log("Connected to the subscription");
});

// Fires for an error the worker does not recognize, before the wait
subscriptionWorker.on("unexpectedSubscriptionError", error => {
    console.log("Unexpected subscription error: " + error.message);
});

// Fires before each reconnection attempt, after the wait
subscriptionWorker.on("connectionRetry", error => {
    console.log("Reconnecting to the subscription after: " + error.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.nodejs.md)
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).

```javascript
subscriptionWorker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            // Read a metadata property you set yourself
            // (the value is null if the metadata does not hold the property)
            const traceId = item.metadata["trace.id"];
            if (traceId) {
                // your processing logic here
            }
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

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.nodejs.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.nodejs.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.nodejs.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 emit,
recreating the worker to resume processing when the error is recoverable.

```javascript
// Create the subscription task on the server:
const subscriptionName = await documentStore.subscriptions.create({
    name: "ProcessOrdersWithLowFreight",
    query: "from Orders where Freight < 0.5"
});

// Create the subscription worker that will consume the documents:
await setupReconnectingWorker(subscriptionName);

async function setupReconnectingWorker(subscriptionName) {
    let subscriptionWorker;

    function closeWorker(worker) {
        worker.dispose();
    }

    function reconnect() {
        if (subscriptionWorker) {
            closeWorker(subscriptionWorker);
        }

        // Configure the worker:
        const subscriptionWorkerOptions = {
            subscriptionName: subscriptionName,
            // Allow a downtime of up to 2 hours
            maxErroneousPeriod: 2 * 3600 * 1000,
            // Wait 2 minutes before reconnecting
            timeToWaitBeforeConnectionRetry: 2 * 60 * 1000
        };

        subscriptionWorker = documentStore.subscriptions.getSubscriptionWorker(subscriptionWorkerOptions);

        // Subscribe to connection retry events, and log any exceptions
        subscriptionWorker.on("connectionRetry", error => {
            console.error("Error during subscription processing: " + subscriptionName, error);
        });

        // Run the worker:
        subscriptionWorker.on("batch", (batch, callback) => {
            try {
                for (const item of batch.items) {
                    const orderDocument = item.result;

                    // Forcefully stop processing if the order's Company is "companies/46-A",
                    // and report an error to let external logic handle the specific case
                    if (orderDocument.Company && orderDocument.Company === "companies/46-A") {
                        // The error reported here will be wrapped by `SubscriberErrorException`
                        const error = new Error("Company ID can't be 'companies/46-A', please fix");
                        error.name = "UnsupportedCompanyError";
                        callback(error);
                        return;
                    }

                    // Process the order document - provide your own logic
                    processOrder(orderDocument);
                }
                // Call 'callback' once you're done so the worker acknowledges the batch
                callback();
            } catch (err) {
                callback(err);
            }
        });

        // Handle errors:
        subscriptionWorker.on("error", error => {
            console.error("Failure in subscription: " + subscriptionName, error);

            // The following errors are not recoverable
            if (error.name === "DatabaseDoesNotExistException" ||
                error.name === "SubscriptionDoesNotExistException" ||
                error.name === "SubscriptionInvalidStateException" ||
                error.name === "AuthorizationException") {
                throw error;
            }

            if (error.name === "SubscriptionClosedException") {
                // Subscription probably closed explicitly by admin
                return closeWorker(subscriptionWorker);
            }

            // For UnsupportedCompanyError, stop and rethrow;
            // for any other error the batch handler reported, try reconnecting
            if (error.name === "SubscriberErrorException" &&
                error.cause && error.cause.name === "UnsupportedCompanyError") {
                throw error;
            }

            // Otherwise, try reconnecting
            setTimeout(reconnect, 1000);
        });
    }

    reconnect();
}
```

### Example: Setting the batch size

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

```javascript
const workerOptions = {
    subscriptionName: subscriptionName,
    maxDocsPerBatch: 20
};

const worker = documentStore.subscriptions.getSubscriptionWorker(workerOptions);

worker.on("batch", (batch, callback) => {
    try {
        // your custom logic
        callback();
    } catch (err) {
        callback(err);
    }
});
```

### 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`, not `documentStore.openSession`.

```javascript
// Create the subscription task on the server:
const subscriptionName = await documentStore.subscriptions.create({
    name: "ProcessOrdersThatWereNotShipped",
    query: "from Orders as o where o.ShippedAt = null"
});

// Create the subscription worker that will consume the documents:
const worker = documentStore.subscriptions.getSubscriptionWorker({ subscriptionName });

worker.on("batch", async (batch, callback) => {
    try {
        // Open a session using 'batch.openSession'
        const session = batch.openSession();

        for (const item of batch.items) {
            const orderDocument = item.result;

            transferOrderToShipmentCompany(orderDocument); // call your custom method
            orderDocument.ShippedAt = new Date();          // update the document field
        }

        // Save the updated Order documents
        await session.saveChanges();
        callback();
    } catch (err) {
        callback(err);
    }
});
```

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

```javascript
// Create the subscription task on the server:
const subscriptionName = await documentStore.subscriptions.create({
    name: "ProcessDynamicFields",
    query: `from Orders as o
            select {
                dynamicField: "Company: " + o.Company + " Employee: " + o.Employee
            }`
});

// Create the subscription worker that will consume the documents:
const worker = documentStore.subscriptions.getSubscriptionWorker({ subscriptionName });

worker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            // Access the dynamic field in the document
            const field = item.result.dynamicField;

            processItem(field); // call your custom method
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

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

```javascript
const session = documentStore.openSession();
const order = await session.load("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
await session.saveChanges();
```

#### Reading the metadata property in the worker

```javascript
const worker = documentStore.subscriptions.getSubscriptionWorker({ subscriptionName });

worker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            // The value is null for orders whose metadata does not hold 'trace.id'
            const traceId = item.metadata["trace.id"];
            if (traceId) {
                console.log(`Order ${item.id} has the trace ID ${traceId}`);
            }
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

### 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 emits a `SubscriptionClosedException` when
it finishes.

```javascript
// Create the subscription task on the server:
const 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`;

const subscriptionName = await documentStore.subscriptions.create({ query });

// Create the subscription worker that will consume the documents:
const workerOptions = {
    subscriptionName: subscriptionName,
    // Stop when there are no more documents left to send,
    // emitting a SubscriptionClosedException when it finishes
    closeWhenNoDocsLeft: true
};

const highValueOrdersWorker = documentStore.subscriptions.getSubscriptionWorker(workerOptions);

highValueOrdersWorker.on("batch", (batch, callback) => {
    try {
        for (const item of batch.items) {
            sendThankYouNoteToCompany(item.result); // call your custom method
        }
        callback();
    } catch (err) {
        callback(err);
    }
});

highValueOrdersWorker.on("error", err => {
    if (err.name === "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.

```javascript
// Create the subscription task on the server:
const subscriptionName = await documentStore.subscriptions.create({
    name: "ProcessIncludedDocuments",
    query: "from Orders include Lines[].Product"
});

// Create the subscription worker that will consume the documents:
const worker = documentStore.subscriptions.getSubscriptionWorker({ subscriptionName });

worker.on("batch", async (batch, callback) => {
    try {
        // Open a session using 'batch.openSession' to access the Product documents
        const session = batch.openSession();

        for (const item of batch.items) {
            const orderDocument = item.result;

            for (const orderLine of orderDocument.Lines) {
                // Calling 'load' will not generate a request to the server,
                // because orderLine.Product was included in the batch
                const product = await session.load(orderLine.Product);

                processOrderAndProduct(orderDocument, product); // call your custom method
            }
        }
        callback();
    } catch (err) {
        callback(err);
    }
});
```

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

```javascript
const worker = documentStore.subscriptions.getSubscriptionWorker({
    subscriptionName,
    // "WaitForFree": wait and take over if the connected worker fails
    strategy: "WaitForFree",
    documentType: Order
});
```

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

```javascript
const primaryWorker = documentStore.subscriptions.getSubscriptionWorker({
    subscriptionName,
    strategy: "TakeOver",
    documentType: Order
});

primaryWorker.on("batch", (batch, callback) => {
    // your logic
    callback();
});

primaryWorker.on("error", err => {
    // retry
});
```

The secondary worker:

```javascript
const secondaryWorker = documentStore.subscriptions.getSubscriptionWorker({
    subscriptionName,
    strategy: "WaitForFree",
    documentType: Order
});

secondaryWorker.on("batch", (batch, callback) => {
    // your logic
    callback();
});

secondaryWorker.on("error", err => {
    // retry
});
```

## Syntax {#syntax}

### Methods

Create a subscription worker through `documentStore.subscriptions`.

```javascript
// Overloads:
getSubscriptionWorker(subscriptionName);
getSubscriptionWorker(subscriptionName, database);
getSubscriptionWorker(options);
getSubscriptionWorker(options, database);
```

| Parameter | Type | Description |
| - | - | - |
| **subscriptionName** | `string` | The name of the subscription the worker connects to. |
| **options** | `object` | Options that affect how the worker interacts with the subscription. They do not change the subscription's own definition. See the [Classes](#classes) below. |
| **database** | `string` | The database where the subscription task resides. If not specified, the document store's default database is used. |

| Return value | |
| - | - |
| `SubscriptionWorker` | The created worker. It starts processing once you attach a handler to its `batch` event. |

### Classes

#### SubscriptionWorkerOptions

When you create a worker with options, the only required property is `subscriptionName`; the rest
fall back to their defaults.

```javascript
// The subscription worker options object:
{
    subscriptionName;
    documentType;
    ignoreSubscriberErrors;
    closeWhenNoDocsLeft;
    maxDocsPerBatch;
    timeToWaitBeforeConnectionRetry;
    connectionStreamTimeout;
    maxErroneousPeriod;
    strategy;
}
```

| Property | Type | Description |
| - | - | - |
| **subscriptionName** | `string` | The name of the subscription the worker connects to. |
| **documentType** | `object` | The document class of the subscription's documents. |
| **ignoreSubscriberErrors** | `boolean` | Whether processing continues when your batch-handling code throws. `true` continues; `false` (default) aborts. |
| **closeWhenNoDocsLeft** | `boolean` | Whether the connection closes when no new documents remain. `true` processes all available documents and then emits a `SubscriptionClosedException` (useful for one-time processing); `false` (default) keeps the worker waiting for new documents. |
| **maxDocsPerBatch** | `number` | 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. |
| **timeToWaitBeforeConnectionRetry** | `number` | The wait before each reconnection attempt, in milliseconds.<br />Default: 5 seconds. |
| **connectionStreamTimeout** | `number` | How long the connection with the server may go without sending or receiving data before the worker treats the connection as broken, in milliseconds.<br />Default: 30 seconds. Minimum: 15 seconds. |
| **maxErroneousPeriod** | `number` | How long the worker may keep failing to reconnect, counted from the first failure since its last successful connection, before the worker stops retrying, in milliseconds.<br />Default: 5 minutes. |
| **strategy** | `string` | How the server handles this worker's connection attempt. Default: `"OpenIfFree"`. |

#### SubscriptionOpeningStrategy

The strategy that decides whether a worker may connect to a subscription, set as a string on the
`strategy` option. See [Worker strategies](#worker-strategies).

```javascript
// Available values:
"OpenIfFree"   // Connect if no other worker is connected
"TakeOver"     // Take over the connection
"WaitForFree"  // Wait for the currently connected worker to disconnect
"Concurrent"   // Connect concurrently
```

#### SubscriptionBatch

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

| Property | Type | Description |
| - | - | - |
| **items** | `Item[]` | The 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 |
| - | - | - |
| **getNumberOfItemsInBatch()** | `number` | The number of items in the batch. |
| **getNumberOfIncludes()** | `number` | `1` if the server sent included documents with the batch, `0` if it did not. |
| **openSession()** | `object` | 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.nodejs.md#processing-projected-objects)). |
| **openSession(options)** | `object` | Opens a session with the given [session options](https://docs.ravendb.net/7.2/client-api/session/opening-a-session.nodejs.md#session-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` throws an exception.

#### Item

A single item in a subscription batch.

```javascript
class Item
{
    result;
    exceptionMessage;
    id;
    changeVector;
    projection;
    revision;
    rawResult;
    rawMetadata;
    metadata;
}
```

| Property | Type | Description |
| - | - | - |
| **result** | `object` | The batch item. |
| **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** | `boolean` | `true` when the item is a projection produced by the subscription query rather than a full document. |
| **revision** | `boolean` | `true` when the item is a document revision, for a subscription that streams revisions. |
| **rawResult** | `object` | The item before deserialization. |
| **rawMetadata** | `object` | The item's metadata, as a raw JSON object. |
| **metadata** | `object` | 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). |

The worker returned by `getSubscriptionWorker`.

**Methods**

| Method | Return type | Description |
| - | - | - |
| **dispose()** | `void` | Aborts the worker. |
| **on(event, handler)** | `object` | Attaches an event listener. |
| **off(event, handler)** | `object` | Detaches an event listener. |
| **getWorkerId()** | `string` | The worker ID. |

**Events**

| Event | Listener signature | Description |
| - | - | - |
| **"batch"** | `(batch, callback) => void` | Fires when a batch of documents arrives from the server. Call `callback()` when done so the worker acknowledges the batch and the server sends the next one. |
| **"onEstablishedSubscriptionConnection"** | `(worker) => void` | Fires each time the worker connects to the subscription, both the first time and after every reconnection. |
| **"stateChanged"** | `(status, worker) => void` | Fires on every change of the worker's state.<br />Receives the worker's new status and the worker. |
| **"afterAcknowledgment"** | `(batch) => void` | Fires after the server acknowledges the progress of a processed batch. |
| **"connectionRetry"** | `(error) => void` | Fires each time the worker is about to reconnect, after the wait set in `timeToWaitBeforeConnectionRetry`. |
| **"unexpectedSubscriptionError"** | `(error) => void` | Fires when the worker hits an error it does not recognize, before the worker waits to reconnect. |
| **"error"** | `(error) => void` | Fires on subscription errors. |
| **"end"** | `() => void` | Fires when the worker stops processing batches.<br />If the worker stopped on an error, `end` fires after the `error` event. |

**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)). |

#### SubscriptionWorkerStatus

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

```javascript
// The worker status object:
{
    state;
    error;
    sinceUtc;
    failingSinceUtc;
}
```

| Property | Type | Description |
| - | - | - |
| **state** | `SubscriptionWorkerState` | The worker's current state. |
| **error** | `Error` | 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** | `Date` | The time the worker entered the current state. |
| **failingSinceUtc** | `Date` | 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, as strings. See [Status and state changes](#status-and-state-changes).

```javascript
// Available values:
"NotStarted"           // No handler was attached to the batch event yet
"Connecting"           // Connecting to the subscription, at startup or before a reconnection
"WaitingForDocuments"  // Connected and waiting for the next batch
"Processing"           // Processing a batch, until the worker acknowledges the batch to the server
"Retrying"             // The connection failed, and the worker is waiting to reconnect
"Faulted"              // Stopped without reconnecting, and emitted the error through the error event
"Stopped"              // The worker was disposed
```
