Anomaly detection

Question:

If I have time-series events in a Kafka topic, how do I find anomalous events?

Edit this page

Example use case:

A common pattern for fraudsters is to disguise transactions under the name of a popular company, the idea being that the chances of them being recognized is very low. For example, transactions labeled Verizon, Citibank, USPS, etc., are likely to look similar and blend in. This tutorial shows you how to identify this pattern of behavior by detecting 'abnormal' transactions that occur within a window of time There will normally be a group of such transactions that occur within a 24-hour period. When it comes to fraud detection, financial institutions will categorize this behavior as unusual and alert their fraud team to investigate immediately. Other example use cases include detecting atm fraud or unusual credit card activity.

Code example:





Short Answer

Assuming transaction events are joined with table reference data, use WINDOWING to group anomalous transactions.

CREATE TABLE accounts_to_monitor
    WITH (kafka_topic='accounts_to_monitor', partitions=1, value_format='JSON') AS
    SELECT TIMESTAMPTOSTRING(WINDOWSTART, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_START,
           TIMESTAMPTOSTRING(WINDOWEND, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_END,
           USERNAME
    FROM suspicious_transactions
    WINDOW TUMBLING (SIZE 24 HOURS)
    GROUP BY USERNAME
    HAVING COUNT(*) > 3;

Try it

1
Initialize the project

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

mkdir anomaly-detection && cd anomaly-detection

Then make the following directories to set up its structure:

mkdir src test

2
Get Confluent Platform

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

---
version: '2'

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

  broker:
    image: confluentinc/cp-kafka:6.0.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.0.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.11.0
    hostname: ksqldb-server
    container_name: ksqldb-server
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: "/etc/ksqldb"
      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"
      KSQL_KSQL_STREAMS_AUTO_OFFSET_RESET: "earliest"

  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.11.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
      - ./test:/opt/app/test

And launch it by running:

docker-compose up -d

3
Write the program interactively using the CLI

To begin developing interactively, open up the ksqlDB CLI:

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

4
Setup ksqlDB stream, table and insert data

First, you will need to create a ksqlDB table and Kafka topic to represent the suspicious names data. You can create a table from a Kafka topic or derive one from an existing stream or table. In both cases, a table’s underlying data is durably stored in a topic on the Kafka brokers. In this tutorial we are creating a new Kafka topic for our table. If kafka_topic was not specified in the query, a new Kafka topic would be created for us.

CREATE TABLE suspicious_names (CREATED_DATE VARCHAR,
                               COMPANY_NAME VARCHAR PRIMARY KEY,
                               COMPANY_ID INT)
    WITH (kafka_topic='suspicious_names',
          partitions=1,
          value_format='JSON',
          timestamp='CREATED_DATE',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

A table is more fitting for this suspicious names data because it is a mutable collection that changes over time. We may want to add company names to this table or remove them in the future.

Likewise, you’ll need a ksqlDB stream and Kafka topic to represent transaction events. The transaction information includes the identifier, the user sending the money, the name of the recipient, the amount of money sent, and the time of the transaction. Since this data represents a historical sequence of events, a stream is most appropriate.

CREATE STREAM transactions (TXN_ID BIGINT, USERNAME VARCHAR, RECIPIENT VARCHAR, AMOUNT DOUBLE, TIMESTAMP VARCHAR)
    WITH (kafka_topic='transactions',
          partitions=1,
          value_format='JSON',
          timestamp='TIMESTAMP',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

Let’s add some suspicious names data into our reference table.

INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-03-08 00:00:00', 'Verizon', 1);
INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-10-31 00:00:00', 'Spirit Halloween', 2);
INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-12-15 00:00:00', 'Best Buy', 3);

Let’s add some transaction data into our event stream.

INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9900, 'Abby Normal', 'Verizon', 22.0, '2020-10-20 13:05:36');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (12, 'Victor von Frankenstein', 'Tattered Cover', 7.0, '2020-10-20 13:07:59');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (13, 'Frau Blücher', 'Peebles', 70.0, '2020-10-20 13:15:00');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9903, 'Abby Normal', 'Verizon', 61.0, '2020-10-20 13:31:02');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9901, 'Abby Normal', 'Spirit Halloween', 83.0, '2020-10-20 13:44:41');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9902, 'Abby Normal', 'Spirit Halloween', 46.0, '2020-10-20 13:44:43');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9904, 'Abby Normal', 'Spirit Halloween', 59.0, '2020-10-20 13:44:44');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (6, 'Victor von Frankenstein', 'Confluent Cloud', 21.0, '2020-10-20 13:47:51');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (18, 'Frau Blücher', 'Target', 70.0, '2020-10-20 13:52:01');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (7, 'Victor von Frankenstein', 'Verizon', 100.0, '2020-10-20 13:55:06');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (19, 'Frau Blücher', 'Goodwill', 7.0, '2020-10-20 14:12:32');

Set ksqlDB to process data from the beginning of each Kafka topic:

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

5
Join ksqlDB stream and table

Using the table of suspicious names and stream of transactions, create a new stream of events containing only those transactions that were sent to an account name contained in the 'suspicious_names' table. We can do this by performing an INNER JOIN. In this case the INNER JOIN will couple events in the transaction stream where the "recipient" is the same as "company_name" in the suspicious_names table. The stream created below will continuously be populated by the coupled events created by the query.

CREATE STREAM suspicious_transactions
    WITH (kafka_topic='suspicious_transactions', partitions=1, value_format='JSON') AS
    SELECT T.TXN_ID, T.USERNAME, T.RECIPIENT, T.AMOUNT, T.TIMESTAMP
    FROM transactions T
    INNER JOIN
    suspicious_names S
    ON T.RECIPIENT = S.COMPANY_NAME;
Stream-Table Joins

Things to note:
- ksqlDB only supports inner and left joins between a stream and a table. See Join a stream and a table together for a LEFT JOIN example.
- It is important for the table data to be loaded before the stream event is received. INNER JOIN does not result in any output if the table-side does not already contain a value for the key, even if the table-side is later populated.
- See more detailed ksqlDB JOIN documentation.

Inspect the new stream.

SELECT TXN_ID, USERNAME, RECIPIENT, AMOUNT
FROM suspicious_transactions
EMIT CHANGES
LIMIT 6;

Note that some of the transactions we inserted earlier were to companies that are in the suspicious names table.

+-------------------------+-------------------------+-------------------------+-------------------------+
|TXN_ID                   |USERNAME                 |RECIPIENT                |AMOUNT                   |
+-------------------------+-------------------------+-------------------------+-------------------------+
|9900                     |Abby Normal              |Verizon                  |22.0                     |
|9903                     |Abby Normal              |Verizon                  |61.0                     |
|9901                     |Abby Normal              |Spirit Halloween         |83.0                     |
|9902                     |Abby Normal              |Spirit Halloween         |46.0                     |
|9904                     |Abby Normal              |Spirit Halloween         |59.0                     |
|7                        |Victor von Frankenstein  |Verizon                  |100.0                    |
Limit Reached
Query terminated

6
Group events by time intervals

For this use case, let’s say that a single transaction to one of the companies in the suspicious_names table is probably okay, but multiple transactions to one or more of those companies in a 24-hour period is an anomaly. ksqlDB gives us the ability to see if any anomalies are present for a particular user with the following query. Create the accounts_to_monitor table by copying and pasting the content below into the ksqlDB CLI.

CREATE TABLE accounts_to_monitor
    WITH (kafka_topic='accounts_to_monitor', partitions=1, value_format='JSON') AS
    SELECT TIMESTAMPTOSTRING(WINDOWSTART, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_START, (1)
           TIMESTAMPTOSTRING(WINDOWEND, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_END,
           USERNAME
    FROM suspicious_transactions
    WINDOW TUMBLING (SIZE 24 HOURS) (2)
    GROUP BY USERNAME
    HAVING COUNT(*) > 3; (3)

1 The fields `WINDOW_START` and `WINDOW_END` tell us what interval of time suspicious activity occurred.

2 The WINDOW TUMBLING part of the query allows us to do an aggregation with distinct time boundaries. In this case our window is fixed at a length of 24 hours, does not allow gaps, and does not allow overlapping. Other types of windows are explained in the "Collect data over time" section of Kafka-Tutorials. For more in-depth descriptions and visualizations, checkout the ksqlDB documentation about windows.

3 The last two lines of the query address how you would determine if a user had multiple suspicious transactions. This aspect of the query says, in essence, if any user has greater than 3 suspicious transactions during the window, emit an event to the accounts_to_monitor table.

The ksqlDB table, and the underlying Kafka topic backing this table, contain a list of accounts against which more than three suspicious transactions have taken place in a 24-hour window.

SELECT USERNAME, WINDOW_START, WINDOW_END
FROM ACCOUNTS_TO_MONITOR
EMIT CHANGES
LIMIT 1;

The output should look like the following:

+-------------------------+-------------------------+-------------------------+
|USERNAME                 |WINDOW_START             |WINDOW_END               |
+-------------------------+-------------------------+-------------------------+
|Abby Normal              |2020-10-20 00:00:00 +0000|2020-10-21 00:00:00 +0000|
Limit Reached
Query terminated

Note that if you were to alter the LIMIT of results to something greater than 1, you would not see any other accounts flagged even though Victor von Frankenstein had a transaction that was flagged as suspicious. If you decided to rerun the query with a new limit, use CTRL+D to terminate the query.

Events within the Kafka topic accounts_to_monitor can be used to drive monitoring and alerting applications that could take action such as placing a hold on the account, notifying the card holder, etc.

Type 'exit' and hit enter to shutdown the ksqlDB cli.

7
Write your statements to a file

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/test-statements.sql with the following content that represents the suspicious names (In production, you would likely use Kafka Connect to read the suspicious names from a database into a Kafka topic, and then create a ksqlDB stream for it).

CREATE TABLE suspicious_names (CREATED_DATE VARCHAR,
                               COMPANY_NAME VARCHAR PRIMARY KEY,
                               COMPANY_ID INT)
    WITH (kafka_topic='suspicious_names',
          partitions=1,
          value_format='JSON',
          timestamp='CREATED_DATE',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-03-08 00:00:00', 'Verizon', 1);
INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-10-31 00:00:00', 'Spirit Halloween', 2);
INSERT INTO suspicious_names (CREATED_DATE, COMPANY_NAME, COMPANY_ID) VALUES ('2019-12-15 00:00:00', 'Best Buy', 3);

CREATE STREAM transactions (TXN_ID BIGINT, USERNAME VARCHAR, RECIPIENT VARCHAR, AMOUNT DOUBLE, TIMESTAMP VARCHAR)
    WITH (kafka_topic='transactions',
          partitions=1,
          value_format='JSON',
          timestamp='TIMESTAMP',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9900, 'Abby Normal', 'Verizon', 22.0, '2020-10-20 13:05:36');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (12, 'Victor von Frankenstein', 'Tattered Cover', 7.0, '2020-10-20 13:07:59');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (13, 'Frau Blücher', 'Peebles', 70.0, '2020-10-20 13:15:00');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9903, 'Abby Normal', 'Verizon', 61.0, '2020-10-20 13:31:02');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9901, 'Abby Normal', 'Spirit Halloween', 83.0, '2020-10-20 13:44:41');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9902, 'Abby Normal', 'Spirit Halloween', 46.0, '2020-10-20 13:44:43');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (9904, 'Abby Normal', 'Spirit Halloween', 59.0, '2020-10-20 13:44:44');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (6, 'Victor von Frankenstein', 'Confluent Cloud', 21.0, '2020-10-20 13:47:51');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (18, 'Frau Blücher', 'Target', 70.0, '2020-10-20 13:52:01');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (7, 'Victor von Frankenstein', 'Verizon', 100.0, '2020-10-20 13:55:06');
INSERT INTO transactions (TXN_ID, USERNAME, RECIPIENT, AMOUNT, TIMESTAMP) VALUES (19, 'Frau Blücher', 'Goodwill', 7.0, '2020-10-20 14:12:32');

CREATE STREAM suspicious_transactions
    WITH (kafka_topic='suspicious_transactions', partitions=1, value_format='JSON') AS
    SELECT T.TXN_ID, T.USERNAME, T.RECIPIENT, T.AMOUNT, T.TIMESTAMP
    FROM transactions T
    INNER JOIN
    suspicious_names S
    ON T.RECIPIENT = S.COMPANY_NAME;

CREATE TABLE accounts_to_monitor
    WITH (kafka_topic='accounts_to_monitor', partitions=1, value_format='JSON') AS
    SELECT TIMESTAMPTOSTRING(WINDOWSTART, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_START,
           TIMESTAMPTOSTRING(WINDOWEND, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_END,
           USERNAME
    FROM suspicious_transactions
    WINDOW TUMBLING (SIZE 24 HOURS)
    GROUP BY USERNAME
    HAVING COUNT(*) > 3;

Test it

1
Create the test data

Create a file at test/output.json with the expected outputs. ksqlDB joins its grouping key with the window boundaries, we need to use a bit of extra expression to describe what to expect. We leverage the window key to describe the start and end boundaries that the key represents. Checkout our tutorial on tumbling windows for a more comprehensive explanation.

{
  "outputs": [
    {
      "topic": "suspicious_transactions",
      "key": "Verizon",
      "value": {
        "TXN_ID": 9900,
        "USERNAME": "Abby Normal",
        "AMOUNT": 22.0,
        "TIMESTAMP": "2020-10-20 13:05:36"
      }
    },
    {
      "topic": "suspicious_transactions",
      "key": "Verizon",
      "value": {
        "TXN_ID": 9903,
        "USERNAME": "Abby Normal",
        "AMOUNT": 61.0,
        "TIMESTAMP": "2020-10-20 13:31:02"
      }
    },
    {
      "topic": "suspicious_transactions",
      "key": "Spirit Halloween",
      "value": {
        "TXN_ID": 9901,
        "USERNAME": "Abby Normal",
        "AMOUNT": 83.0,
        "TIMESTAMP": "2020-10-20 13:44:41"
      }
    },
    {
      "topic": "suspicious_transactions",
      "key": "Spirit Halloween",
      "value": {
        "TXN_ID": 9902,
        "USERNAME": "Abby Normal",
        "AMOUNT": 46.0,
        "TIMESTAMP": "2020-10-20 13:44:43"
      }
    },
    {
      "topic": "suspicious_transactions",
      "key": "Spirit Halloween",
      "value": {
        "TXN_ID": 9904,
        "USERNAME": "Abby Normal",
        "AMOUNT": 59.0,
        "TIMESTAMP": "2020-10-20 13:44:44"
      }
    },
    {
      "topic": "suspicious_transactions",
      "key": "Verizon",
      "value": {
        "TXN_ID": 7,
        "USERNAME": "Victor von Frankenstein",
        "AMOUNT": 100.0,
        "TIMESTAMP": "2020-10-20 13:55:06"
      }
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Abby Normal",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": null,
      "timestamp": 1603199136000
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Abby Normal",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": null,
      "timestamp": 1603200662000
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Abby Normal",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": null,
      "timestamp": 1603201481000
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Abby Normal",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": {
        "WINDOW_START": "2020-10-20 00:00:00 +0000",
        "WINDOW_END": "2020-10-21 00:00:00 +0000"
      },
      "timestamp": 1603201483000
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Abby Normal",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": {
        "WINDOW_START": "2020-10-20 00:00:00 +0000",
        "WINDOW_END": "2020-10-21 00:00:00 +0000"
      },
      "timestamp": 1603201484000
    },
    {
      "topic": "accounts_to_monitor",
      "key": "Victor von Frankenstein",
      "window": {
        "start": 1603152000000,
        "end": 1603238400000,
        "type": "time"
      },
      "value": null,
      "timestamp": 1603202106000
    }

  ]
}

2
Invoke the tests

Invoke the tests using the ksqlDB test runner and the statements file that you created earlier:

docker exec ksqldb-cli ksql-test-runner -s /opt/app/src/test-statements.sql -o /opt/app/test/output.json

Which should pass:

	 >>> Test passed!

Take it to production

1
Send the statements to the REST API

Create a file at src/statements.sql with the following content that represents the statements we tested above without the test data.

CREATE TABLE suspicious_names (CREATED_DATE VARCHAR,
                               COMPANY_NAME VARCHAR PRIMARY KEY,
                               COMPANY_ID INT)
    WITH (kafka_topic='suspicious_names',
          partitions=1,
          value_format='JSON',
          timestamp='CREATED_DATE',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

CREATE STREAM transactions (TXN_ID BIGINT, USERNAME VARCHAR, RECIPIENT VARCHAR, AMOUNT DOUBLE, TIMESTAMP VARCHAR)
    WITH (kafka_topic='transactions',
          partitions=1,
          value_format='JSON',
          timestamp='TIMESTAMP',
          timestamp_format='yyyy-MM-dd HH:mm:ss');

CREATE STREAM suspicious_transactions
    WITH (kafka_topic='suspicious_transactions', partitions=1, value_format='JSON') AS
    SELECT T.TXN_ID, T.USERNAME, T.RECIPIENT, T.AMOUNT, T.TIMESTAMP
    FROM transactions T
    INNER JOIN
    suspicious_names S
    ON T.RECIPIENT = S.COMPANY_NAME;

CREATE TABLE accounts_to_monitor
    WITH (kafka_topic='accounts_to_monitor', partitions=1, value_format='JSON') AS
    SELECT TIMESTAMPTOSTRING(WINDOWSTART, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_START,
           TIMESTAMPTOSTRING(WINDOWEND, 'yyyy-MM-dd HH:mm:ss Z') AS WINDOW_END,
           USERNAME
    FROM suspicious_transactions
    WINDOW TUMBLING (SIZE 24 HOURS)
    GROUP BY USERNAME
    HAVING COUNT(*) > 3;

Launch your statements into production by sending them to the REST API with the following command:

tr '\n' ' ' < src/statements.sql | \
sed 's/;/;\'$'\n''/g' | \
while read stmt; do
    echo '{"ksql":"'$stmt'", "streamsProperties": {}}' | \
        curl -s -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq
done

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 your run application locally while your Kafka topics and stream processing is backed to your Confluent Cloud instance.