Timezone conversion and Kafka Connect JDBC sink

Question:

How can I convert a timestamp into a different timezone and sync that data to Postgres?

Edit this page

Example use case:

Consider the requirement to create reports from a database, for which all of the timestamps must be in a timezone which happens to be different from the timezone of the Kafka data source. This examples shows how you can convert timestamp data into another timezone and use a Kafka connector to send that data to Postgres database.

Code example:





Short Answer

First use the ksqlDB function FROM_UNIXTIME to convert a data field type from BIGINT to TIMESTAMP, then use the ksqlDB function CONVERT_TZ to change the timestamp to the desired timezone.

CREATE STREAM TEMPERATURE_READINGS_TIMESTAMP_MT AS
SELECT TEMPERATURE, CONVERT_TZ(FROM_UNIXTIME(EVENTTIME), 'UTC', 'America/Denver') AS EVENTTIME_MT
FROM TEMPERATURE_READINGS_RAW;

Afterward, deploy a sink connector that reads from the ksqlDB output topic with the converted timezone data and writes to the target database.

CREATE SINK CONNECTOR JDBC_SINK_POSTGRES_01 WITH (
    'connector.class'     = 'io.confluent.connect.jdbc.JdbcSinkConnector',
    'connection.url'      = 'jdbc:postgresql://postgres:5432/',
    'connection.user'     = 'postgres',
    'connection.password' = 'postgres',
    'topics'              = 'TEMPERATURE_READINGS_TIMESTAMP_MT',
    'auto.create'         = 'true',
    'auto.evolve'         = 'true'
  );

Try it

1
Initialize the project

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

mkdir connect-sink-timestamp && cd connect-sink-timestamp

2
Set up environment

Next create the following docker-compose.yml file. In this file we obtain the Confluent Platform, setup a postgres database, configure an embedded connect worker in ksqlDB and install a JDBC connector package from Confluent Hub.

---
version: '2'

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

  broker:
    image: confluentinc/cp-kafka:6.1.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_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

  schema-registry:
    image: confluentinc/cp-schema-registry:6.1.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.17.0
    hostname: ksqldb-server
    container_name: ksqldb-server
    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_01
      KSQL_KSQL_HIDDEN_TOPICS: '^_.*'
      KSQL_KSQL_STREAMS_AUTO_OFFSET_RESET: "earliest"
      # Setting KSQL_KSQL_CONNECT_WORKER_CONFIG enables embedded Kafka Connect
      KSQL_KSQL_CONNECT_WORKER_CONFIG: "/connect/connect.properties"
      # Kafka Connect config below
      KSQL_CONNECT_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_CONNECT_REST_ADVERTISED_HOST_NAME: 'ksqldb'
      KSQL_CONNECT_REST_PORT: 8083
      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:
      # In the command section, $ are replaced with $$ to avoid the error 'Invalid interpolation format for "command" option'
      - bash
      - -c
      - |
        echo "Installing connector plugins"
        mkdir -p ~/confluent-hub-components/
        /home/appuser/bin/confluent-hub install --no-prompt --component-dir confluent-hub-components/ confluentinc/kafka-connect-jdbc:10.0.2
        #
        echo "Launching ksqlDB"
        /usr/bin/docker/run &
        #
        sleep infinity

  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.17.0
    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

  postgres:
    # *-----------------------------*
    # To connect to the DB:
    #   docker exec -it postgres bash -c 'psql -U $POSTGRES_USER $POSTGRES_DB'
    # *-----------------------------*
    image: postgres:13
    container_name: postgres
    environment:
     - POSTGRES_USER=postgres
     - POSTGRES_PASSWORD=postgres

And launch it by running:

docker-compose up -d

3
Convert column to TIMESTAMP data type

The best way to interact with ksqlDB when you’re learning how things work is with the ksqlDB CLI. Fire it up as follows:

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

Before we get too far, let’s set the auto.offset.reset configuration parameter to earliest. This means all new ksqlDB queries will automatically compute their results from the beginning of a stream, rather than the end. This isn’t always what you’ll want to do in production, but it makes query results much easier to see in examples like this.

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

We will create a stream to model some sample data with this command.

CREATE STREAM TEMPERATURE_READINGS_RAW (eventTime BIGINT, temperature INT)
    WITH (kafka_topic='deviceEvents', value_format='avro', partitions=1);

The schema for our example stream specifies eventTime as a BIGINT. It is common for applications to send data in Unix time, thus why eventTime is specified as a BIGINT.

Insert sample data into the stream with the commands below.

INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615566394751, 100);
INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615566401534, 132);
INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615567732840, 144);
INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615567735866, 103);
INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615567736875, 102);
INSERT INTO TEMPERATURE_READINGS_RAW (eventTime, temperature) VALUES (1615567738890, 101);

Let’s examine the ksqlDB stream with the DESCRIBE function:

DESCRIBE TEMPERATURE_READINGS_RAW;

After entering the command above, you should see the following:

Name                 : TEMPERATURE_READINGS_RAW
 Field       | Type
-----------------------
 EVENTTIME   | BIGINT
 TEMPERATURE | INTEGER
-----------------------
For runtime statistics and query details run: DESCRIBE EXTENDED <Stream,Table>;

To convert the BIGINT UTC time into a TIMESTAMP American/Denver time, we need to use a combination of two ksqlDB functions: FROM_UNIX and CONVERT_TZ. Our first step is to convert the BIGINT into a TIMESTAMP using the FROM_UNIX ksqlDB function. Run the command below to convert the EVENTTIME column to a TIMESTAMP.

SELECT TEMPERATURE, FROM_UNIXTIME(EVENTTIME) AS EVENTTIME_TS
FROM TEMPERATURE_READINGS_RAW
EMIT CHANGES
LIMIT 6;

The query will result in the following output.

+-------------------------+-------------------------+
|TEMPERATURE              |EVENTTIME_TS             |
+-------------------------+-------------------------+
|100                      |2021-03-12T16:26:34.751  |
|132                      |2021-03-12T16:26:41.534  |
|144                      |2021-03-12T16:48:52.840  |
|103                      |2021-03-12T16:48:55.866  |
|102                      |2021-03-12T16:48:56.875  |
|101                      |2021-03-12T16:48:58.890  |
Limit Reached
Query terminated

Let’s create a persistent query to continuously convert the EVENTTIME column into a TIMESTAMP. Do so with the command below.

CREATE STREAM TEMPERATURE_READINGS_TIMESTAMP AS
SELECT TEMPERATURE, FROM_UNIXTIME(EVENTTIME) AS EVENTTIME_TS
FROM TEMPERATURE_READINGS_RAW;

4
Convert column to different timezone

Now that the EVENTTIME column is a TIMESTAMP, we can use the CONVERT_TZ ksqlDB function to convert it from UTC to America/Denver. Run the SELECT query below to see the timezone conversion.

SELECT TEMPERATURE, CONVERT_TZ(EVENTTIME_TS, 'UTC', 'America/Denver') AS EVENTTIME_MT
FROM TEMPERATURE_READINGS_TIMESTAMP
EMIT CHANGES
LIMIT 6;

The query will output the content below.

+-------------------------+-------------------------+
|TEMPERATURE              |EVENTTIME_MT             |
+-------------------------+-------------------------+
|100                      |2021-03-12T09:26:34.751  |
|132                      |2021-03-12T09:26:41.534  |
|144                      |2021-03-12T09:48:52.840  |
|103                      |2021-03-12T09:48:55.866  |
|102                      |2021-03-12T09:48:56.875  |
|101                      |2021-03-12T09:48:58.890  |
Limit Reached
Query terminated

Things look good, so let’s create a persistent query to continuously convert that column into a human readable America/Denver timestamp.

CREATE STREAM TEMPERATURE_READINGS_TIMESTAMP_MT AS
SELECT TEMPERATURE, CONVERT_TZ(EVENTTIME_TS, 'UTC', 'America/Denver') AS EVENTTIME_MT
FROM TEMPERATURE_READINGS_TIMESTAMP;

5
Create Postgres sink connector

Now deploy a JDBC sink connector with the code below. The sink connector will write the specified topic records to the Postgres database. Notice no transforms will be necessary to the eventTime column because the column is already a supported TIMESTAMP type.

CREATE SINK CONNECTOR JDBC_SINK_POSTGRES_01 WITH (
    'connector.class'     = 'io.confluent.connect.jdbc.JdbcSinkConnector',
    'connection.url'      = 'jdbc:postgresql://postgres:5432/',
    'connection.user'     = 'postgres',
    'connection.password' = 'postgres',
    'topics'              = 'TEMPERATURE_READINGS_TIMESTAMP_MT',
    'auto.create'         = 'true',
    'auto.evolve'         = 'true'
  );

Prior to version 0.17.0, ksqlDB did not have a TIMESTAMP data type so the only way to convert BIGINT to a TIMESTAMP was with Kafka Connect’s Single Message Transforms (SMT), specifically the TimestampConverter; . Using this SMT is simple but it does not provide a way to convert timestamp data to other timezones, and it needs to be configured a per connector basis. If you were going this route of using TimestampConverter, you would add the SMT into the connector configuration, something similar to the following:

"transforms": "TimestampConverter",
"transforms.TimestampConverter.type": "org.apache.kafka.connect.transforms.TimestampConverter$Value",
"transforms.TimestampConverter.format": "yyyy-MM-ddTHH:mm:ss.SSS"
"transforms.TimestampConverter.target.type": "Timestamp"

We can check the status of our connector by running the following:

DESCRIBE CONNECTOR JDBC_SINK_POSTGRES_01;

Which will give output similar to below. You will see that State is Running, meaning that our connector should be up and running.

Name                 : JDBC_SINK_POSTGRES_01
Class                : io.confluent.connect.jdbc.JdbcSinkConnector
Type                 : sink
State                : RUNNING
WorkerId             : ksqldb:8083

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

6
Query the data in Postgres

We can now query our Postgres database to verify that the connector is working as expected. Enter the following command into the command line, not the ksqlDB CLI:

 echo 'SELECT * FROM "TEMPERATURE_READINGS_TIMESTAMP_MT";' | docker exec -i postgres bash -c 'psql -U $POSTGRES_USER $POSTGRES_DB'

You should see something similar to below:

 TEMPERATURE |      EVENTTIME_MT
-------------+-------------------------
         100 | 2021-03-12 09:26:34.751
         132 | 2021-03-12 09:26:41.534
         144 | 2021-03-12 09:48:52.84
         103 | 2021-03-12 09:48:55.866
         102 | 2021-03-12 09:48:56.875
         101 | 2021-03-12 09:48:58.89
(6 rows)

7
Clean up

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

docker-compose down

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 CC100KTS to receive an additional $100 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 run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.