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

# Delivering data to Yandex Managed Service for YDB using Yandex Data Transfer

# Delivering data from an Apache Kafka® queue to YDB


A Managed Service for YDB cluster can ingest data from Apache Kafka® topics in real time. This data is automatically added to YDB tables with topic names.

To start data delivery:

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 Apache Kafka® cluster: computing resources allocated to hosts, storage and backup size (see [Managed Service for Apache Kafka® pricing](../pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Managed Service for YDB database (see [Managed Service for YDB pricing](../../ydb/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.

* 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 Apache Kafka® source cluster](../operations/cluster-create.md) of any suitable configuration.
       1. [Create a Managed Service for YDB database](../../ydb/operations/manage-databases.md) of any suitable configuration.
       1. [In the source cluster, create a topic](../operations/cluster-topics.md#create-topic) named `sensors`.
       1. [In the source cluster, create a user](../operations/cluster-accounts.md#create-account) with the `ACCESS_ROLE_PRODUCER` and `ACCESS_ROLE_CONSUMER` permissions for the new topic.

   
   - 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-mkf-ydb.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-kafka-to-ydb/blob/main/data-transfer-mkf-ydb.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 Apache Kafka® source cluster.
           * Apache Kafka® topic.
           * Apache Kafka® user.
           * Managed Service for YDB database.
           * Service account for connecting to the Managed Service for YDB database.
           * Apache Kafka® endpoint.
           * Managed Service for YDB endpoint.
           * Transfer.

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

           * `folder_id`: ID of the folder to create the required resources in.
           * `source_kf_version`: Apache Kafka® version in the source cluster.
           * `source_user_name`: Username for connection to the Apache Kafka® topic.
           * `source_user_password`: User password.
           * `target_db_name`: Managed Service for YDB database name.

       1. Make sure the Terraform configuration files are correct 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 %}

   The new source cluster Apache Kafka® topic named `sensors` will receive test data from car sensors in JSON format:

   ```json
   {
       "device_id":"iv9a94th6rzt********",
       "datetime":"2020-06-05 17:27:00",
       "latitude":"55.70329032",
       "longitude":"37.65472196",
       "altitude":"427.5",
       "speed":"0",
       "battery_voltage":"23.5",
       "cabin_temperature":"17",
       "fuel_level":null
   }
   ```

1. Install these tools:

    - [kafkacat](https://github.com/edenhill/kcat): For reading from and writing to Apache Kafka® topics.

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

        Check that you can use it to [connect to the Managed Service for Apache Kafka® source cluster over SSL](../operations/connect/clients.md#bash-zsh).

    - [jq](https://stedolan.github.io/jq/): For stream processing of JSON files.

        ```bash
        sudo apt update && sudo apt-get install --yes jq
        ```

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

{% list tabs group=instructions %}

- Manually {#manual}

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

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

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

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


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

        * **Database type**: `Kafka`.
        * **Endpoint parameters**:
            * **Connection type**: `Managed Service for Apache Kafka cluster`.

                Select your source cluster from the list and specify its connection settings.

            * **Advanced settings** → **Conversion rules**:
                * **Data format**: `JSON`.
                * **Data scheme**: You can specify a schema using one of these two methods:

                    * `Field list`.

                        Set a list of topic fields manually:

                       | Name                 | Type      | Key |
                       |:--------------------|:---------|:-----|
                       | `device_id`         | `STRING` | Yes   |
                       | `datetime`          | `STRING` |      |
                       | `latitude`          | `DOUBLE` |      |
                       | `longitude`         | `DOUBLE` |      |
                       | `altitude`          | `DOUBLE` |      |
                       | `speed`             | `DOUBLE` |      |
                       | `battery_voltage`   | `DOUBLE` |      |
                       | `cabin_temperature` | `UINT16` |      |
                       | `fuel_level`        | `UINT16` |      |

                    * `JSON specification`.

                        Create and upload a data schema file in JSON format, `json_schema.json`:

                        {% cut "json_schema.json" %}

                        ```json
                        [
                            {
                                "name": "device_id",
                                "type": "string",
                                "key": true
                            },
                            {
                                "name": "datetime",
                                "type": "string"
                            },
                            {
                                "name": "latitude",
                                "type": "double"
                            },
                            {
                                "name": "longitude",
                                "type": "double"
                            },
                            {
                                "name": "altitude",
                                "type": "double"
                            },
                            {
                                "name": "speed",
                                "type": "double"
                            },
                            {
                                "name": "battery_voltage",
                                "type": "double"
                            },
                            {
                                "name": "cabin_temperature",
                                "type": "uint16"
                            },
                            {
                                "name": "fuel_level",
                                "type": "uint16"
                            }
                        ]
                        ```

                        {% endcut %}

    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-mkf-ydb.tf` file, set the `transfer_enabled` variable to `1` to create your endpoints and transfer.

    1. Make sure the Terraform configuration files are correct 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. Make sure that the data from the topic in the source Managed Service for Apache Kafka® cluster is being transferred to the Managed Service for YDB database:

    1. Create a file named `sample.json` with test data:

        ```json
        {
            "device_id": "iv9a94th6rzt********",
            "datetime": "2020-06-05 17:27:00",
            "latitude": 55.70329032,
            "longitude": 37.65472196,
            "altitude": 427.5,
            "speed": 0,
            "battery_voltage": 23.5,
            "cabin_temperature": 17,
            "fuel_level": null
        }

        {
            "device_id": "rhibbh3y08qm********",
            "datetime": "2020-06-06 09:49:54",
            "latitude": 55.71294467,
            "longitude": 37.66542005,
            "altitude": 429.13,
            "speed": 55.5,
            "battery_voltage": null,
            "cabin_temperature": 18,
            "fuel_level": 32
        }

        {
            "device_id": "iv9a94th6rzt********",
            "datetime": "2020-06-07 15:00:10",
            "latitude": 55.70985913,
            "longitude": 37.62141918,
            "altitude": 417.0,
            "speed": 15.7,
            "battery_voltage": 10.3,
            "cabin_temperature": 17,
            "fuel_level": null
        }
        ```

    1. Send data from `sample.json` to the Managed Service for Apache Kafka® `sensors` topic using `jq` and `kafkacat`:

        ```bash
        jq -rc . sample.json | kafkacat -P \
           -b <broker_host_FQDN>:9091 \
           -t sensors \
           -k key \
           -X security.protocol=SASL_SSL \
           -X sasl.mechanisms=SCRAM-SHA-512 \
           -X sasl.username="<username_in_source_cluster>" \
           -X sasl.password="<user_password_in_source_cluster>" \
           -X ssl.ca.location=/usr/local/share/ca-certificates/Yandex/YandexInternalRootCA.crt -Z
        ```

        The data is sent on behalf of the [created user](#prepare-source). To learn more about setting up an SSL certificate and using `kafkacat`, see [Connecting to an Apache Kafka® cluster from applications](../operations/connect/clients.md).

    1. Make sure the data from the Managed Service for Apache Kafka® source cluster has been transferred to the Managed Service for YDB database:

        {% list tabs group=instructions %}

        - Management console {#console}

           1. In the [management console](https://console.yandex.cloud), select the folder containing your database.
           1. Navigate to **Managed Service for&nbsp;YDB**.
           1. Select your database from the list.
           1. Navigate to the **Navigation** tab.
           1. Check that the Managed Service for YDB database contains a table named `sensors` with the test data from the topic.

        - YDB CLI {#cli}

           1. [Connect to the Managed Service for YDB database](../../ydb/operations/connection.md).
           1. Check that the database contains a table named `sensors` with the test data from the topic:

               ```bash
               ydb table query execute \
                 --query "SELECT * \
                 FROM sensors"
               ```

        {% endlist %}

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

{% note info %}

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

{% endnote %}

To reduce the consumption of resources, delete those you do not need:

{% list tabs group=instructions %}

- Manually {#manual}

    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 target endpoint, [delete it](../../iam/operations/sa/delete.md).


    1. [Delete the Managed Service for Apache Kafka® cluster](../operations/cluster-delete.md).
    1. [Delete the Managed Service for YDB database](../../ydb/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 %}