How to transform a stream of events

Question:

How do I transform a field in a stream of events in a Kafka topic?

Edit this page

Example use case:

Consider a topic with events that represent movies. Each event has a single attribute that combines its title and its release year into a string. In this tutorial, we'll write a program that creates a new topic with the title and release date turned into their own attributes.

Code example:





Short Answer

Use the map() method to take each input record and create a new stream with transformed records in it. The records are transformed via a custom function, in this case convertRawMovie().

KStream<Long, Movie> movies = rawMovies.map((key, rawMovie) ->
                                                new KeyValue<>(rawMovie.getId(), convertRawMovie(rawMovie)));

Try it

1
Initialize the project

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

mkdir transform-stream && cd transform-stream

Next, create a directory for configuration data:

mkdir configuration

2
Sign up for Confluent Cloud and provision resources

Sign up for Confluent Cloud, a fully-managed Apache Kafka service. Then provision your resources:

  1. After you log in to Confluent Cloud, 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.

  2. From the Billing & payment section in the Menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details).

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

Confluent Cloud

3
Create a properties file with Confluent Cloud information

From the Confluent Cloud UI, navigate to your Kafka cluster and click on Clients and then select Java.

Create new credentials for your Kafka cluster and Schema Registry, and then Confluent Cloud will show a configuration similar to below with your new credentials automatically populated (make sure show API keys is checked). Copy and paste it into a configuration/ccloud.properties file on your machine.

# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BOOTSTRAP_SERVERS }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule   required username='{{ CLUSTER_API_KEY }}'   password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips

# Best practice for Kafka producer to prevent data loss
acks=all

# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url={{ SR_URL }}
basic.auth.credentials.source=USER_INFO
basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Do not directly copy and paste the above configuration. You must copy it from the UI so that it includes your Confluent Cloud information and credentials.

4
Download and setup the Confluent Cloud CLI

Instructions for installing Confluent Cloud CLI and configuring it to your Confluent Cloud environment is available from within the Confluent Cloud UI. Navigate to your Kafka cluster, click on the CLI and tools section, and run through the steps in the CCloud CLI tab.

5
Configure the project

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

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.commercehub.gradle.plugin:gradle-avro-plugin:0.22.0'
    classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.2'
  }
}

plugins {
  id 'java'
  id 'com.google.cloud.tools.jib' version '2.8.0'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '0.0.1'

repositories {
  mavenCentral()


  maven {
    url 'https://packages.confluent.io/maven'
  }
}

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

dependencies {
  implementation 'org.apache.avro:avro:1.10.2'
  implementation 'org.slf4j:slf4j-simple:1.7.30'
  implementation 'org.apache.kafka:kafka-streams:2.7.0'
  implementation 'io.confluent:kafka-streams-avro-serde:6.1.1'
  testImplementation 'org.apache.kafka:kafka-streams-test-utils:2.7.0'
  testImplementation 'junit:junit:4.13.2'
}

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

task run(type: JavaExec) {
  main = 'io.confluent.developer.TransformStream'
  classpath = sourceSets.main.runtimeClasspath
  args = ['configuration/dev.properties']
}

jar {
  manifest {
    attributes(
        'Class-Path': configurations.compileClasspath.collect { it.getName() }.join(' '),
        'Main-Class': 'io.confluent.developer.TransformStream'
    )
  }
}

shadowJar {
  archiveBaseName = "kstreams-transform-standalone"
  archiveClassifier = ''
}

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

gradle wrapper

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

application.id=transforming-app
replication.factor=3

input.topic.name=raw-movies
input.topic.partitions=6
input.topic.replication.factor=3

output.topic.name=movies
output.topic.partitions=6
output.topic.replication.factor=3

6
Update the properties file with Confluent Cloud information

Using the command below, append the contents of configuration/ccloud.properties (with your Confluent Cloud configuration) to configuration/dev.properties (with the application properties).

cat configuration/ccloud.properties >> configuration/dev.properties

7
Create a schema for the events

Create a directory for the schemas that represent the events in the stream:

mkdir -p src/main/avro

Then create the following Avro schema file at src/main/avro/input_movie_event.avsc for the raw movies:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "RawMovie",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "title", "type": "string"},
    {"name": "genre", "type": "string"}
  ]
}

While you’re at it, create another Avro schema file at src/main/avro/parsed_movies.avsc for the transformed movies:

{
  "namespace": "io.confluent.developer.avro",
  "type": "record",
  "name": "Movie",
  "fields": [
    {"name": "id", "type": "long"},
    {"name": "title", "type": "string"},
    {"name": "release_year", "type": "int"},
    {"name": "genre", "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 files, generate Java code for them, and compile those and all other Java sources. Run this command to get it all done:

./gradlew build

8
Create the Kafka Streams topology

Create a directory for the Java files in this project:

mkdir -p src/main/java/io/confluent/developer

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

The first thing the method does is create an instance of StreamsBuilder, which is the helper object that lets us build our topology. Next we call the stream() method, which creates a KStream object (called rawMovies in this case) out of an underlying Kafka topic. Note the type of that stream is Long, RawMovie, because the topic contains the raw movie objects we want to transform. RawMovie’s title field contains the title and the release year together, which we want to make into separate fields in a new object.

We get that transforming work done with the next line, which is a call to the map() method. map() takes each input record and creates a new stream with transformed records in it. Its parameter is a single Java Lambda that takes the input key and value and returns an instance of the KeyValue class with the new record in it. This does two things. First, it rekeys the incoming stream, using the movieId as the key. We don’t absolutely need to do that to accomplish the transformation, but it’s easy enough to do at the same time, and it sets a useful key on the output stream, which is generally a good idea. Second, it calls the convertRawMovie() method to turn the RawMovie value into a Movie. This is the essence of the transformation. The convertRawMovie() method contains the sort of unpleasant string parsing that is a part of many stream processing pipelines, which we are happily able to encapsulate in a single, easily testable method. Any further stages we might build in the pipeline after this point are blissfully unaware that we ever had a string to parse in the first place.

Moreover, it’s worth noting that we’re calling map() and not mapValues():

package io.confluent.developer;

import java.time.Duration;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
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.KStream;
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.Movie;
import io.confluent.developer.avro.RawMovie;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;

public class TransformStream {

    public Topology buildTopology(Properties allProps) {
        final StreamsBuilder builder = new StreamsBuilder();
        final String inputTopic = allProps.getProperty("input.topic.name");

        KStream<String, RawMovie> rawMovies = builder.stream(inputTopic);
        KStream<Long, Movie> movies = rawMovies.map((key, rawMovie) ->
                                                        new KeyValue<>(rawMovie.getId(), convertRawMovie(rawMovie)));

        movies.to("movies", Produced.with(Serdes.Long(), movieAvroSerde(allProps)));

        return builder.build();
    }

    public static Movie convertRawMovie(RawMovie rawMovie) {
        String[] titleParts = rawMovie.getTitle().split("::");
        String title = titleParts[0];
        int releaseYear = Integer.parseInt(titleParts[1]);
        return new Movie(rawMovie.getId(), title, releaseYear, rawMovie.getGenre());
    }

    private SpecificAvroSerde<Movie> movieAvroSerde(Properties allProps) {
        SpecificAvroSerde<Movie> movieAvroSerde = new SpecificAvroSerde<>();
        movieAvroSerde.configure((Map)allProps, false);
        return movieAvroSerde;
    }

    public void createTopics(Properties allProps) {
        AdminClient client = AdminClient.create(allProps);

        List<NewTopic> topics = new ArrayList<>();

        topics.add(new NewTopic(
                allProps.getProperty("input.topic.name"),
                Integer.parseInt(allProps.getProperty("input.topic.partitions")),
                Short.parseShort(allProps.getProperty("input.topic.replication.factor"))));

        topics.add(new NewTopic(
                allProps.getProperty("output.topic.name"),
                Integer.parseInt(allProps.getProperty("output.topic.partitions")),
                Short.parseShort(allProps.getProperty("output.topic.replication.factor"))));

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

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

        return allProps;
    }

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

        TransformStream ts = new TransformStream();
        Properties allProps = ts.loadEnvProperties(args[0]);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
        Topology topology = ts.buildTopology(allProps);

        ts.createTopics(allProps);

        final KafkaStreams streams = new KafkaStreams(topology, allProps);
        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(Duration.ofSeconds(5));
                latch.countDown();
            }
        });

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

9
Compile and run the Kafka Streams program

In your terminal, run:

./gradlew shadowJar

Now that an uberjar for the Kafka Streams application has been built, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it:

java -jar build/libs/kstreams-transform-standalone-0.0.1.jar configuration/dev.properties

10
Produce events to the input topic

In a new terminal, run:

ccloud kafka topic produce raw-movies \
      --value-format avro \
      --schema src/main/avro/input_movie_event.avsc

You will be prompted for the Confluent Cloud Schema Registry credentials as shown below, which you can find in the configuration/ccloud.properties configuration file. Look for the configuration parameter basic.auth.user.info, whereby the ":" is the delimiter between the key and secret.

Enter your Schema Registry API key:
Enter your Schema Registry API secret:

When the console producer starts, it will log some messages and hang, waiting for your input. Type in one line at a time and press enter to send it. Each line represents an event. To send all of the events below, paste the following into the prompt and press enter:

{"id": 294, "title": "Die Hard::1988", "genre": "action"}
{"id": 354, "title": "Tree of Life::2011", "genre": "drama"}
{"id": 782, "title": "A Walk in the Clouds::1995", "genre": "romance"}
{"id": 128, "title": "The Big Lebowski::1998", "genre": "comedy"}

11
Observe the transformed movies in the output topic

Leave your original terminal running. To consume the events produced by your Streams application you’ll need another terminal open.

First, to consume the events of drama films, run the following:

ccloud kafka topic consume movies \
      --from-beginning \
      --value-format avro

This should yield the following messages:

{"id":294,"title":"Die Hard","release_year":1988,"genre":"action"}
{"id":354,"title":"Tree of Life","release_year":2011,"genre":"drama"}
{"id":782,"title":"A Walk in the Clouds","release_year":1995,"genre":"romance"}
{"id":128,"title":"The Big Lebowski","release_year":1998,"genre":"comedy"}

12
Teardown Confluent Cloud resources

You may try another Kafka tutorial, but if you don’t plan on doing other tutorials, use the Confluent Cloud UI or CLI to destroy all the resources you created. Verify they are destroyed to avoid unexpected charges.

Test it

1
Create a test configuration file

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

application.id=transforming-app
bootstrap.servers=127.0.0.1:29092
schema.registry.url=mock://transforming-app:8081

input.topic.name=raw-movies
input.topic.partitions=1
input.topic.replication.factor=1

output.topic.name=movies
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

Create the following test file at src/test/java/io/confluent/developer/TransformStreamTest.java. Testing a Kafka streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver class makes this much more pleasant that it would otherwise be.

There are two methods in TransformStreamTest annotated with @Test: testMovieConverter() and testTransformStream(). testMovieConverter() is a simple method that tests the string that is core to the transformation action of this Streams application. testMovieConverter() actually runs our Streams topology using the TopologyTestDriver and some mocked data that is set up inside the test method.

package io.confluent.developer;

import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
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.StreamsConfig;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.After;
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.Objects;
import java.util.Properties;
import java.util.stream.Collectors;

import io.confluent.developer.avro.Movie;
import io.confluent.developer.avro.RawMovie;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroDeserializer;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class TransformStreamTest {

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

    public SpecificAvroSerializer<RawMovie> makeSerializer(Properties allProps) {
        SpecificAvroSerializer<RawMovie> serializer = new SpecificAvroSerializer<>();

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

        return serializer;
    }

    public SpecificAvroDeserializer<Movie> makeDeserializer(Properties allProps) {
        SpecificAvroDeserializer<Movie> deserializer = new SpecificAvroDeserializer<>();

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

        return deserializer;
    }

    private List<Movie> readOutputTopic(TopologyTestDriver testDriver,
                                        String topic,
                                        Deserializer<String> keyDeserializer,
                                        SpecificAvroDeserializer<Movie> valueDeserializer) {

        return testDriver
            .createOutputTopic(topic, keyDeserializer, valueDeserializer)
            .readKeyValuesToList()
            .stream()
            .filter(Objects::nonNull)
            .map(record -> record.value)
            .collect(Collectors.toList());
    }

    @Test
    public void testMovieConverter() {
        Movie movie;

        movie = TransformStream.convertRawMovie(new RawMovie(294L, "Tree of Life::2011", "drama"));
        assertNotNull(movie);
        assertEquals(294L, movie.getId());
        assertEquals("Tree of Life", movie.getTitle());
        assertEquals(2011, movie.getReleaseYear());
        assertEquals("drama", movie.getGenre());
    }


    @Test
    public void testTransformStream() throws IOException {
        TransformStream ts = new TransformStream();
        Properties allProps = ts.loadEnvProperties(TEST_CONFIG_FILE);
        allProps.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        allProps.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);

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

        Topology topology = ts.buildTopology(allProps);
        testDriver = new TopologyTestDriver(topology, allProps);

        Serializer<String> keySerializer = Serdes.String().serializer();
        SpecificAvroSerializer<RawMovie> valueSerializer = makeSerializer(allProps);

        Deserializer<String> keyDeserializer = Serdes.String().deserializer();
        SpecificAvroDeserializer<Movie> valueDeserializer = makeDeserializer(allProps);

        List<RawMovie> input = new ArrayList<>();
        input.add(RawMovie.newBuilder().setId(294).setTitle("Die Hard::1988").setGenre("action").build());
        input.add(RawMovie.newBuilder().setId(354).setTitle("Tree of Life::2011").setGenre("drama").build());
        input.add(RawMovie.newBuilder().setId(782).setTitle("A Walk in the Clouds::1995").setGenre("romance").build());
        input.add(RawMovie.newBuilder().setId(128).setTitle("The Big Lebowski::1998").setGenre("comedy").build());

        List<Movie> expectedOutput = new ArrayList<>();
        expectedOutput.add(Movie.newBuilder().setTitle("Die Hard").setId(294).setReleaseYear(1988).setGenre("action").build());
        expectedOutput.add(Movie.newBuilder().setTitle("Tree of Life").setId(354).setReleaseYear(2011).setGenre("drama").build());
        expectedOutput.add(Movie.newBuilder().setTitle("A Walk in the Clouds").setId(782).setReleaseYear(1995).setGenre("romance").build());
        expectedOutput.add(Movie.newBuilder().setTitle("The Big Lebowski").setId(128).setReleaseYear(1998).setGenre("comedy").build());

        final TestInputTopic<String, RawMovie>
            testDriverInputTopic =
            testDriver.createInputTopic(inputTopic, keySerializer, valueSerializer);

        for (RawMovie rawMovie : input) {
            testDriverInputTopic.pipeInput(rawMovie.getTitle(), rawMovie);
        }
        List<Movie> actualOutput = readOutputTopic(testDriver, outputTopic, keyDeserializer, valueDeserializer);

        assertEquals(expectedOutput, actualOutput);
    }

    @After
    public void cleanup() {
        if (testDriver != null) {
            testDriver.close();
        }
    }

}

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=transforming-app
bootstrap.servers=<< FILL ME IN >>
schema.registry.url=<< FILL ME IN >>

input.topic.name=raw-movies
input.topic.partitions=<< FILL ME IN >>
input.topic.replication.factor=<< FILL ME IN >>

output.topic.name=movies
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:

gradle jibDockerBuild --image=io.confluent.developer/kstreams-transform: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/kstreams-transform:0.0.1 config.properties