Timezone conversion and Kafka Connect JDBC sink

Question:

How can you convert a timestamp into a different timezone and sync that data to a PostgreSQL database?

Edit this page

Example use case:

Suppose you want to create reports from a database and all of the timestamps must be in a particular 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 a PostgreSQL database.

Hands-on 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 IF NOT EXISTS 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'
  );

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-sink-timestamp && cd connect-sink-timestamp

Set up environment

3

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:
  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
    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
      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"
      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.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
  postgres:
    image: postgres:13
    container_name: postgres
    environment:
    - POSTGRES_USER=postgres
    - POSTGRES_PASSWORD=postgres

And launch it by running:

docker compose up -d

Convert column to TIMESTAMP data type

4

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;

Convert column to different timezone

5

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;

Create Postgres sink connector

6

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 IF NOT EXISTS 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 |
---------------------------------

Query the data in Postgres

7

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)

Clean up

8

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.