Add a key to data ingested through Kafka Connect

Question:

How can you stream data from a source system (such as a database) into Kafka using Kafka Connect, and add a key to the data as part of the ingestion?

Edit this page

Example use case:

Kafka Connect is the integration API for Apache Kafka. It enables you to stream data from source systems (such as databases, message queues, SaaS platforms, and flat files) into Kafka, and from Kafka to target systems. When you stream data into Kafka, you often need to set the key correctly for partitioning and application logic reasons. In this example, we have a database containing data about cities, and we want to key the resulting Kafka messages by the city_id field. This tutorial will show you different ways of setting the key correctly. It will also cover how to declare the schema and use Kafka Streams to process the data using SpecificAvro.

Hands-on code example:

Run it

Prerequisites

1

This tutorial installs Confluent Platform using Docker. Before proceeding:

  • • Install Docker Desktop (version 4.0.0 or later) or Docker Engine (version 19.03.0 or later) if you don’t already have it

  • • Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.

  • • Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd, via systemctl

  • • Verify that Docker is set up properly by ensuring no errors are output when you run docker info and docker compose version on the command line

Initialize the project

2

To get started, make a new directory anywhere you’d like for this project:

mkdir connect-add-key-to-source && cd connect-add-key-to-source

Then make the following directories to set up its structure:

mkdir src 

Prepare the source data

3

Create a file cities.sql with commands to pre-populate the database table with city information:

DROP TABLE IF EXISTS cities;
CREATE TABLE cities (city_id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(255), state VARCHAR(255));
INSERT INTO cities (city_id, name, state) VALUES (1, 'Raleigh', 'NC');
INSERT INTO cities (city_id, name, state) VALUES (2, 'Mountain View', 'CA');
INSERT INTO cities (city_id, name, state) VALUES (3, 'Knoxville', 'TN');
INSERT INTO cities (city_id, name, state) VALUES (4, 'Houston', 'TX');
INSERT INTO cities (city_id, name, state) VALUES (5, 'Olympia', 'WA');
INSERT INTO cities (city_id, name, state) VALUES (6, 'Bismarck', 'ND');

Get Confluent Platform

4

Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud). Make sure that you create this file in the same place as the cities.sql file that you created above.

version: '2'
services:
  broker:
    image: confluentinc/cp-kafka:7.4.1
    hostname: broker
    container_name: broker
    ports:
    - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_NODE_ID: 1
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
  schema-registry:
    image: confluentinc/cp-schema-registry:7.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
    - broker
    ports:
    - 8081:8081
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: broker:9092
  ksqldb-server:
    image: confluentinc/ksqldb-server:0.28.2
    hostname: ksqldb
    container_name: ksqldb
    depends_on:
    - broker
    ports:
    - 8088:8088
    environment:
      KSQL_LISTENERS: http://0.0.0.0:8088
      KSQL_BOOTSTRAP_SERVERS: broker:9092
      KSQL_KSQL_LOGGING_PROCESSING_STREAM_AUTO_CREATE: 'true'
      KSQL_KSQL_LOGGING_PROCESSING_TOPIC_AUTO_CREATE: 'true'
      KSQL_KSQL_SCHEMA_REGISTRY_URL: http://schema-registry:8081
      KSQL_KSQL_SERVICE_ID: confluent_rmoff_01
      KSQL_KSQL_HIDDEN_TOPICS: ^_.*
      KSQL_KSQL_CONNECT_WORKER_CONFIG: /connect/connect.properties
      KSQL_CONNECT_BOOTSTRAP_SERVERS: broker:9092
      KSQL_CONNECT_REST_ADVERTISED_HOST_NAME: ksqldb
      KSQL_CONNECT_GROUP_ID: ksqldb-kafka-connect-group-01
      KSQL_CONNECT_CONFIG_STORAGE_TOPIC: _ksqldb-kafka-connect-group-01-configs
      KSQL_CONNECT_OFFSET_STORAGE_TOPIC: _ksqldb-kafka-connect-group-01-offsets
      KSQL_CONNECT_STATUS_STORAGE_TOPIC: _ksqldb-kafka-connect-group-01-status
      KSQL_CONNECT_KEY_CONVERTER: io.confluent.connect.avro.AvroConverter
      KSQL_CONNECT_KEY_CONVERTER_SCHEMA_REGISTRY_URL: http://schema-registry:8081
      KSQL_CONNECT_VALUE_CONVERTER: io.confluent.connect.avro.AvroConverter
      KSQL_CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: http://schema-registry:8081
      KSQL_CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: '1'
      KSQL_CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: '1'
      KSQL_CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: '1'
      KSQL_CONNECT_LOG4J_APPENDER_STDOUT_LAYOUT_CONVERSIONPATTERN: '[%d] %p %X{connector.context}%m
        (%c:%L)%n'
      KSQL_CONNECT_PLUGIN_PATH: /home/appuser/share/java,/home/appuser/confluent-hub-components/,/data/connect-jars
    command:
    - bash
    - -c
    - "echo \"Installing connector plugins\"\nmkdir -p ~/confluent-hub-components/\n/home/appuser/bin/confluent-hub
      install --no-prompt --component-dir confluent-hub-components/ confluentinc/kafka-connect-jdbc:10.0.2\n#\necho
      \"Launching ksqlDB\"\n/usr/bin/docker/run & \n#\nsleep infinity\n"
  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.28.2
    container_name: ksqldb-cli
    depends_on:
    - broker
    - ksqldb-server
    entrypoint: /bin/sh
    tty: true
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
    volumes:
    - ./src:/opt/app/src
  kcat:
    image: edenhill/kcat:1.7.1
    container_name: kcat
    links:
    - broker
    entrypoint:
    - /bin/sh
    - -c
    - "apk add jq; \nwhile [ 1 -eq 1 ];do sleep 60;done\n"
  postgres:
    image: postgres:11
    container_name: postgres
    environment:
    - POSTGRES_USER=postgres
    - POSTGRES_PASSWORD=postgres
    volumes:
    - ./cities.sql:/docker-entrypoint-initdb.d/cities.sql

Now launch Confluent Platform by running:

docker compose up -d

Check the source data

5

Check the data in the source database. Observe the city_id primary key:

echo 'SELECT * FROM cities;' | docker exec -i postgres bash -c 'psql -U $POSTGRES_USER $POSTGRES_DB'
 city_id |     name      | state
---------+---------------+-------
       1 | Raleigh       | NC
       2 | Mountain View | CA
       3 | Knoxville     | TN
       4 | Houston       | TX
       5 | Olympia       | WA
       6 | Bismarck      | ND
(6 rows)

Create the connector

6

Launch the ksqlDB CLI:

docker exec -it ksqldb-cli ksql http://ksqldb-server:8088

From the ksqlDB prompt you can create the JDBC source connector. There are a couple of points to note:

  1. The transforms stanza, which is responsible for setting the key to the value of the city_id field. They run in the order defined by transforms:

    • - copyFieldToKey sets the key to a struct containing the city_id field from the value.

    • - extractKeyFromStruct sets the key to just the city_id field of the struct set by the previous step.

    • - removeKeyFromValue removes the city_id from the message value, as it’s now stored in the message key.

  2. Since the key is an integer we override the default serialization and instead use the IntegerConverter for the key field

CREATE SOURCE CONNECTOR IF NOT EXISTS JDBC_SOURCE_POSTGRES_01 WITH (
    'connector.class'= 'io.confluent.connect.jdbc.JdbcSourceConnector',
    'connection.url'= 'jdbc:postgresql://postgres:5432/postgres',
    'connection.user'= 'postgres',
    'connection.password'= 'postgres',
    'mode'= 'incrementing',
    'incrementing.column.name'= 'city_id',
    'topic.prefix'= 'postgres_',
    'transforms'= 'copyFieldToKey,extractKeyFromStruct,removeKeyFromValue',
    'transforms.copyFieldToKey.type'= 'org.apache.kafka.connect.transforms.ValueToKey',
    'transforms.copyFieldToKey.fields'= 'city_id',
    'transforms.extractKeyFromStruct.type'= 'org.apache.kafka.connect.transforms.ExtractField$Key',
    'transforms.extractKeyFromStruct.field'= 'city_id',
    'transforms.removeKeyFromValue.type'= 'org.apache.kafka.connect.transforms.ReplaceField$Value',
    'transforms.removeKeyFromValue.blacklist'= 'city_id',
    'key.converter' = 'org.apache.kafka.connect.converters.IntegerConverter'
);

Check that the connector is running:

SHOW CONNECTORS;

You should see that the state is RUNNING:

 Connector Name          | Type   | Class                                         | Status
----------------------------------------------------------------------------------------------------------------
 JDBC_SOURCE_POSTGRES_01 | SOURCE | io.confluent.connect.jdbc.JdbcSourceConnector | RUNNING (1/1 tasks RUNNING)
----------------------------------------------------------------------------------------------------------------

You can also inspect further details about the connector including to which topics it is writing:

DESCRIBE CONNECTOR JDBC_SOURCE_POSTGRES_01;
Name                 : JDBC_SOURCE_POSTGRES_01
Class                : io.confluent.connect.jdbc.JdbcSourceConnector
Type                 : source
State                : RUNNING
WorkerId             : ksqldb:8083

 Task ID | State   | Error Trace
---------------------------------
 0       | RUNNING |
---------------------------------

 Related Topics
-----------------
 postgres_cities
-----------------

Consume events from the output topic

7

With the connector running let’s now inspect the data on the Kafka topic. ksqlDB’s PRINT command will show the contents of a topic:

PRINT postgres_cities FROM BEGINNING LIMIT 6;

The output should resemble:

Key format: KAFKA_INT or KAFKA_STRING
Value format: AVRO or KAFKA_STRING
rowtime: 3/25/20 11:53:36 AM UTC, key: 1, value: {"name": "Raleigh", "state": "NC"}, partition: 0
rowtime: 3/25/20 11:53:36 AM UTC, key: 2, value: {"name": "Mountain View", "state": "CA"}, partition: 0
rowtime: 3/25/20 11:53:36 AM UTC, key: 3, value: {"name": "Knoxville", "state": "TN"}, partition: 0
rowtime: 3/25/20 11:53:36 AM UTC, key: 4, value: {"name": "Houston", "state": "TX"}, partition: 0
rowtime: 3/25/20 11:53:36 AM UTC, key: 5, value: {"name": "Olympia", "state": "WA"}, partition: 0
rowtime: 3/25/20 11:53:36 AM UTC, key: 6, value: {"name": "Bismarck", "state": "ND"}, partition: 0
Topic printing ceased

Notice how each Kafka message’s key has been set to the city_id.

Declare the topic as a ksqlDB table

8

Now that we have a topic with data in from the source system and the keys appropriately set, we can declare a ksqlDB table over the topic.

We only need to specify the datatype of the table’s key (CITY_ID) – the rest of the schema is picked up automagically from the Schema Registry since we’re using Avro to serialize the value part of the payload.

CREATE TABLE CITIES (CITY_ID INT PRIMARY KEY) WITH (KAFKA_TOPIC='postgres_cities', VALUE_FORMAT='AVRO');

With this table object created, we can query it or use it in queries such as joining to other objects.

SET 'auto.offset.reset' = 'earliest';

SELECT CITY_ID, NAME, STATE FROM CITIES EMIT CHANGES LIMIT 6;
+--------------------+--------------------+--------------------+
|CITY_ID             |NAME                |STATE               |
+--------------------+--------------------+--------------------+
|1                   |Raleigh             |NC                  |
|2                   |Mountain View       |CA                  |
|3                   |Knoxville           |TN                  |
|4                   |Houston             |TX                  |
|5                   |Olympia             |WA                  |
|6                   |Bismarck            |ND                  |
Limit Reached
Query terminated

Clean up

9

Exit the ksqlDB CLI with exit and shut down the stack by running:

docker compose down

Deploy on Confluent Cloud

Run your app with Confluent Cloud

1

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.

  1. Sign up for Confluent Cloud, a fully managed Apache Kafka service.

  2. After you log in to Confluent Cloud Console, click Environments in the lefthand navigation, click on Add cloud environment, and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  3. From the Billing & payment section in the menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.

  4. Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.

Confluent Cloud

Next, from the Confluent Cloud Console, click on Clients to get the cluster-specific configurations, e.g., Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.