How to build a User-Defined Function (UDF) to transform events

Question:

How can you transform the values of a Kafka topic using a stateless scalar function not already provided by ksqlDB?

Edit this page

Example use case:

Consider a topic of stock price events. You want to calculate the volume-weighted average price (VWAP) for each event, publishing the result to a new topic. There is no built-in function for VWAP, so we'll write a custom KSQL user-defined function (UDF) that performs the calculation.

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 udf && cd udf

Then make the following directories:

mkdir src extensions

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

buildscript {
    repositories {
        mavenCentral()
    }
}

plugins {
    id "java"
}

// Use Java 11 since CP Docker images package Java 11 as of CP 7.3.x
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
version = "0.0.1"

repositories {
    mavenCentral()


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

dependencies {
    implementation 'io.confluent.ksql:ksql-udf:5.4.11'
    testImplementation 'junit:junit:4.13.2'
}

task copyJar(type: Copy) {
    from jar
    into "extensions/"
}

build.dependsOn copyJar

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

The build.gradle also contains a copyJar step to copy the jar file to the extensions/ directory where it will be picked up by KSQL. This is convenient when you are iterating on a function. For example, you might have tested your UDF against your suite of unit tests and you are now ready to test against streams in KSQL. With the jar in the correct place, a restart of KSQL will load your updated jar.

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

gradle wrapper

Implement the KSQL User-Defined Function

3

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/VwapUdf.java. This file contains the Java logic of your custom function. Read through the code to familiarize yourself.

package io.confluent.developer;

import io.confluent.ksql.function.udf.Udf;
import io.confluent.ksql.function.udf.UdfDescription;
import io.confluent.ksql.function.udf.UdfParameter;

@UdfDescription(name = "vwap", description = "Volume weighted average price")
public class VwapUdf {

    @Udf(description = "vwap for market prices as integers, returns double")
    public double vwap(
            @UdfParameter(value = "bid")
            final int bid,
            @UdfParameter(value = "bidQty")
            final int bidQty,
            @UdfParameter(value = "ask")
            final int ask,
            @UdfParameter(value = "askQty")
            final int askQty) {
        return ((ask * askQty) + (bid * bidQty)) / (bidQty + askQty);
    }

    @Udf(description = "vwap for market prices as doubles, returns double")
    public double vwap(
            @UdfParameter(value = "bid")
            final double bid,
            @UdfParameter(value = "bidQty")
            final int bidQty,
            @UdfParameter(value = "ask")
            final double ask,
            @UdfParameter(value = "askQty")
            final int askQty) {
        return ((ask * askQty) + (bid * bidQty)) / (bidQty + askQty);
    }
}

Here we have created a new Class which defines two functions, both of which are annotated with Udf, indicating they are ksqlDB UDF function definitions. Both functions take parameters of type double or int and produce a single result of type double, representing the calculated volume-weighted average price of the inputs.

Build the JAR

4

In your terminal, run:

./gradlew build

The copyJar gradle task will automatically deliver the jar to the extensions/ directory.

Get Confluent Platform

5

Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):

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-server
    container_name: ksqldb-server
    depends_on:
    - broker
    - schema-registry
    volumes:
    - ./extensions:/etc/ksqldb/ext
    ports:
    - 8088:8088
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
      KSQL_KSQL_EXTENSION_DIR: /etc/ksqldb/ext/
      KSQL_LOG4J_OPTS: -Dlog4j.configuration=file:/etc/ksqldb/log4j.properties
      KSQL_BOOTSTRAP_SERVERS: broker:9092
      KSQL_HOST_NAME: ksqldb-server
      KSQL_LISTENERS: http://0.0.0.0:8088
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: http://schema-registry:8081
  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
    - ./test:/opt/app/test

Note docker-compose.yml has configured the ksql-server container with KSQL_KSQL_EXTENSION_DIR: "/etc/ksql/ext/", mapping the local extensions directory to /etc/ksql/ext in the container. KSQL is now configured to look in this location for your extensions such as custom functions.

Launch the platform by running:

docker compose up -d

Write the program interactively using the CLI

6

To begin developing interactively, open up the ksqlDB CLI:

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

Let’s confirm the UDF jar has been loaded correctly. You will see VWAP in the list of functions.

SHOW FUNCTIONS;

You can see some additional detail about the function with DESCRIBE FUNCTION.

DESCRIBE FUNCTION VWAP;

The result gives you a description of the function including input parameters and the return type.

Name        : VWAP
Overview    : Volume weighted average price
Type        : SCALAR
Jar         : /etc/ksqldb/ext/udf-0.0.1.jar
Variations  :

	Variation   : VWAP(bid DOUBLE, bidQty INT, ask DOUBLE, askQty INT)
	Returns     : DOUBLE
	Description : vwap for market prices as doubles, returns double

	Variation   : VWAP(bid INT, bidQty INT, ask INT, askQty INT)
	Returns     : DOUBLE
	Description : vwap for market prices as integers, returns double

You’ll need to create a Kafka topic and stream to represent the stock quote stream. The following creates both in one shot:

CREATE STREAM raw_quotes(ticker varchar key, bid int, ask int, bidqty int, askqty int)
    WITH (kafka_topic='stockquotes', value_format='avro', partitions=1);

Then produce the following events to the stream:

INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZTEST', 15, 25, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVV',   25, 35, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVZZT', 35, 45, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZXZZT', 45, 55, 100, 100);

INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZTEST', 10, 20, 50, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVV',   30, 40, 100, 50);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVZZT', 30, 40, 50, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZXZZT', 50, 60, 100, 50);

INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZTEST', 15, 20, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVV',   25, 35, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZVZZT', 35, 45, 100, 100);
INSERT INTO raw_quotes (ticker, bid, ask, bidqty, askqty) VALUES ('ZXZZT', 45, 55, 100, 100);

Now that you have stream with some events in it, let’s read them out. The first thing to do is set the following properties to ensure that you’re reading from the beginning of the stream:

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

Let’s invoke the vwap function for every observed raw quote. Pay attention to the parameter ordering of the UDF when invoking from the ksqlDB syntax.

SELECT ticker, vwap(bid, bidqty, ask, askqty) AS vwap FROM raw_quotes EMIT CHANGES LIMIT 12;

This should yield the following output:

+--------------------+--------------------+
|TICKER              |VWAP                |
+--------------------+--------------------+
|ZTEST               |20.0                |
|ZVV                 |30.0                |
|ZVZZT               |40.0                |
|ZXZZT               |50.0                |
|ZTEST               |16.0                |
|ZVV                 |33.0                |
|ZVZZT               |36.0                |
|ZXZZT               |53.0                |
|ZTEST               |17.0                |
|ZVV                 |30.0                |
|ZVZZT               |40.0                |
|ZXZZT               |50.0                |
Limit Reached
Query terminated

Since the output looks right, the next step is to make the query continuous. Issue the following to create a new stream that is continuously populated by its query:

CREATE STREAM vwap WITH (kafka_topic = 'vwap', partitions = 1) AS
    SELECT ticker,
           vwap(bid, bidqty, ask, askqty) AS vwap
    FROM raw_quotes
    EMIT CHANGES;

To check that it’s working, print out the contents of the output stream’s underlying topic:

PRINT vwap FROM BEGINNING LIMIT 12;

This should yield the following output:

Key format: KAFKA_STRING
Value format: AVRO
rowtime: 2020/05/04 23:03:23.467 Z, key: ZTEST, value: {"VWAP": 20.0}, partition: 0
rowtime: 2020/05/04 23:03:23.672 Z, key: ZVV, value: {"VWAP": 30.0}, partition: 0
rowtime: 2020/05/04 23:03:23.801 Z, key: ZVZZT, value: {"VWAP": 40.0}, partition: 0
rowtime: 2020/05/04 23:03:23.967 Z, key: ZXZZT, value: {"VWAP": 50.0}, partition: 0
rowtime: 2020/05/04 23:03:24.100 Z, key: ZTEST, value: {"VWAP": 16.0}, partition: 0
rowtime: 2020/05/04 23:03:24.399 Z, key: ZVV, value: {"VWAP": 33.0}, partition: 0
rowtime: 2020/05/04 23:03:24.551 Z, key: ZVZZT, value: {"VWAP": 36.0}, partition: 0
rowtime: 2020/05/04 23:03:24.705 Z, key: ZXZZT, value: {"VWAP": 53.0}, partition: 0
rowtime: 2020/05/04 23:03:24.844 Z, key: ZTEST, value: {"VWAP": 17.0}, partition: 0
rowtime: 2020/05/04 23:03:24.980 Z, key: ZVV, value: {"VWAP": 30.0}, partition: 0
rowtime: 2020/05/04 23:03:25.096 Z, key: ZVZZT, value: {"VWAP": 40.0}, partition: 0
rowtime: 2020/05/04 23:03:25.400 Z, key: ZXZZT, value: {"VWAP": 50.0}, partition: 0
Topic printing ceased

Write your statements to a file

7

Now that you have a series of statements that’s doing the right thing, the last step is to put them into a file so that they can be used outside the CLI session. Create a file at src/statements.sql with the following content:

CREATE STREAM raw_quotes(ticker varchar key, bid int, ask int, bidqty int, askqty int)
    WITH (kafka_topic='stockquotes', value_format='avro', partitions=1);

CREATE STREAM vwap WITH (kafka_topic = 'vwap', partitions = 1) AS
    SELECT ticker,
           vwap(bid, bidqty, ask, askqty) AS vwap
    FROM raw_quotes;

Test it

Write a test

1

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/VwapUdfTest.java:

package io.confluent.developer;

import static org.junit.Assert.*;
import org.junit.Test;

public class VwapUdfTest {

    @Test
    public void testVwapAllInts() {
        assertEquals(100D,
                new VwapUdf().vwap(95, 100, 105, 100),
               0D);
    }
    @Test
    public void testVwap() {
        assertEquals(100D,
                new VwapUdf().vwap(95D, 100, 105D, 100),
                0D);
    }
}

Invoke the tests

2

Now run the test, which is as simple as:

./gradlew test

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.