Add key to data ingested through Kafka Connect

Question:

How can I 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 ingest?

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 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 there is data about cities in a database, and we want to key the resulting Kafka message by the city_id field. There are different ways to set the key correctly and these tutorials will show you how. It will also cover how to declare the schema and use Kafka Streams to process the data using SpecificAvro.

Code example:

Try it

1
Initialize the project

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

2
Get Confluent Platform

Next, create the following docker-compose.yml file to obtain Confluent Platform:

---
version: '2'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.5.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:5.5.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

  schema-registry:
    image: confluentinc/cp-schema-registry:5.5.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - zookeeper
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: 'zookeeper:2181'

  connect:
    image: confluentinc/cp-kafka-connect:5.5.0
    hostname: connect
    container_name: connect
    depends_on:
      - schema-registry
    ports:
      - "8083:8083"
    environment:
      CONNECT_BOOTSTRAP_SERVERS: 'broker:9092'
      CONNECT_REST_ADVERTISED_HOST_NAME: connect
      CONNECT_REST_PORT: 8083
      CONNECT_GROUP_ID: compose-connect-group
      CONNECT_CONFIG_STORAGE_TOPIC: docker-connect-configs
      CONNECT_CONFIG_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_OFFSET_FLUSH_INTERVAL_MS: 10000
      CONNECT_OFFSET_STORAGE_TOPIC: docker-connect-offsets
      CONNECT_OFFSET_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_STATUS_STORAGE_TOPIC: docker-connect-status
      CONNECT_STATUS_STORAGE_REPLICATION_FACTOR: 1
      CONNECT_KEY_CONVERTER: org.apache.kafka.connect.storage.StringConverter
      CONNECT_VALUE_CONVERTER: io.confluent.connect.avro.AvroConverter
      CONNECT_VALUE_CONVERTER_SCHEMA_REGISTRY_URL: http://schema-registry:8081
      CONNECT_INTERNAL_KEY_CONVERTER: "org.apache.kafka.connect.json.JsonConverter"
      CONNECT_INTERNAL_VALUE_CONVERTER: "org.apache.kafka.connect.json.JsonConverter"
      CONNECT_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      CONNECT_PLUGIN_PATH: "/usr/share/java,/usr/share/confluent-hub-components"
      CONNECT_LOG4J_LOGGERS: org.apache.zookeeper=ERROR,org.I0Itec.zkclient=ERROR,org.reflections=ERROR

And launch it by running:

docker-compose up -d

3
Configure the project

Create the following Gradle build file, named build.gradle for the project:

buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:0.15.1"
  }
}

plugins {
  id "java"
  id "application"
  id "com.google.cloud.tools.jib" version "1.1.1"
  id "com.github.johnrengelman.shadow" version "5.1.0"
}

sourceCompatibility = "1.8"
targetCompatibility = "1.8"
version = "0.0.1"

repositories {
  jcenter()

  maven {
    url "http://packages.confluent.io/maven"
  }
}

apply plugin: "com.commercehub.gradle.plugin.avro"
apply plugin: "com.github.johnrengelman.shadow"

dependencies {
  compile "org.apache.avro:avro:1.8.2"
  implementation "org.slf4j:slf4j-simple:1.7.26"
  implementation "org.apache.kafka:kafka-streams:2.2.0"
  implementation "io.confluent:kafka-streams-avro-serde:5.2.0"
  implementation 'com.google.code.gson:gson:2.8.5'

  testCompile "org.apache.kafka:kafka-streams-test-utils:2.2.0"
  testImplementation 'junit:junit:4.12'
}

test {
  testLogging {
    outputs.upToDateWhen { false }
    showStandardStreams = true
    exceptionFormat = "full"
  }
}

jar {
  manifest {
    attributes(
        "Class-Path": configurations.compile.collect { it.getName() }.join(" "),
        "Main-Class": "io.confluent.developer.connect.jdbc.specificavro.StreamsIngest"
    )
  }
}

shadowJar {
  baseName = "connect-add-key-to-source"
  classifier = "standalone"
}

// Define the main class for the application
mainClassName = 'io.confluent.developer.connect.jdbc.specificavro.StreamsIngest'

And be sure to run the following command to obtain the Gradle wrapper:

gradle wrapper

Next, create a directory for configuration data:

mkdir configuration

Then create a development file at configuration/dev.properties:

application.id=cities_ingestion
bootstrap.servers=127.0.0.1:29092
schema.registry.url=http://127.0.0.1:8081

input.topic.name=cities
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=cities_keyed
output.topic.partitions=1
output.topic.replication.factor=1

4
Create a schema for the events

This tutorial uses one stream of cities. Let’s create the schemas for it.

Create a directory for the schema that represents each city in the stream:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/city.avsc for the cities lookup table:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "City",
  "fields": [
    {
      "name": "city_id",
      "type": "long"
    },
    {
      "name": "name",
      "type": "string"
    },
    {
      "name": "state",
      "type": "string"
    }
  ]
}

Because we will use this Avro schema in our Java code, we’ll need to compile it. The Gradle Avro plugin is a part of the build, so it will see your new Avro file, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

5
Create the source database

Create a file cities.sql with commands to prepopulate the database table with city information:

DROP TABLE IF EXISTS cities;
CREATE TABLE cities (city_id INTEGER 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');

Then create a Dockerfile to build the sqlite container. Notice that it pulls in the cities.sql file created in the previous step.

FROM alpine:3.4
RUN apk add --update sqlite
RUN mkdir /db
WORKDIR /db
ADD cities.sql /db
RUN sqlite3 geos.db < /db/cities.sql

ENTRYPOINT ["sqlite3"]

Create the source database, running this from the directory with the Dockerfile and the cities.sql file:

docker build -t sqlitekt . && docker run -d -i --name sqlitekt sqlitekt

View the data in the source table:

echo 'select * from cities;' | docker exec -i sqlitekt sqlite3 geos.db

6
Run the connector

Copy the sqlite database from the sqlitekt docker image to the connect docker image:

docker cp sqlitekt:/db/geos.db /tmp/geos.db && docker cp /tmp/geos.db connect:/tmp/geos.db

Make a configuration file called jdbc_source.config for the JDBC source connector to pull data from the cities table. Notice that it uses a single message transformation (SMT) called SetSchemaMetadata to set the schema name to the City class name.

{
  "name": "jdbc-cities",
  "config": {
    "connector.class": "io.confluent.connect.jdbc.JdbcSourceConnector",
    "connection.url": "jdbc:sqlite:/tmp/geos.db",
    "mode": "incrementing",
    "incrementing.column.name": "city_id",
    "topic.prefix": "",
    "table.whitelist": "cities",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter.schema.registry.url": "http://schema-registry:8081",
    "value.converter.schemas.enable": "true",
    "transforms": "SetValueSchema",
    "transforms.SetValueSchema.type": "org.apache.kafka.connect.transforms.SetSchemaMetadata$Value",
    "transforms.SetValueSchema.schema.name": "io.confluent.developer.avro.City",
    "tasks.max": "1"
  }
}

Run the JDBC source connector:

curl -X POST -H Accept:application/json -H Content-Type:application/json http://localhost:8083/connectors/ -d @jdbc_source.config

7
Create the Kafka Streams topology

Create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer/connect/jdbc/specificavro

Then create the following file at src/main/java/io/confluent/developer/connect/jdbc/specificavro/StreamsIngest.java. Let’s take a close look at the buildTopology() method, which uses the Kafka Streams DSL.

The first thing the method does is build a stream from the input topic. It uses the SpecificAvroSerde<> to create a KStream called citiesNoKey that has no message key and a message value of type City.

Next, using the map method, it extracts a field in the message value that corresponds to the city ID, and assigns it as the message key. It results in a KStream called citiesKeyed that has a message key of type Long and a message value of type City.

Finally this is written to the output topic using the to method.

package io.confluent.developer.connect.jdbc.specificavro;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import io.confluent.developer.avro.City;
import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

public class StreamsIngest {

  public Properties buildStreamsProperties(Properties envProps) {
    Properties props = new Properties();

    //props.put(StreamsConfig.APPLICATION_ID_CONFIG, envProps.getProperty("application.id"));
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "foo2");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, envProps.getProperty("bootstrap.servers"));
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
    props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);

    return props;
  }

  private SpecificAvroSerde<City> citySerde(final Properties envProps) {
    final SpecificAvroSerde<City> serde = new SpecificAvroSerde<>();
    Map<String, String> config = new HashMap<>();
    config.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, envProps.getProperty("schema.registry.url"));
    serde.configure(config, false);
    return serde;
  }

  public Topology buildTopology(Properties envProps,
                                final SpecificAvroSerde<City> citySerde) {
    final StreamsBuilder builder = new StreamsBuilder();

    final String inputTopic = envProps.getProperty("input.topic.name");
    final String outputTopic = envProps.getProperty("output.topic.name");

    KStream<String, City> citiesNoKey = builder.stream(inputTopic, Consumed.with(Serdes.String(), citySerde));
    final KStream<Long, City> citiesKeyed = citiesNoKey.map((k, v) -> new KeyValue<>(v.getCityId(), v));
    citiesKeyed.to(outputTopic, Produced.with(Serdes.Long(), citySerde));

    return builder.build();
  }

  public void createTopics(Properties envProps) {
    Map<String, Object> config = new HashMap<>();
    config.put("bootstrap.servers", envProps.getProperty("bootstrap.servers"));
    AdminClient client = AdminClient.create(config);

    List<NewTopic> topics = new ArrayList<>();
    topics.add(new NewTopic(
        envProps.getProperty("input.topic.name"),
        Integer.parseInt(envProps.getProperty("input.topic.partitions")),
        Short.parseShort(envProps.getProperty("input.topic.replication.factor"))));
    topics.add(new NewTopic(
        envProps.getProperty("output.topic.name"),
        Integer.parseInt(envProps.getProperty("output.topic.partitions")),
        Short.parseShort(envProps.getProperty("output.topic.replication.factor"))));

    client.createTopics(topics);
    client.close();
  }

  public Properties loadEnvProperties(String fileName) throws IOException {
    Properties envProps = new Properties();
    FileInputStream input = new FileInputStream(fileName);
    envProps.load(input);
    input.close();

    return envProps;
  }

  public static void main(String[] args) throws IOException {
    if (args.length < 1) {
      throw new IllegalArgumentException(
          "This program takes one argument: the path to an environment configuration file.");
    }

    new StreamsIngest().runRecipe(args[0]);
  }

  private void runRecipe(final String configPath) throws IOException {
    Properties envProps = this.loadEnvProperties(configPath);
    Properties streamProps = this.buildStreamsProperties(envProps);

    Topology topology = this.buildTopology(envProps, this.citySerde(envProps));
    this.createTopics(envProps);

    final KafkaStreams streams = new KafkaStreams(topology, streamProps);
    final CountDownLatch latch = new CountDownLatch(1);

    // Attach shutdown handler to catch Control-C.
    Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
      @Override
      public void run() {
        streams.close();
        latch.countDown();
      }
    });

    try {
      streams.start();
      latch.await();
    } catch (Throwable e) {
      System.exit(1);
    }
    System.exit(0);

  }
}

8
Compile and run the Kafka Streams program

In your terminal, run:

./gradlew shadowJar

Now that you have an uberjar for the Kafka Streams application, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it. There is always another message to process, so streaming applications don’t exit until you force them.

java -jar build/libs/connect-add-key-to-source-0.0.1-standalone.jar configuration/dev.properties

9
Consume events from the input topic and output topic

Run the Avro console consumer to view the messages in the topic cities. This is the topic that the JDBC source connector writes to, and note that the keys are null:

docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic cities --bootstrap-server broker:9092 --from-beginning --property schema.registry.url=http://localhost:8081 --property print.key=true --property key.deserializer=org.apache.kafka.common.serialization.LongDeserializer --timeout-ms 20000

Next, run the Avro console consumer to view the messages in the topic cities_keyed. This is the output topic that the Kafka Streams application creates from the input topic cities, and note that it has added the keys:

docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic cities_keyed --bootstrap-server broker:9092 --from-beginning --property schema.registry.url=http://localhost:8081 --property print.key=true --property key.deserializer=org.apache.kafka.common.serialization.LongDeserializer --timeout-ms 20000

Test it

1
Create a test configuration file

First, create a test file at configuration/test.properties:

application.id=cities_ingestion
bootstrap.servers=127.0.0.1:9092
schema.registry.url=http://SR_CLOUD_DUMMY_URL:8081

input.topic.name=cities
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=cities_keyed
output.topic.partitions=1
output.topic.replication.factor=1

2
Write a test

Then, create a directory for the tests to live in:

mkdir -p src/test/java/io/confluent/developer/connect/jdbc/specificavro

Create the following test file at src/test/java/io/confluent/developer/connect/jdbc/specificavro/StreamsIngestTest.java:

package io.confluent.developer.connect.jdbc.specificavro;

import org.apache.avro.Schema;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.test.ConsumerRecordFactory;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import io.confluent.developer.avro.City;
import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

import static java.util.Arrays.asList;

public class StreamsIngestTest {

  private final static String TEST_CONFIG_FILE = "configuration/test.properties";

  private SpecificAvroSerde<City> makeSerializer(Properties envProps)
      throws IOException, RestClientException {

    final MockSchemaRegistryClient client = new MockSchemaRegistryClient();
    String inputTopic = envProps.getProperty("input.topic.name");
    String outputTopic = envProps.getProperty("output.topic.name");

    final Schema schema = City.SCHEMA$;
    client.register(inputTopic + "-value", schema);
    client.register(outputTopic + "-value", schema);

    SpecificAvroSerde<City> serde = new SpecificAvroSerde<>(client);

    Map<String, String> config = new HashMap<>();
    config.put("schema.registry.url", envProps.getProperty("schema.registry.url"));
    serde.configure(config, false);

    return serde;
  }

  @Test
  public void shouldCreateKeyedStream() throws IOException, RestClientException {
    StreamsIngest si = new StreamsIngest();
    Properties envProps = si.loadEnvProperties(TEST_CONFIG_FILE);
    Properties streamProps = si.buildStreamsProperties(envProps);

    String inputTopic = envProps.getProperty("input.topic.name");
    String outputTopic = envProps.getProperty("output.topic.name");

    final SpecificAvroSerde<City> citySpecificAvroSerde = makeSerializer(envProps);

    Topology topology = si.buildTopology(envProps, citySpecificAvroSerde);
    TopologyTestDriver testDriver = new TopologyTestDriver(topology, streamProps);

    Serializer<String> keySerializer = Serdes.String().serializer();
    Deserializer<Long> keyDeserializer = Serdes.Long().deserializer();

    ConsumerRecordFactory<String, City>
        inputFactory =
        new ConsumerRecordFactory<>(keySerializer, citySpecificAvroSerde.serializer());

    // Fixture
    City c1 = new City(1L, "Raleigh", "NC");
    City c2 = new City(2L, "Mountain View", "CA");
    City c3 = new City(3L, "Knoxville", "TN");
    City c4 = new City(4L, "Houston", "TX");
    City c5 = new City(5L, "Olympia", "WA");
    City c6 = new City(6L, "Bismarck", "ND");
    // end Fixture

    final List<City>
        input = asList(c1, c2, c3, c4, c5, c6);

    final List<Long> expectedOutput = asList(1L, 2L, 3L, 4L, 5L, 6L);

    for (City city : input) {
      testDriver.pipeInput(inputFactory.create(inputTopic, null, city));
    }

    List<Long> actualOutput = new ArrayList<>();
    while (true) {
      ProducerRecord<Long, City>
          record =
          testDriver.readOutput(outputTopic, keyDeserializer, citySpecificAvroSerde.deserializer());

      if (record != null) {
        actualOutput.add(record.key());
      } else {
        break;
      }
    }

    Assert.assertEquals(expectedOutput, actualOutput);
  }

}

3
Invoke the tests

Now run the test, which is as simple as:

./gradlew test

Take it to production

1
Create a production configuration file

First, create a new configuration file at configuration/prod.properties with the following content. Be sure to fill in the addresses of your production hosts and change any other parameters that make sense for your setup.

application.id=cities_ingestion
bootstrap.servers=<< FILL ME IN >>
schema.registry.url=<< FILL ME IN >>

input.topic.name=cities
input.topic.partitions=<< FILL ME IN >>
input.topic.replication.factor=<< FILL ME IN >>

output.topic.name=cities_keyed
output.topic.partitions=<< FILL ME IN >>
output.topic.replication.factor=<< FILL ME IN >>

2
Build a Docker image

In your terminal, execute the following to invoke the Jib plugin to build an image:

./gradlew jibDockerBuild --image=io.confluent.developer/connect-add-key-to-source:0.0.1

3
Launch the container

Finally, launch the container using your preferred container orchestration service. If you want to run it locally, you can execute the following:

docker run -v $PWD/configuration/prod.properties:/config.properties io.confluent.developer/connect-add-key-to-source:0.0.1 config.properties

Deploy on Confluent Cloud

1
Run your app to Confluent Cloud

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

First, create your Kafka cluster in Confluent Cloud. Use the promo code C50INTEG to receive an additional $50 free usage (details).

Next, from the Confluent Cloud UI, click on Tools & client config 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 your run application locally while your Kafka topics and stream processing is backed to your Confluent Cloud instance.