---
title: "Queue Sink: Apache Kafka"
description: "Consume messages from Kafka topics and write them into RavenDB documents using queue sink tasks with JavaScript processing scripts."
url: "https://docs.ravendb.net/7.2/server/ongoing-tasks/queue-sink/kafka-queue-sink"
version: "7.2"
---

# Queue Sink: Apache Kafka

> 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**
>
> - **Apache Kafka** is a distributed, high-performance, transactional messaging
>   platform, that remains performant as the number of messages it needs to process
>   increases and the number of events it needs to stream climbs to the big-data zone.
>
> - RavenDB can harness the advantages presented by message brokers like Kafka
>   both as a producer (by [running ETL tasks](https://docs.ravendb.net/7.2/server/ongoing-tasks/etl/queue-etl/kafka.md))
>   and as a **consumer** (using a sink task to consume enqueued messages).
>
> - To use RavenDB as a consumer, define an ongoing Sink task that will read batches
>   of enqueued JSON formatted messages from Kafka topics, construct documents using
>   user-defined scripts, and store the documents in RavenDB collections.
>
> - In this article:
>   - [The Queue Sink Task](#the-queue-sink-task)
>     - [Connecting a Kafka broker](#connecting-a-kafka-broker)
>     - [Retrieving enqueued messages from selected Kafka topics](#retrieving-enqueued-messages-from-selected-kafka-topics)
>     - [Running user-defined scripts](#running-user-defined-scripts)
>     - [Storing documents in RavenDB collections](#storing-documents-in-ravendb-collections)
>   - [Client API](#client-api)
>     - [Adding a Kafka connection string](#adding-a-kafka-connection-string)
>     - [Adding a Kafka sink task](#adding-a-kafka-sink-task)
>   - [Configuration Options](#configuration-options)
>   - [Syntax](#syntax)
>     - [Classes](#classes)

## The Queue Sink Task {#the-queue-sink-task}

### Connecting a Kafka broker

Users of RavenDB 6.0 and on can create an ongoing Sink task that connects
a Kafka broker, retrieves enqueued messages from selected Kafka topics,
runs a user-defined script to manipulate data and construct documents, and
potentially stores the created documents in RavenDB collections.

In the message broker architecture, RavenDB sinks take the role of data consumers.  
A sink would connect a Kafka broker using a connection string, and retrieve messages
from the broker's Topics.

Read [below](#adding-a-kafka-connection-string)
about adding a connection string via API.  
Read [here](https://docs.ravendb.net/7.2/studio/database/tasks/ongoing-tasks/kafka-queue-sink.md#define-a-kafka-sink-task)
about adding a connection string using Studio.

> **Warning**
>
> Like all ongoing tasks, a sink task is operated by a
> [responsible node](https://docs.ravendb.net/7.2/server/clustering/distribution/highly-available-tasks.md#responsible-node).  
> When the responsibility for the task is moved from one node to another,
> e.g. from node `A` to node `B` as a result of node `A` down time:
>
> - The consumer task will maintain the same consumer group id it had on the original node.
> - Kafka brokers may **cease serving the sink task for some time** as the Kafka consumer
>   group rebalances (adapting to the leaving of one node and the joining of another, among
>   other changes).

### Retrieving enqueued messages from selected Kafka topics

> **Note**
>
> While a queue sink task is running, it prevents the host database from being unloaded due to idle operations.  
> This ensures that message consumption from Kafka topics continues uninterrupted, even if the database would otherwise go idle.

When a message is sent to a Kafka broker by a producer, it is pushed to
the tail of a topic. As preceding messages are pulled, the message advances
up the queue until it reaches its head and can be consumed by RavenDB's sink.

### Running user-defined scripts

A sink task's script is a JavaScript segment. Its basic role is to retrieve
selected Kafka messages or message properties, and construct documents that
will then be stored in RavenDB.

The script can store the whole message as a document, as in this segment:

```javascript
// Add the document a metadata `@collection` property to keep it in
// this collection, or do not set it to store the document in @empty).
this['@metadata']['@collection'] = 'Orders';
// Store the message as is, using its Id property as its RavenDB Id as well.
put(this.Id.toString(), this)
```

The script can also retrieve selected information from the read message and
construct a new document that does not resemble the original message.  
Scripts often apply two sections: a section that creates a JSON object
that defines the document's structure and contents, and a second section
that stores the document.

E.g., for Kafka messages of this format:

```json
{
   "Id" : 13,
   "FirstName" : "John",
   "LastName" : "Doe"
}
```

We can create this script:

```javascript
var item = {
    Id : this.Id,
    FirstName : this.FirstName,
    LastName : this.LastName,
    FullName : this.FirstName + ' ' + this.LastName,
    "@metadata" : {
        "@collection" : "Users"
    }
};

// Use .toString() to pass the Id as a string even if Kafka provides it as a number
put(this.Id.toString(), item)
```

The script can also apply various other JavaScript commands, including
`load` to load a RavenDB document (e.g. to construct a document that
includes data from the retrieved message and complementing data from
existing RavenDB documents), `del` to remove existing RavenDB documents,
and [many others](https://docs.ravendb.net/7.2/server/kb/javascript-engine.md#predefined-javascript-functions).

### Storing documents in RavenDB collections

The sink task consumes batches of queued messages and stores them in RavenDB
in a transactional manner, processing either the entire batch or none of it.

> **Note:** Exceptions to this rule {#exceptions-to-this-rule}
>
> Some script processing errors are allowed; when such an error occurs RavenDB
> will skip the affected message, record the event in the logs, and alert the
> user in Studio, but **continue processing the batch**.

Once a batch is consumed, the task confirms it by calling `kafkaConsumer.Commit()`.

Note that the number of documents included in a batch is
[configurable](#configuration-options).

> **Warning:** Take care of duplicates {#take-care-of-duplicates}
>
> Producers may enqueue
> [multiple instances](https://docs.ravendb.net/7.2/server/ongoing-tasks/etl/queue-etl/overview.md#idempotence-and-message-duplication)
> of the same document.  
> If processing each message only once is important to the consumer,
> it is **the consumer's responsibility** to verify the uniqueness of
> each consumed message.
>
> Note that as long as the **Id** property of Kafka messages is preserved
> (so duplicate messages share an Id), the script's `put(ID, { ... })`
> command will overwrite a previous document with the same Id and only
> one copy of it will remain.

## Client API {#client-api}

### Adding a Kafka connection string

- A Kafka queue sink task uses a **Kafka connection string** to connect to its source Kafka cluster.  
  The connection string stores one or more Kafka bootstrap server addresses and, when needed, additional Kafka client settings such as authentication and TLS options.

- The sink task does not store these connection details directly.  
  Instead, its configuration references the connection string by name through the `ConnectionStringName` property.

- A Kafka connection string can be created in any of these ways:
  - **From the Client API**:
    [per-database](https://docs.ravendb.net/7.2/integrations/connection-strings/per-database/add-or-update-connection-string.md#add-a-connection-string---from-the-client-api)
    or [server-wide](https://docs.ravendb.net/7.2/integrations/connection-strings/server-wide/add-or-update-connection-string.md#add-a-connection-string---from-the-client-api).
  - **From Studio**:
    [per-database](https://docs.ravendb.net/7.2/integrations/connection-strings/per-database/add-or-update-connection-string.md#add-a-connection-string---from-the-studio),
    [server-wide](https://docs.ravendb.net/7.2/integrations/connection-strings/server-wide/add-or-update-connection-string.md#add-a-connection-string---from-the-studio),
    or while creating a [Kafka queue sink task](https://docs.ravendb.net/7.2/studio/database/tasks/ongoing-tasks/kafka-queue-sink.md#define-a-kafka-sink-task).

- The example below adds a **per-database** Kafka connection string from the **Client API**.  
  The connection string is stored in the current database record and can be used by tasks in that database.

#### Sync

```csharp
// Define a Kafka connection string
// =================================
var kafkaConnectionString = new QueueConnectionString
{
    // The name used by the Kafka queue sink task configuration
    Name = "kafka-connection-string-name",

    // Set the queue broker type to Kafka
    BrokerType = QueueBrokerType.Kafka,

    // Configure the Kafka broker connection
    KafkaConnectionSettings = new KafkaConnectionSettings
    {
        // A comma-separated list of Kafka bootstrap servers
        BootstrapServers = "localhost:9092"
    }
};

// Deploy (send) the connection string to the server
// ==================================================
var putConnectionStringOp =
    new PutConnectionStringOperation<QueueConnectionString>(kafkaConnectionString);

PutConnectionStringResult connectionStringResult =
    store.Maintenance.Send(putConnectionStringOp);
```

#### Async

```csharp
// Define a Kafka connection string
// =================================
var kafkaConnectionString = new QueueConnectionString
{
    // The name used by the Kafka queue sink task configuration
    Name = "kafka-connection-string-name",

    // Set the queue broker type to Kafka
    BrokerType = QueueBrokerType.Kafka,

    // Configure the Kafka broker connection
    KafkaConnectionSettings = new KafkaConnectionSettings
    {
        // A comma-separated list of Kafka bootstrap servers
        BootstrapServers = "localhost:9092"
    }
};

// Deploy (send) the connection string to the server
// ==================================================
var putConnectionStringOp =
    new PutConnectionStringOperation<QueueConnectionString>(kafkaConnectionString);

PutConnectionStringResult connectionStringResult =
    await store.Maintenance.SendAsync(putConnectionStringOp);
```

#### Secure Kafka clusters

For a secure Kafka cluster, define the relevant Kafka client configuration keys in the `ConnectionOptions` dictionary.  
For example, use `security.protocol`, `sasl.mechanism`, `sasl.username`, and `sasl.password` to configure SASL authentication over SSL/TLS.

If your RavenDB cluster is secured and Kafka should authenticate RavenDB by certificate,  
set `UseRavenCertificate` to `true` on `KafkaConnectionSettings`.

##### Sync

```csharp
// Define a Kafka connection string for a secure Kafka cluster
// ===========================================================
var kafkaConnectionString = new QueueConnectionString
{
    // The name used by the Kafka queue sink task configuration
    Name = "secure-kafka-connection-string-name",

    // Set the queue broker type to Kafka
    BrokerType = QueueBrokerType.Kafka,

    // Configure the Kafka broker connection
    KafkaConnectionSettings = new KafkaConnectionSettings
    {
        BootstrapServers = "broker.example.com:9092",

        ConnectionOptions = new Dictionary<string, string>
        {
            // Transport protocol. SASL_SSL combines SASL auth with SSL/TLS encryption.
            // Other values: PLAINTEXT, SSL (mTLS only), SASL_PLAINTEXT.
            { "security.protocol", "SASL_SSL" },

            // SASL mechanism. PLAIN sends credentials as cleartext (safe only over TLS).
            // Other common values: SCRAM-SHA-256, SCRAM-SHA-512.
            { "sasl.mechanism", "PLAIN" },

            // Credentials issued by the Kafka cluster admin.
            { "sasl.username", "<your-username>" },
            { "sasl.password", "<your-password>" }
        }
    }
};

// Deploy (send) the connection string to the server
// ==================================================
var putConnectionStringOp =
    new PutConnectionStringOperation<QueueConnectionString>(kafkaConnectionString);

PutConnectionStringResult connectionStringResult =
    store.Maintenance.Send(putConnectionStringOp);
```

##### Async

```csharp
// Define a Kafka connection string for a secure Kafka cluster
// ===========================================================
var kafkaConnectionString = new QueueConnectionString
{
    // The name used by the Kafka queue sink task configuration
    Name = "secure-kafka-connection-string-name",

    // Set the queue broker type to Kafka
    BrokerType = QueueBrokerType.Kafka,

    // Configure the Kafka broker connection
    KafkaConnectionSettings = new KafkaConnectionSettings
    {
        BootstrapServers = "broker.example.com:9092",

        ConnectionOptions = new Dictionary<string, string>
        {
            // Transport protocol. SASL_SSL combines SASL auth with SSL/TLS encryption.
            // Other values: PLAINTEXT, SSL (mTLS only), SASL_PLAINTEXT.
            { "security.protocol", "SASL_SSL" },

            // SASL mechanism. PLAIN sends credentials as cleartext (safe only over TLS).
            // Other common values: SCRAM-SHA-256, SCRAM-SHA-512.
            { "sasl.mechanism", "PLAIN" },

            // Credentials issued by the Kafka cluster admin.
            { "sasl.username", "<your-username>" },
            { "sasl.password", "<your-password>" }
        }
    }
};

// Deploy (send) the connection string to the server
// ==================================================
var putConnectionStringOp =
    new PutConnectionStringOperation<QueueConnectionString>(kafkaConnectionString);

PutConnectionStringResult connectionStringResult =
    await store.Maintenance.SendAsync(putConnectionStringOp);
```

#### Syntax

`QueueConnectionString`:

| Property | Type | Description |
| - | - | - |
| **Name** | `string` | The connection string name. Use this value in the sink task's `ConnectionStringName` property. |
| **BrokerType** | `QueueBrokerType` | Set to `QueueBrokerType.Kafka` for a Kafka connection string. |
| **KafkaConnectionSettings** | `KafkaConnectionSettings` | The Kafka-specific connection settings. |

`KafkaConnectionSettings`:

| Property | Type | Description |
| - | - | - |
| **BootstrapServers** | `string` | A comma-separated list of Kafka bootstrap servers, in `host:port` format. |
| **ConnectionOptions** | `Dictionary<string, string>` | Optional Kafka client configuration keys used by the Kafka connection. |
| **UseRavenCertificate** | `bool` | Set to `true` to use RavenDB's cluster-wide certificate for SSL/TLS client authentication. |

---

### Adding a Kafka sink task

To define the sink task, prepare a `QueueSinkConfiguration` object and pass it to
`AddQueueSinkOperation`.  
The configuration needs to name the connection string to use, set the broker type to Kafka,
and hold one or more `QueueSinkScript` objects.

- Each script lists the Kafka topics to consume from in its `Queues` property, where each
  entry is a topic name.
- Each script's `Script` property holds the JavaScript that turns the consumed messages into
  RavenDB documents.

#### Example: Adding a Kafka sink task

```csharp
// Add Kafka connection string
var res = store.Maintenance.Send(
    new PutConnectionStringOperation<QueueConnectionString>(
        new QueueConnectionString
        {
            Name = "KafkaConStr",
            BrokerType = QueueBrokerType.Kafka,
            KafkaConnectionSettings = new KafkaConnectionSettings()
                    { BootstrapServers = "localhost:9092" }
        }));

// Define a Sink script
QueueSinkScript queueSinkScript = new QueueSinkScript
{
    // Script name
    Name = "orders",
    // A list of Kafka topics to consume from
    Queues = new List<string>() { "orders" },
    // Apply this script
    Script = @"this['@metadata']['@collection'] = 'Orders';
               put(this.Id.toString(), this)"
};

// Define a Kafka sink task configuration
var config = new QueueSinkConfiguration()
{
    // Sink name
    Name = "KafkaSinkTaskName",
    // The connection string to connect the broker with
    ConnectionStringName = "KafkaConStr",
    // What queue broker is this task using
    BrokerType = QueueBrokerType.Kafka,
    // The list of scripts to run
    Scripts = { queueSinkScript }
};

AddQueueSinkOperationResult addQueueSinkOperationResult =
    store.Maintenance.Send(new AddQueueSinkOperation<QueueConnectionString>(config));
```

For the `QueueSinkConfiguration` and `QueueSinkScript` property reference, see the
[Sink task](#sink-task)
classes in the Syntax section.

## Configuration Options {#configuration-options}

Use these configuration options to gain more control over queue sink tasks.

- [QueueSink.MaxBatchSize](https://docs.ravendb.net/7.2/server/configuration/queue-sink-configuration.md#queuesinkmaxbatchsize)  
  The maximum number of pulled messages consumed in a single batch.
- [QueueSink.MaxFallbackTimeInSec](https://docs.ravendb.net/7.2/server/configuration/queue-sink-configuration.md#queuesinkmaxfallbacktimeinsec)  
  The maximum number of seconds the Queue Sink process will be in a fallback
  mode (i.e. suspending the process) after a connection failure.

## Syntax {#syntax}

### Classes

#### Connection string

##### QueueConnectionString

**The connection string a sink task uses to reach a Kafka broker.**

```csharp
class QueueConnectionString
{
    string Name
    QueueBrokerType BrokerType
    KafkaConnectionSettings KafkaConnectionSettings
}
```

| Property | Type | Description |
| - | - | - |
| **Name** | `string` | The connection string name |
| **BrokerType** | `QueueBrokerType` | Set to `QueueBrokerType.Kafka` for a Kafka connection string |
| **KafkaConnectionSettings** | `KafkaConnectionSettings` | The broker's bootstrap servers and connection options |

`QueueConnectionString` is shared by all queue brokers, so it also defines settings for the other
broker types (`RabbitMqConnectionSettings`, `AzureQueueStorageConnectionSettings`,
`AmazonSqsConnectionSettings`, `AzureServiceBusConnectionSettings`).  
Set only the one matching `BrokerType`.

##### KafkaConnectionSettings

**The connection details for a Kafka broker.**

```csharp
class KafkaConnectionSettings
{
    string BootstrapServers
    Dictionary<string, string> ConnectionOptions
    bool UseRavenCertificate
}
```

| Property | Type | Description |
| - | - | - |
| **BootstrapServers** | `string` | A comma-separated list of the broker's bootstrap servers, in `host:port` form |
| **ConnectionOptions** | `Dictionary<string, string>` | Additional Kafka client configuration options, as key-value pairs |
| **UseRavenCertificate** | `bool` | Whether to authenticate the connection with RavenDB's own certificate |

#### Sink task

##### QueueSinkConfiguration

**The configuration of a Kafka sink task.**

```csharp
class QueueSinkConfiguration
{
    string Name
    string ConnectionStringName
    QueueBrokerType BrokerType
    List<QueueSinkScript> Scripts
    bool Disabled
    string MentorNode
    bool PinToMentorNode
    long TaskId
}
```

| Property | Type | Description |
| - | - | - |
| **Name** | `string` | The sink task name |
| **ConnectionStringName** | `string` | The name of the Kafka connection string the task uses |
| **BrokerType** | `QueueBrokerType` | Set to `QueueBrokerType.Kafka` (must match the connection string's broker type) |
| **Scripts** | `List<QueueSinkScript>` | The scripts the task runs |
| **Disabled** | `bool` | Whether the task is created in a disabled state |
| **MentorNode** | `string` | The preferred responsible node for the task, if any |
| **PinToMentorNode** | `bool` | Whether to pin the task to its mentor node |
| **TaskId** | `long` | The task's identifier, assigned by the server |

##### QueueSinkScript

**A script that turns the messages from its topics into RavenDB documents.**

```csharp
class QueueSinkScript
{
    string Name
    List<string> Queues
    string Script
    bool Disabled
}
```

| Property | Type | Description |
| - | - | - |
| **Name** | `string` | The script name |
| **Queues** | `List<string>` | The Kafka topics to consume from |
| **Script** | `string` | The JavaScript that processes each message |
| **Disabled** | `bool` | Whether the script is disabled |

#### Enums

**Identifies the message broker that a connection string and sink task use.**

```csharp
enum QueueBrokerType
{
    None,
    Kafka,
    RabbitMq,
    AzureQueueStorage,
    AmazonSqs,
    AzureServiceBus
}
```

| Value | Description |
| - | - |
| **Kafka** | Selects Apache Kafka. Use this value for a Kafka connection string and sink task. |
| **None, RabbitMq, AzureQueueStorage, AmazonSqs, AzureServiceBus** | The other broker types, used by the remaining Queue Sink and Queue ETL brokers. |
