[Yandex Cloud documentation](../../index.md) > [Yandex Managed Service for YDB](../index.md) > [Tutorials](index.md) > Delivering data from YDB to Yandex Managed Service for Apache Kafka® using Yandex Data Transfer

# Delivering data from YDB to Yandex Managed Service for Apache Kafka®

# Delivering data from Yandex Managed Service for YDB to Yandex Managed Service for Apache Kafka®


You can track data changes in a Managed Service for YDB _source_ and send them to a Managed Service for Apache Kafka® _target cluster_ using [change data capture](../../data-transfer/concepts/cdc.md) (CDC). The system will automatically insert this data into Managed Service for Apache Kafka® topics with Managed Service for YDB table names.

{% note info %}

In YDB, CDC mode is supported starting from version 22.5.

{% endnote %}

To start data delivery:

1. [Prepare the source](#prepare-source).
1. [Prepare and activate your transfer](#prepare-transfer).
1. [Test the transfer](#verify-transfer).

If you no longer need the resources you created, [delete them](#clear-out).


## Required paid resources {#paid-resources}

* Managed Service for YDB database (see [Managed Service for YDB pricing](../pricing/index.md)). The cost depends on the deployment mode:

	* In serverless mode, you pay for data operations as well as the amount of stored data and backups.
  	* In dedicated instance mode, you pay for the use of computing resources allocated to the database, storage size, and backups.

* Managed Service for Apache Kafka® cluster: computing resources allocated to hosts, storage and backup size (see [Managed Service for Apache Kafka® pricing](../../managed-kafka/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Each transfer: use of computing resources and the number of transferred data rows (see [Data Transfer pricing](../../data-transfer/pricing.md)).


## Getting started {#before-you-begin}

1. Set up your data delivery infrastructure:

   {% list tabs group=instructions %}

   - Manually {#manual}


       1. [Create a Managed Service for YDB database](../operations/manage-databases.md) of any suitable configuration.

       1. If you selected Dedicated database mode, [create](../../vpc/operations/security-group-create.md) and [configure](../operations/connection.md#configuring-security-groups) a security group in the network hosting your database.

       1. [Create a Managed Service for Apache Kafka® target cluster](../../managed-kafka/operations/cluster-create.md) in any suitable configuration with publicly accessible hosts.

          {% note info %}
          
          Public access to cluster hosts is required if you plan to connect to the cluster via the internet. This connection option is simpler and is recommended for the purposes of this guide. You can connect to non-public hosts as well but only from Yandex Cloud virtual machines located in the same cloud network as the cluster.
          
          {% endnote %}

       
        1. If using security groups, [configure them to allow internet access to your cluster](../../managed-kafka/operations/connect/index.md#configuring-security-groups).


       1. Configure Apache Kafka® topics in the target cluster. The settings vary depending on the [topic management method](../../managed-kafka/concepts/topics.md#management) used. The format for data topic names is as follows: `<topic_prefix>.<YDB_table_name>`. In this tutorial, we will use the `cdc` prefix as an example.

          * When managing topics using the native Yandex Cloud interfaces (management console, CLI, or API):

              1. [Create a topic](../../managed-kafka/operations/cluster-topics.md#create-topic) named `cdc.sensors`.

                 To track changes in multiple tables, create a separate topic with the `cdc` prefix for each of them.

              1. [Create a user](../../managed-kafka/operations/cluster-accounts.md#create-account) with the `ACCESS_ROLE_CONSUMER` and `ACCESS_ROLE_PRODUCER` roles for the `cdc.sensors` topic. To include all created topics, specify `cdc.*` in the topic name.

          * When managing topics via the Kafka Admin API:

              1. Create an [admin user](../../managed-kafka/operations/cluster-accounts.md).
              1. In addition to `ACCESS_ROLE_ADMIN`, assign the admin user the `ACCESS_ROLE_CONSUMER` and `ACCESS_ROLE_PRODUCER` roles for `cdc.*` topics whose names are prefixed with `cdc`.

                 The system will automatically create the relevant topics upon the first change to the source cluster tables you are tracking. This solution can help tracking changes in multiple tables but it requires extra free space in the cluster storage. For more information, see [Storage in Managed Service for Apache Kafka®](../../managed-kafka/concepts/storage.md).

   - Terraform {#tf}

       1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
       1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
       1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
       1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

       1. Download the [data-transfer-ydb-mkf.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-cdc-from-ydb-to-kafka/blob/main/data-transfer-ydb-mkf.tf) configuration file to the same working directory.

           This file describes:

           * [Network](../../vpc/concepts/network.md#network).
           * [Subnet](../../vpc/concepts/network.md#subnet).
           * [Security group](../../vpc/concepts/security-groups.md) and the rule required for connecting to the Managed Service for Apache Kafka® cluster.
           * Managed Service for YDB database.
           * Managed Service for Apache Kafka® target cluster.
           * Apache Kafka® topic.
           * Apache Kafka® user.
           * Transfer.

           The [topic management method](../../managed-kafka/concepts/topics.md#management) is specified in the `kf_topics_management` Terraform variable. You set it when running the `terraform plan` and `terraform apply` commands (see below):

           * When managing topics using the native Yandex Cloud interfaces (management console, CLI, or API):
               1. To track changes in multiple tables, add the descriptions of separate topics with the `cdc` prefix to the configuration file, one for each table.
               1. Set the `kf_topics_management` Terraform variable to `false`.

           * When managing topics using the Kafka Admin API, set the `kf_topics_management` Terraform variable to `true`.

       1. In the `data-transfer-ydb-mkf.tf` file, specify the following variables:

           * `source_db_name`: Managed Service for YDB database name.
           * `target_kf_version`: Apache Kafka® version in the target cluster.
           * `target_user_name`: Username for connection to the Apache Kafka® topic.
           * `target_user_password`: User password.
           * `transfer_enabled`: Set to `0` to ensure no transfer is created until you [create endpoints manually](#prepare-transfer).

       1. Validate your Terraform configuration files using this command:

           ```bash
           terraform validate
           ```

           Terraform will display any configuration errors detected in your files.

       1. Create the required infrastructure:

           1. Run this command to view the planned changes:
           
              ```bash
              terraform plan
              ```
           
              If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
           
           1. If everything looks correct, apply the changes:
              1. Run this command:
           
                 ```bash
                 terraform apply
                 ```
           
              1. Confirm updating the resources.
              1. Wait for the operation to complete.

           All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

   {% endlist %}

1. Install [kafkacat](https://github.com/edenhill/kcat) for data reads and writes in Apache Kafka® topics.

    ```bash
    sudo apt update && sudo apt install --yes kafkacat
    ```

    Make sure you can use it to [connect to the Managed Service for Apache Kafka® target cluster over SSL](../../managed-kafka/operations/connect/clients.md#bash-zsh).

## Prepare the source {#prepare-source}

1. [Connect to the Managed Service for YDB database](../operations/connection.md).
1. [Create a YDB table](../operations/schema.md#create-table). As an example, we will use the `sensors` table with data collected from some car sensors.

   Add the following columns to the table manually:

    | Name | Type | Primary key |
    |:--------------------|:---------|:---------------|
    | `device_id`         | `String` | Yes             |
    | `datetime`          | `String` |                |
    | `latitude`          | `Double` |                |
    | `longitude`         | `Double` |                |
    | `altitude`          | `Double` |                |
    | `speed`             | `Double` |                |
    | `battery_voltage`   | `Double` |                |
    | `cabin_temperature` | `Uint8`  |                |
    | `fuel_level`        | `Uint32` |                |

    Leave the other settings at their defaults.

    You can also create a table by running this YQL command:

    ```sql
    CREATE TABLE sensors (
        device_id String,
        datetime String,
        latitude Double,
        longitude Double,
        altitude Double,
        speed Double,
        battery_voltage Double,
        cabin_temperature Uint8,
        fuel_level Uint32,
        PRIMARY KEY (device_id)
    )
    ```

## Prepare and activate a transfer {#prepare-transfer}

1. [Create a source endpoint](../../data-transfer/operations/endpoint/index.md#create):

    * **Database type**: `YDB`.
    * **Endpoint parameters**:

        * **Connection settings**:
           * **Database**: Select the Managed Service for YDB database from the list.

           
           * **Service account ID**: Select an existing service account or create a new one with the `editor` role.


        * **Included paths list**: Specify the names of tables and Managed Service for YDB database directories to transfer.

           {% note warning %}

           Only the listed tables and directories will be replicated. If you do not specify any names, no tables will be transferred.

           {% endnote %}

1. [Create a target endpoint](../../data-transfer/operations/endpoint/index.md#create):
    * **Database type**: `Kafka`.
    * **Endpoint parameters**:
        * **Connection type**: `Managed Service for Apache Kafka cluster`:
            * **Managed Service for Apache Kafka cluster**: Select the [previously created](#before-you-begin) Managed Service for Apache Kafka® source cluster.
            * **Authentication**: Specify the credentials of the Apache Kafka® user [you created](#before-you-begin).

        * **Topic**: `Topic full name`.
        * **Topic full name**: `cdc.sensors`.

        If you need to track changes in multiple tables, fill in the fields as follows:

        * **Topic**: `Topic prefix`.
        * **Topic prefix**: Enter the `cdc` prefix you used to generate topic names.

1. Create a transfer:

    {% list tabs group=instructions %}

    - Manually {#manual}

        1. [Create a transfer](../../data-transfer/operations/transfer.md#create) of the **_Replication_** type that will use the endpoints you created.
        1. [Activate](../../data-transfer/operations/transfer.md#activate) the transfer.

    - Terraform {#tf}

        1. In the `data-transfer-ydb-mkf.tf` file, specify the following variables:

            * `source_endpoint_id`: Source endpoint ID.
            * `target_endpoint_id`: Target endpoint ID.
            * `transfer_enabled`: Set to `1` to create the transfer.

        1. Validate your Terraform configuration files using this command:

            ```bash
            terraform validate
            ```

            Terraform will display any configuration errors detected in your files.

        1. Create the required infrastructure:

            1. Run this command to view the planned changes:
            
               ```bash
               terraform plan
               ```
            
               If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
            
            1. If everything looks correct, apply the changes:
               1. Run this command:
            
                  ```bash
                  terraform apply
                  ```
            
               1. Confirm updating the resources.
               1. Wait for the operation to complete.

            The transfer will be activated automatically upon creation.

    {% endlist %}

## Test the transfer {#verify-transfer}

1. Wait for the transfer status to change to **Replicating**.
1. In a separate terminal, run `kafkacat` in consumer mode:

    ```bash
    kafkacat \
        -C \
        -b <broker_host_1_FQDN>:9091,...,<broker_host_N_FQDN>:9091 \
        -t cdc.sensors \
        -X security.protocol=SASL_SSL \
        -X sasl.mechanisms=SCRAM-SHA-512 \
        -X sasl.username=kafka-user \
        -X sasl.password=<password> \
        -X ssl.ca.location=/usr/local/share/ca-certificates/Yandex/YandexInternalRootCA.crt \
        -Z \
        -K:
    ```

    You can get the FQDNs of broker hosts with the [list of hosts in the Managed Service for Apache Kafka® cluster](../../managed-kafka/operations/cluster-hosts.md).

1. [Connect to the Managed Service for YDB database](../operations/connection.md) and [add test data](../operations/crud.md) to the `sensors` table:

    ```sql
    REPLACE INTO sensors (device_id, datetime, latitude, longitude, altitude, speed, battery_voltage, cabin_temperature, fuel_level) VALUES 
        ('iv9a94th6rzt********', '2022-06-05 17:27:00', 55.70329032, 37.65472196, 427.5, 0, 23.5, 17, NULL),
        ('rhibbh3y08qm********', '2022-06-06 09:49:54', 55.71294467, 37.66542005, 429.13, 55.5, NULL, 18, 32),
        ('iv9a94th6rzt********', '2022-06-08 17:45:00', 53.70987913, 36.62549834, 378.0, NULL, 20.5, 15, 20);
    ```

1. Make sure the terminal running `kafkacat` displays the data format schema of the `sensors` table and information about the added rows.

    {% cut "Message snippet example" %}

    ```json
    {
      "payload": {
          "device_id": "aXY5YTk0dGg2cnp0b294********"
        },
        "schema": {
          "fields": [
            {
                "field": "device_id",
                "optional": false,
                "type": "bytes"
            }
          ],
          "name": "cdc..sensors.Key",
          "optional": false,
          "type": "struct"
        }
    }: {
      "payload": {
        "after": {
            "altitude": 378,
            "battery_voltage": 20.5,
            "cabin_temperature": 15,
            "datetime": "MjAyMi0wNi0wOCAxNzo0********",
            "device_id": "aXY5YTk0dGg2cnp0b294********",
            "fuel_level": 20,
            "latitude": 53.70987913,
            "longitude": 36.62549834,
            "speed": null
        },
        "before": null,
        "op": "c",
        "source": {
            "db": "",
            "name": "cdc",
            "snapshot": "false",
            "table": "sensors",
            "ts_ms": 1678642104797,
            "version": "1.1.2.Final"
        },
        "transaction": null,
        "ts_ms": 1678642104797
      },
      "schema": {
        "fields": [
            {
                "field": "before",
                "fields": [
                    {
                        "field": "device_id",
                        "optional": false,
                        "type": "bytes"
                    },
                    ...
                ],
                "name": "cdc..sensors.Value",
                "optional": true,
                "type": "struct"
            },
            {
                "field": "after",
                "fields": [
                    {
                        "field": "device_id",
                        "optional": false,
                        "type": "bytes"
                    },
                    ...
                ],
                "name": "cdc..sensors.Value",
                "optional": true,
                "type": "struct"
            },
            {
                "field": "source",
                "fields": [
                    {
                        "field": "version",
                        "optional": false,
                        "type": "string"
                    },
                    {
                        "field": "connector",
                        "optional": false,
                        "type": "string"
                    },
                    {
                        "field": "name",
                        "optional": false,
                        "type": "string"
                    },
                    {
                        "field": "ts_ms",
                        "optional": false,
                        "type": "int64"
                    },
                    {
                        "default": "false",
                        "field": "snapshot",
                        "name": "io.debezium.data.Enum",
                        "optional": true,
                        "parameters": {
                            "allowed": "true,last,false"
                        },
                        "type": "string",
                        "version": 1
                    },
                    {
                        "field": "db",
                        "optional": false,
                        "type": "string"
                    },
                    {
                        "field": "table",
                        "optional": false,
                        "type": "string"
                    }
                ],
                "optional": false,
                "type": "struct"
            },
            ...,
            {
                "field": "transaction",
                "fields": [
                    {
                        "field": "id",
                        "optional": false,
                        "type": "string"
                    },
                    {
                        "field": "total_order",
                        "optional": false,
                        "type": "int64"
                    },
                    {
                        "field": "data_collection_order",
                        "optional": false,
                        "type": "int64"
                    }
                ],
                "optional": true,
                "type": "struct"
            }
        ],
        "name": "cdc..sensors.Envelope",
        "optional": false,
        "type": "struct"
      }
    }
    ```

    {% endcut %}

## Delete the resources you created {#clear-out}

{% note info %}

Before deleting any resources, [deactivate the transfer](../../data-transfer/operations/transfer.md#deactivate).

{% endnote %}

To minimize resource consumption, delete the resources you no longer need:

1. [Delete the transfer](../../data-transfer/operations/transfer.md#delete).
1. [Delete the source and target endpoints](../../data-transfer/operations/endpoint/index.md#delete).


1. If you created a service account when creating the source endpoint, [delete it](../../iam/operations/sa/delete.md).


1. Delete the rest of the resources depending on how you created them:

   {% list tabs group=instructions %}

   - Manually {#manual}

       1. [Delete the Managed Service for Apache Kafka® cluster](../../managed-kafka/operations/cluster-delete.md).
       1. [Delete the Managed Service for YDB database](../operations/manage-databases.md#delete-db).

   - Terraform {#tf}

       1. In the terminal window, go to the directory containing the infrastructure plan.
       
           {% note warning %}
       
           Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
       
           {% endnote %}
       
       1. Delete resources:
       
           1. Run this command:
       
               ```bash
               terraform destroy
               ```
       
           1. Confirm deleting the resources and wait for the operation to complete.
       
           All the resources described in the Terraform manifests will be deleted.

   {% endlist %}