ksqlDB: The Streaming SQL Engine

7 min read

👋 Introduction

Welcome to the world of ksqlDB.

If you have survived the journey through Kafka Brokers, Zookeepers, and the Producer/Consumer API, you have likely realized one thing: writing low-level stream processing code in Java or Scala (using the Kafka Streams API) can be complex. It requires significant boilerplate, JVM management, and a deep understanding of state stores.

The Problem:
Data Analysts, Ops teams, and developers often need to filter, aggregate, or join streams in real-time, but they do not want to write and deploy a full Java application to do it. They speak SQL, not Java.

The Solution:
ksqlDB. It is the database purpose-built for stream processing applications. It allows you to build stream processing applications using a syntax you already know: SQL.

💡 Interesting Fact: ksqlDB was originally just "KSQL". It was rebranded to ksqlDB to emphasize that it isn't just a query layer; it is an event streaming database that manages state (via RocksDB) and allows for point-in-time lookups, effectively becoming a materialized view engine.


1. ksqlDB: Bringing SQL to Event Streams

The Concept

Traditionally, databases and stream processing were separate. You had a database (Oracle, Postgres) for static data and a stream processor (Storm, Flink, Spark) for moving data.

ksqlDB merges these. It is an abstraction layer over the Kafka Streams API. When you write a SQL query in ksqlDB, the engine compiles that SQL into a Kafka Streams topology (a graph of processing nodes) and runs it.

Architecture Overview

  1. ksqlDB Server: The runtime engine that executes your queries. It runs independently of the Kafka brokers.
  2. ksqlDB CLI / UI: The interface where you type your SQL.
  3. Kafka Cluster: The storage layer. ksqlDB reads from Kafka topics and writes results back to new Kafka topics.

Why this matters

It democratizes stream processing. You can filter a topic with millions of events per second using a simple SELECT * FROM stream WHERE ... without compiling a single binary.


2. Defining Streams and Tables in ksqlDB

In the world of standard SQL (Postgres/MySQL), everything is a Table. In ksqlDB, we have two primary abstractions: Streams and Tables.

The Problem of Semantics

A Kafka topic is just a log of byte arrays. It doesn't know if the data represents a sequence of independent events (like credit card swipes) or updates to a specific entity (like a user changing their address). We need a way to tell the engine how to interpret the data.

2.1 Streams (CREATE STREAM)

A Stream is an immutable, append-only collection of events. It represents history.

  • Analogy: A bank ledger. Every transaction is recorded.
  • Behavior: If you read a stream, you process every single message in the topic from start to end.

Syntax:

sql
CREATE STREAM user_clicks (
    user_id VARCHAR,
    page_url VARCHAR,
    click_time BIGINT
) WITH (
    KAFKA_TOPIC = 'clicks_topic_raw',
    VALUE_FORMAT = 'JSON',
    PARTITIONS = 3
);

2.2 Tables (CREATE TABLE)

A Table represents the current state. It is a mutable collection based on the primary key.

  • Analogy: The current bank balance. We don't care about the history of transactions here, only the final resulting value for a specific ID.
  • Behavior: It uses the Log Compaction strategy. If a new message arrives with the same Key, it overwrites the previous value for that Key.

Syntax:

sql
CREATE TABLE user_metadata (
    user_id VARCHAR PRIMARY KEY,
    username VARCHAR,
    region VARCHAR
) WITH (
    KAFKA_TOPIC = 'users_topic_raw',
    VALUE_FORMAT = 'JSON'
);

⚠️ Critical Distinction:

  • Stream: "Alice sent 5.Alicesent5. Alice sent 5." (Total records: 2)
  • Table: "Alice has 5.Alicehas5. Alice has 10." (Total records: 1, current state is $10).

3. Push vs. Pull Queries: Continuous vs. Point-in-time

This is where ksqlDB diverges radically from standard RDBMS.

The Problem

In a standard database (MySQL), when you run a query, the database looks at the data at that exact moment, returns the result, and the connection closes. This is a Pull Query. But in streaming, data never stops arriving. How do you query a dataset that is infinite?

3.1 Push Queries (The "Streaming" Query)

A push query subscribes to a result change. The connection remains open, and the server pushes new rows to the client as soon as they are computed.

  • Keyword: EMIT CHANGES
  • Use Case: Real-time dashboards, alerting, microservices triggers.
sql
-- This query never ends. It pushes a new row every time a user logs in from 'US'.
SELECT user_id, login_time
FROM user_logins
WHERE region = 'US'
EMIT CHANGES;

3.2 Pull Queries (The "Lookup" Query)

A pull query retrieves the current state from a Materialized View (a Table) and returns immediately. It looks exactly like standard SQL.

  • Constraint: Can only be run against Tables (Materialized Views), not raw Streams (usually).
  • Use Case: A REST API fetching a user's current profile.
sql
-- Returns the current value immediately and closes connection.
SELECT * FROM user_metadata WHERE user_id = 'user_123';

4. Practical Example: Building a Real-time Materialized View

Let's simulate a real-industry scenario: Fraud Detection. We want to count how many transactions a user makes within a 1-minute window. If it's high, it might be a bot.

Prerequisites (Docker Setup)

To follow along, you need a running ksqlDB instance. Here is the standard docker-compose.yml boilerplate:

yaml
---
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181

  broker:
    image: confluentinc/cp-kafka:7.5.0
    depends_on: [zookeeper]
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

  ksqldb-server:
    image: confluentinc/cp-ksqldb-server:7.5.0
    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"

  ksqldb-cli:
    image: confluentinc/cp-ksqldb-cli:7.5.0
    depends_on: [ksqldb-server]
    entrypoint: /bin/sh
    tty: true

Step 1: Create the Input Stream

First, we define the stream of incoming raw transactions.

sql
CREATE STREAM raw_payments (
    payment_id VARCHAR,
    user_id VARCHAR,
    amount DOUBLE,
    currency VARCHAR
) WITH (
    KAFKA_TOPIC = 'payments',
    VALUE_FORMAT = 'JSON',
    PARTITIONS = 1
);

Step 2: Create a Materialized View (Table)

We want to aggregate this data. We will create a Table derived from the Stream. This table will utilize a Tumbling Window (a distinct slice of time).

sql
CREATE TABLE payments_per_minute AS
    SELECT
        user_id,
        COUNT(*) AS payment_count,
        SUM(amount) AS total_amount
    FROM raw_payments
    WINDOW TUMBLING (SIZE 1 MINUTE)
    GROUP BY user_id
    EMIT CHANGES;

What just happened?

  1. ksqlDB created a persistent query (Topology).
  2. It listens to raw_payments.
  3. Every minute, it buckets payments by user_id.
  4. It writes the results into a new internal Kafka topic (backed by RocksDB).

Step 3: Query the Data

Now, an application can perform a Push Query to watch for suspicious users in real-time:

sql
-- Alert me immediately if anyone makes more than 5 payments in a minute
SELECT *
FROM payments_per_minute
WHERE payment_count > 5
EMIT CHANGES;

Or perform a Pull Query to check a specific user's status right now:

sql
-- Check user 42
SELECT payment_count
FROM payments_per_minute
WHERE user_id = '42';

🧠 Summary & Best Practices

  1. Duality: Remember that Streams are history (Insert), Tables are state (Upsert).
  2. Keys Matter: Partition keys are critical in ksqlDB. Joins require both sides to be co-partitioned (same partition count, same partitioning strategy).
  3. Headless vs. Interactive: You can run ksqlDB in "Headless" mode (using .sql files on startup for production) or "Interactive" mode (for exploration via CLI/UI). Use Headless for Prod.
  4. Serialization: Prefer Avro, Protobuf, or JSON_SR (Schema Registry) over plain JSON for type safety and storage efficiency.

ksqlDB allows you to perform complex stream processing operations (Joins, Aggregations, Windowing) using the SQL syntax you love, removing the barrier to entry for real-time data processing.

Happy Streaming! 🌊


🔗 References & Further Reading

Challenge

You are a data engineer tasked with monitoring a real-time stream of login attempts for a financial application to detect potential brute-force attacks. A Kafka topic named login_attempts_topic receives a new message for every login attempt.

Each message in the topic has the following structure:

  • attempt_timestamp (BIGINT - Unix timestamp)
  • user_ip (VARCHAR)
  • username (VARCHAR)
  • success (BOOLEAN)

Your task is to write three ksqlDB statements to identify and report suspicious activity.

  1. First, declare a STREAM named login_attempts_stream to represent the raw data from the login_attempts_topic. The stream should be configured to read JSON formatted data.

  2. Next, create a TABLE named failed_logins_per_ip that materializes the count of failed login attempts (success = false) originating from each user_ip. This aggregation should be calculated over a 2-minute TUMBLING window.

  3. Finally, write a continuous push query that actively monitors the failed_logins_per_ip table. The query should select the user_ip and the corresponding count of failed attempts for any IP address that has more than 5 failed attempts within any 2-minute window. The query must emit results as soon as they are computed.

Expected result

Your submission should consist of three valid ksqlDB statements.

  1. A CREATE STREAM statement that defines login_attempts_stream with the columns attempt_timestamp, user_ip, username, and success with their correct data types. It must be connected to the login_attempts_topic Kafka topic and specify VALUE_FORMAT = 'JSON'.

  2. A CREATE TABLE ... AS SELECT ... statement that creates failed_logins_per_ip. This statement must select from login_attempts_stream, filter records using WHERE success = false, group the results by user_ip, and use a WINDOW TUMBLING (SIZE 2 MINUTES) clause to perform the aggregation.

  3. A SELECT statement that queries the failed_logins_per_ip table. It must include a WHERE clause to filter for records where the count is greater than 5 and must terminate with the EMIT CHANGES clause to ensure it operates as a continuous push query.

sql

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.