Skip to main content

Consuming a data subscription

Creating a subscription worker​

Create a worker using the store's Subscriptions.GetSubscriptionWorker method, passing either the subscription name or a SubscriptionWorkerOptions object.

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

This constructs the worker but does not run it yet.

Running the worker​

To start processing the documents the server sends, call the worker's Run method, passing the logic that handles each batch:

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.

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.

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​

  • 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​

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 add another way a document can be reprocessed, by reassigning a dropped worker's documents to the other workers.

Worker strategies​

A worker is configured with a strategy, set in the SubscriptionWorkerOptions 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.

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​

Connection failures​

When an error interrupts the worker's communication with the server, the worker tries to reconnect (see 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).

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).
  • The worker uses the Concurrent strategy on a sharded database, which does not support concurrent subscriptions (see Unsupported features).
  • The subscription was disabled, or the worker's connection was dropped (see 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).
  • The worker runs with CloseWhenNoDocsLeft and no documents are left (see 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.

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.
var options = new SubscriptionWorkerOptions(subscriptionName);

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

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

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

Worker events​

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

// 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​

The Metadata property of each batch item holds the metadata of the item's document (see SubscriptionBatch<T>.Item), 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).

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.

  • When a subscription's query applies a projection, 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
See Reading a revision's metadata

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.

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.

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.

Open the session using batch.OpenSession or batch.OpenAsyncSession, not store.OpenSession or store.OpenAsyncSession.

// 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();
}
});

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.

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

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

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

Setting the metadata property​

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​

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.

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

// 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
}
}
}
});

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, a worker that reconnects after a failure does not take the connection back, but joins the waiting workers.

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:

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:

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​

Methods​

Create a subscription worker through store.Subscriptions.

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;

ParameterTypeDescription
subscriptionNamestringThe name of the subscription the worker connects to.
optionsSubscriptionWorkerOptionsOptions that affect how the worker interacts with the subscription. They do not change the subscription's own definition.
databasestringThe database where the subscription task resides. If null, the document store's default database is used.
Return value
SubscriptionWorkerThe created worker. It is idle until you call Run.

Classes​

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

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; }
}

PropertyTypeDescription
SubscriptionNamestringThe name of the subscription the worker connects to.
MaxDocsPerBatchintThe 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.
SendBufferSizeInBytesintThe size of the TCP socket buffer the worker uses to send data. Default: 32,768 bytes (32 KiB).
ReceiveBufferSizeInBytesintThe size of the TCP socket buffer the worker uses to receive data. Default: 32,768 bytes (32 KiB).
IgnoreSubscriberErrorsboolWhether processing continues when your batch-handling code throws. true continues; false (default) aborts.
CloseWhenNoDocsLeftboolWhether 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.
TimeToWaitBeforeConnectionRetryTimeSpanThe wait before each reconnection attempt.
Default: 5 seconds.
ConnectionStreamTimeoutTimeSpanHow long the worker waits for data from the server, or for a write to the server to complete, before treating the connection as broken.
Default: 30 seconds. Minimum: 15 seconds.
MaxErroneousPeriodTimeSpanHow 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.
StrategySubscriptionOpeningStrategyHow the server handles this worker's connection attempt. Default: OpenIfFree.

The batch passed to your Run delegate (see Running the worker).

PropertyTypeDescription
ItemsList<SubscriptionBatch<T>.Item>The items in the batch.
NumberOfItemsInBatchintThe number of items in the batch.
LastSentChangeVectorInBatchstringThe change vector of the last item in the batch.
The worker acknowledges the batch to the server with this value, so do not change it.
MethodReturn valueDescription
OpenSession()IDocumentSessionOpens a session that tracks the batch's documents and included documents.
Projected items and revisions are not tracked (see Processing projected objects).
OpenSession(SessionOptions options)IDocumentSessionOpens a session with the given session options.
OpenAsyncSession()IAsyncDocumentSessionThe asynchronous version of OpenSession().
OpenAsyncSession(SessionOptions options)IAsyncDocumentSessionThe asynchronous version of OpenSession(SessionOptions options).
  • 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).

  • You can open only one session per batch. A second call to OpenSession or OpenAsyncSession throws an exception.

The worker returned by GetSubscriptionWorker.

Methods

MethodReturn typeDescription
Dispose()voidAborts the worker, waiting for the task returned by Run to finish.
DisposeAsync()ValueTaskThe asynchronous version of Dispose().
Dispose(bool waitForSubscriptionTask)voidAborts the worker, letting you choose whether to wait for the Run task.
DisposeAsync(bool waitForSubscriptionTask)ValueTaskThe asynchronous version of Dispose(bool waitForSubscriptionTask).
Run (overloads)TaskStarts the worker's batch processing. See Run above.

Events

EventTypeDescription
AfterAcknowledgmentAfterAcknowledgmentActionFires after the server acknowledges the progress of a processed batch.
OnSubscriptionConnectionRetryAction<Exception>Fires each time the worker is about to reconnect, after the wait set in TimeToWaitBeforeConnectionRetry.
Receives the exception that caused the reconnection.
OnUnexpectedSubscriptionErrorAction<Exception>Fires when the worker hits an error it does not recognize, before the worker waits to reconnect.
Receives the exception.
OnEstablishedSubscriptionConnectionActionFires each time the worker connects to the subscription, both the first time and after every reconnection.
OnStateChangedAction<AbstractSubscriptionWorker<SubscriptionBatch<T>, T>, SubscriptionWorkerStatus>Fires on every change of the worker's state.
Receives the worker and the worker's new status.
OnDisposedAction<AbstractSubscriptionWorker<SubscriptionBatch<T>, T>>Fires after the worker is disposed.

AfterAcknowledgmentAction is defined as:

public delegate Task AfterAcknowledgmentAction(SubscriptionBatch<T> batch);

Properties

PropertyTypeDescription
CurrentNodeTagstringThe node tag of the RavenDB server currently handling the subscription.
SubscriptionNamestringThe name of the subscription being processed.
StatusSubscriptionWorkerStatusThe worker's current status (see Status and state changes).
WorkerIdstringThe worker ID.

The worker's status, returned by the worker's Status property and passed to OnStateChanged handlers. See Status and state changes.

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

PropertyTypeDescription
StateSubscriptionWorkerStateThe worker's current state.
ExceptionExceptionThe failure that caused the Retrying or Faulted state, or null in other states.
If the worker fails repeatedly, this property holds the latest failure.
SinceUtcDateTimeThe time the worker entered the current state.
FailingSinceUtcDateTime?The time of the first failure since the worker's last successful connection, or null while the worker is connected.

In this article