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

# Delivering data from Yandex Managed Service for Apache Kafka® to Yandex Data Streams using Yandex Data Transfer

# Delivering data from an Apache Kafka® queue to YDS


A stream in Data Streams can receive data from Apache Kafka® topics in real time.

To start data delivery:

1. [Create a target stream in Data Streams](#create-target-yds).
1. [Set up and activate the transfer](#prepare-transfer).
1. [Test your 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, which includes 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)).
* Managed Service for YDB database (see [Managed Service for YDB pricing](../../ydb/pricing/index.md)). Its cost depends on the deployment mode:

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

* Data Streams (see [Data Streams pricing](../../data-streams/pricing.md)). The cost depends on the pricing model:

    * [Based on allocated resources](../../data-streams/pricing.md#rules): You pay a fixed hourly rate for the established throughput limit and message retention period, and additionally for the number of units of actually written data.
    * [On-demand](../../data-streams/pricing.md#on-demand): You pay for the performed read/write operations, the amount of read or written data, and the actual storage used for messages that are still within their retention period.


## 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](../../managed-kafka/operations/cluster-create.md) of any suitable configuration.
        1. [Create a Managed Service for YDB database](../../ydb/operations/manage-databases.md) of your preferred configuration.
        1. [In the source cluster, create a topic](../../managed-kafka/operations/cluster-topics.md#create-topic) named `sensors`.
        1. [In the source cluster, create a user](../../managed-kafka/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](../infrastructure-management/terraform-quickstart.md#install-terraform).
        1. [Get the authentication credentials](../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](../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](../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-yds/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.
            * Transfer.

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

            * `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.
            * `transfer_enabled`: Set to `0` to ensure that 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 %}

    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 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® source cluster over SSL](../../managed-kafka/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
        ```

## Create a target stream in Data Streams {#create-target-yds}

[Create a target stream in Data Streams](../../data-streams/operations/aws-cli/create.md) for your Managed Service for YDB database.

## Set up and activate the transfer {#prepare-transfer}

1. [Create](../../data-transfer/operations/endpoint/index.md#create) an [`Apache Kafka®` source endpoint](../../data-transfer/operations/endpoint/source/kafka.md):

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

        * **Conversion rules**: `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 an endpoint](../../data-transfer/operations/endpoint/index.md#create) for the [`Yandex Data Streams` target](../../data-transfer/operations/endpoint/target/data-streams.md):

    **Connection settings**:

    * **Database**: Select your Managed Service for YDB database from the list.
    * **Stream**: Specify the name of the stream in Data Streams.

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


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.

            If you want to transform data during the transfer, specify the relevant transformers in the transfer settings:

            * [Renaming tables](../../data-transfer/concepts/data-transformation.md#rename-tables)
            * [Column filter](../../data-transfer/concepts/data-transformation.md#columns-filter)
            * [Data masking](../../data-transfer/concepts/data-transformation.md#data-mask)
            * [Splitting tables into subtables](../../data-transfer/concepts/data-transformation.md#subtable-splitting)
            * [Replacing primary keys](../../data-transfer/concepts/data-transformation.md#replace-primary-key)
            * [Converting column values to strings](../../data-transfer/concepts/data-transformation.md#convert-to-string)
            * [Sharding](../../data-transfer/concepts/data-transformation.md#shard)
            * [String filter for APPEND-ONLY sources](../../data-transfer/concepts/data-transformation.md#append-only-sources)

        1. [Activate](../../data-transfer/operations/transfer.md#activate) the transfer.

    - Terraform {#tf}

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

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

        1. If you want to transform data during the transfer, add the `transformation` section with a list of relevant transformers to the `yandex_datatransfer_transfer` resource:

            ```hcl
            resource "yandex_datatransfer_transfer" "mkf-ydb-transfer" {
              ...
              transformation {
                transformers{
                  <transformer_1>
                }
                transformers{
                  <transformer_2>
                }
                ...
                transformers{
                  <transformer_N>
                }
              }
            }
            ```

            The following transformer types are available:

            * [Renaming tables](../../data-transfer/concepts/data-transformation.md#rename-tables)
            * [Column filter](../../data-transfer/concepts/data-transformation.md#columns-filter)
            * [Data masking](../../data-transfer/concepts/data-transformation.md#data-mask)
            * [Splitting tables into subtables](../../data-transfer/concepts/data-transformation.md#subtable-splitting)
            * [Replacing primary keys](../../data-transfer/concepts/data-transformation.md#replace-primary-key)
            * [Converting column values to strings](../../data-transfer/concepts/data-transformation.md#convert-to-string)
            * [Sharding](../../data-transfer/concepts/data-transformation.md#shard)
            * [String filter for APPEND-ONLY sources](../../data-transfer/concepts/data-transformation.md#append-only-sources)

            For more information on configuring transformers, see [this Terraform provider article](../../terraform/resources/datatransfer_transfer.md).

        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. Make sure data from the Managed Service for Apache Kafka® source cluster topic is being transferred to the stream in Data Streams:

    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": "iv9a94th6r********",
            "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](../../managed-kafka/operations/connect/clients.md).

    Make sure the data from the source has been moved to the Data Streams stream:
    
      {% list tabs group=instructions %}
    
      - Management console {#console}
    
          1. In the [management console](https://console.yandex.cloud), select a folder.
          1. Navigate to **Data Streams**.
          1. Select the target stream from the list and navigate to ![image](../../_assets/console-icons/bars.svg) **Data viewer**.
          1. Make sure `shard-000000` now contains messages with the source table rows. For a closer look at the messages, click ![image](../../_assets/console-icons/eye.svg).
    
      - AWS CLI {#cli}
    
          1. Install the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
          1. [Configure the environment](../../data-streams/quickstart/index.md) for Data Streams.
          1. Read the stream data using:
    
              * [AWS CLI](../../data-streams/operations/aws-cli/get-records.md).
              * [AWS SDK](../../data-streams/operations/aws-sdk/get-records.md).
    
      {% endlist %}

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

{% note info %}

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

{% endnote %}

To reduce the consumption of resources, delete those you do not 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 target endpoint, [delete it](../../iam/operations/sa/delete.md).


1. Delete the other 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](../../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 %}