ksqlDB: streaming SQL on Kafka, and the Kafka Streams code behind it
ksqlDB lets you write stream processing as SQL statements that run continuously on a server. Underneath, every persistent query becomes a Kafka Streams topology. This page explains ksqlDB's model and syntax from its official documentation, and runs the equivalent Kafka Streams code for each query, so you can see exactly what the SQL does and decide which of the two to use.
Contents
What ksqlDB is
ksqlDB is a server that runs stream processing written in SQL. You declare a stream or a table over a Kafka topic, then write a query such as "keep the orders over 100" or "count page views per minute". ksqlDB turns each persistent query into a Kafka Streams topology and runs it until you stop it, writing the results to a new topic. Its documentation puts it plainly: ksqlDB is built on Kafka Streams.
The model has the same two building blocks as the Kafka Streams DSL:
- Stream: an append-only sequence of events over a topic, declared with
. Like aCREATE STREAM , every row counts.KStream - Table: the latest value per primary key, declared with
or derived withCREATE TABLE . Like aCREATE TABLE AS SELECT , a new row for a key replaces the old one.KTable
And three kinds of queries:
| Query | Written as | What it does | Kafka Streams counterpart |
|---|---|---|---|
| Persistent | CREATE STREAM AS SELECTCREATE TABLE AS SELECT | Runs on the server indefinitely, writing to an output topic | A running KafkaStreams |
| Push | SELECTEMIT CHANGES | A client subscribes and receives every change as it happens | Consuming the output topic |
| Pull | SELECTWHERE | Returns the current value and ends, like a database lookup | An interactive query on a state store |
The standalone ksqlDB project's latest release is 0.29.0, from June 2023, and it is licensed under the Confluent Community License, not the Apache License. The Confluent Platform 8.4 documentation still covers ksqlDB. ksqlDB cannot run in this environment, so none of the SQL on this page was run: every statement follows the syntax in the official ksqlDB documentation. The Java programs are the Kafka Streams equivalents, run on Kafka 4.2 with TopologyTestDriver
Declaring streams and tables
A ksqlDB statement first gives a topic a schema. The KEYPRIMARY KEYCREATE STREAMCREATE TABLE
CREATE STREAM orders (
id VARCHAR KEY,
customer VARCHAR,
product VARCHAR,
amount INT
) WITH (KAFKA_TOPIC = 'orders', VALUE_FORMAT = 'JSON', PARTITIONS = 6);
CREATE TABLE users (
id VARCHAR PRIMARY KEY,
tier VARCHAR
) WITH (KAFKA_TOPIC = 'users', VALUE_FORMAT = 'JSON');
is required. WithKAFKA_TOPIC , ksqlDB creates the topic if it does not exist; without it, the topic must already exist.PARTITIONS can beVALUE_FORMAT ,JSON ,AVRO ,PROTOBUF ,JSON_SR and others. With the Schema Registry formats, the columns can be read from the registry instead of being listed.DELIMITED- A declaration does not start any processing. It only records the schema in ksqlDB's metadata, much like a
with serdes in aConsumed .StreamsBuilder
A table declared with CREATE TABLECREATE TABLE AS SELECT
Filtering and transforming
A persistent query that keeps large orders and reshapes them is the simplest case. In ksqlDB it is one statement (not run):
CREATE STREAM big_orders WITH (KAFKA_TOPIC = 'big_orders') AS
SELECT id, customer, UCASE(product) AS product, amount * 100 AS cents
FROM orders
WHERE amount >= 100
EMIT CHANGES;
The Kafka Streams program below does the same work, with the JSON handled by Jackson. Three orders of 240, 3 and 100 test the boundary of the WHERE
import ch.qos.logback.classic.Level;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Kafka Streams version of:
// CREATE STREAM big_orders WITH (KAFKA_TOPIC='big_orders') AS
// SELECT id, customer, UCASE(product) AS product, amount * 100 AS cents
// FROM orders WHERE amount >= 100 EMIT CHANGES;
public class FilterAsStreams {
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
.mapValues(FilterAsStreams::parse)
.filter((key, order) -> order.get("amount").asInt() >= 100) // WHERE
.mapValues(order -> { // SELECT list
ObjectNode out = JSON.createObjectNode();
out.put("ID", order.get("id").asText());
out.put("CUSTOMER", order.get("customer").asText());
out.put("PRODUCT", order.get("product").asText().toUpperCase());
out.put("CENTS", order.get("amount").asInt() * 100);
return out.toString();
})
.to("big_orders", Produced.with(Serdes.String(), Serdes.String()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "big-orders");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("orders",
new StringSerializer(), new StringSerializer());
in.pipeInput("o1", order("o1", "ann", "desk", 240));
in.pipeInput("o2", order("o2", "bob", "pen", 3));
in.pipeInput("o3", order("o3", "cid", "lamp", 100));
driver.createOutputTopic("big_orders", new StringDeserializer(),
new StringDeserializer()).readKeyValuesToList().forEach(System.out::println);
}
}
static String order(String id, String customer, String product, int amount) {
return JSON.createObjectNode().put("id", id).put("customer", customer)
.put("product", product).put("amount", amount).toString();
}
static JsonNode parse(String json) {
try {
return JSON.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException("not JSON: " + json, e);
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
KeyValue(o1, {"ID":"o1","CUSTOMER":"ann","PRODUCT":"DESK","CENTS":24000})
KeyValue(o3, {"ID":"o3","CUSTOMER":"cid","PRODUCT":"LAMP","CENTS":10000})
- The 3-unit pen order was dropped and the 100-unit lamp kept, because
includes the boundary.>= - The column names are upper case. ksqlDB folds unquoted identifiers to upper case, so its JSON output uses
,ID and so on; the program imitates that.CUSTOMER andUCASE(product) became oneamount * 100 call. In ksqlDB, the key columnmapValues stays the record key, as in the program, where the key passed through unchanged.id
The SQL is shorter and needs no build or deployment of Java code, which is ksqlDB's main appeal. The Java version can do anything Java can, such as calling a library, which in ksqlDB needs a user-defined function packaged as a jar on the server.
Windowed aggregations: EMIT CHANGES and EMIT FINAL
Counting page views per page per minute is a windowed aggregation, and it produces a table. ksqlDB documents EMIT CHANGESEMIT FINAL
CREATE TABLE views_per_minute AS
SELECT page, COUNT(*) AS views
FROM pageviews
WINDOW TUMBLING (SIZE 1 MINUTE, GRACE PERIOD 0 SECONDS)
GROUP BY page
EMIT CHANGES;
-- the same aggregation, final results only
CREATE TABLE views_per_minute_final AS
SELECT page, COUNT(*) AS views
FROM pageviews
WINDOW TUMBLING (SIZE 1 MINUTE, GRACE PERIOD 0 SECONDS)
GROUP BY page
EMIT FINAL;
The Kafka Streams equivalent groups by page, which repartitions the views, counts in tumbling windows, and prints the eager updates and the results of suppress
import ch.qos.logback.classic.Level;
import java.time.Duration;
import java.time.Instant;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Suppressed;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.Windowed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Kafka Streams version of:
// CREATE TABLE views_per_minute AS
// SELECT page, COUNT(*) AS views FROM pageviews
// WINDOW TUMBLING (SIZE 1 MINUTE, GRACE PERIOD 0 SECONDS)
// GROUP BY page EMIT CHANGES; -- and the same with EMIT FINAL
public class WindowedCounts {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
// pageviews keyed by user; the value is the page
// GROUP BY page, WINDOW TUMBLING, COUNT(*)
KTable<Windowed<String>, Long> counts = builder
.stream("pageviews", Consumed.with(Serdes.String(), Serdes.String()))
.groupBy((user, page) -> page, Grouped.with(Serdes.String(), Serdes.String()))
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(1), Duration.ZERO))
.count(Materialized.with(Serdes.String(), Serdes.Long()));
counts.toStream().foreach((w, n) -> System.out.println(" EMIT CHANGES " + row(w, n)));
counts.suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
.toStream()
.foreach((w, n) -> System.out.println(" EMIT FINAL " + row(w, n)));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "views-per-minute");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("pageviews",
new StringSerializer(), new StringSerializer());
Instant t0 = Instant.parse("2026-05-01T12:00:00Z");
String[][] views = {{"5", "u1", "/home"}, {"20", "u2", "/home"},
{"40", "u1", "/cart"}, {"65", "u3", "/home"}};
for (String[] v : views) {
System.out.println("view at +" + v[0] + "s: " + v[1] + " " + v[2]);
in.pipeInput(v[1], v[2], t0.plusSeconds(Long.parseLong(v[0])));
}
}
}
static String row(Windowed<String> w, Long n) {
String start = Instant.ofEpochMilli(w.window().start()).toString().substring(11, 19);
return "WINDOWSTART=" + start + " PAGE=" + w.key() + " VIEWS=" + n;
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
view at +5s: u1 /home
EMIT CHANGES WINDOWSTART=12:00:00 PAGE=/home VIEWS=1
view at +20s: u2 /home
EMIT CHANGES WINDOWSTART=12:00:00 PAGE=/home VIEWS=2
view at +40s: u1 /cart
EMIT CHANGES WINDOWSTART=12:00:00 PAGE=/cart VIEWS=1
view at +65s: u3 /home
EMIT CHANGES WINDOWSTART=12:01:00 PAGE=/home VIEWS=1
EMIT FINAL WINDOWSTART=12:00:00 PAGE=/cart VIEWS=1
EMIT FINAL WINDOWSTART=12:00:00 PAGE=/home VIEWS=2
- Each of the first three views produced an
row at once:EMIT CHANGES went to 1, then 2, and/home to 1, all in the window starting 12:00:00./cart - No
row appeared until the view at 65 seconds moved stream time past the end of that window. Then both final counts came out together:EMIT FINAL 1 and/cart 2./home - The view at 65 seconds started the 12:01:00 window, whose final result would only come with a later record.
The grace period matters even more in ksqlDB than in hand-written Kafka Streams code, because the documentation gives it a default of 24 hours when the statement does not set one. With EMIT FINALGRACE PERIODWINDOWSTARTWINDOWEND
Joins
Enriching click events with the user's tier is a stream-table join. In ksqlDB (not run):
CREATE STREAM enriched_clicks AS
SELECT c.user_id, c.page, u.tier
FROM clicks c
LEFT JOIN users u ON c.user_id = u.id
EMIT CHANGES;
The Kafka Streams version prints its topology, so you can see the shape that such a statement compiles to, then sends clicks before and after a profile change:
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Kafka Streams version of:
// CREATE STREAM enriched_clicks AS
// SELECT c.user_id, c.page, u.tier FROM clicks c
// LEFT JOIN users u ON c.user_id = u.id EMIT CHANGES;
public class JoinAsStreams {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
Consumed<String, String> strings = Consumed.with(Serdes.String(), Serdes.String());
KStream<String, String> clicks = builder.stream("clicks", strings); // key: user id
KTable<String, String> users = builder.table("users", strings); // key: user id
clicks.leftJoin(users, (page, tier) -> "PAGE=" + page + " TIER=" + tier)
.to("enriched_clicks", Produced.with(Serdes.String(), Serdes.String()));
Topology topology = builder.build();
System.out.print(topology.describe());
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "enrich");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
try (var driver = new TopologyTestDriver(topology, props)) {
var user = driver.createInputTopic("users",
new StringSerializer(), new StringSerializer());
var click = driver.createInputTopic("clicks",
new StringSerializer(), new StringSerializer());
user.pipeInput("u1", "gold");
click.pipeInput("u1", "/home");
click.pipeInput("u2", "/home"); // no user row yet
user.pipeInput("u1", "platinum");
click.pipeInput("u1", "/cart");
driver.createOutputTopic("enriched_clicks", new StringDeserializer(),
new StringDeserializer()).readKeyValuesToList().forEach(System.out::println);
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
Topologies:
Sub-topology: 0
Source: KSTREAM-SOURCE-0000000000 (topics: [clicks])
--> KSTREAM-LEFTJOIN-0000000004
Processor: KSTREAM-LEFTJOIN-0000000004 (stores: [users-STATE-STORE-0000000001])
--> KSTREAM-SINK-0000000005
<-- KSTREAM-SOURCE-0000000000
Source: KSTREAM-SOURCE-0000000002 (topics: [users])
--> KTABLE-SOURCE-0000000003
Sink: KSTREAM-SINK-0000000005 (topic: enriched_clicks)
<-- KSTREAM-LEFTJOIN-0000000004
Processor: KTABLE-SOURCE-0000000003 (stores: [users-STATE-STORE-0000000001])
--> none
<-- KSTREAM-SOURCE-0000000002
KeyValue(u1, PAGE=/home TIER=gold)
KeyValue(u2, PAGE=/home TIER=null)
KeyValue(u1, PAGE=/cart TIER=platinum)
- The topology is one sub-topology: the
topic feeds a table store, and the clicks source looks it up in the join processor. No repartition topic is needed because both topics are keyed by user id.users - u1's first click joined "gold"; u2 had no user row, so the left join produced a null tier.
- After the profile changed, u1's next click joined "platinum". The earlier joined row was not updated: a stream-table join never revisits past events, in ksqlDB as in Kafka Streams.
The same co-partitioning rules apply. If the join condition is not on the key of both sides, ksqlDB repartitions one side itself, through an internal topic. A stream-stream join needs a time window, written as WITHININNER JOIN payments p WITHIN 1 HOURS ON p.id = o.id
Push queries and pull queries
A client reads ksqlDB results in two ways. A push query subscribes to a table or stream and receives every change; a pull query asks for the current value of a key and returns once. For a count of orders per customer, the statements are (not run):
CREATE TABLE orders_per_customer AS
SELECT customer, COUNT(*) AS orders FROM orders GROUP BY customer EMIT CHANGES;
SELECT * FROM orders_per_customer EMIT CHANGES; -- push: runs until cancelled
SELECT * FROM orders_per_customer WHERE customer = 'ann'; -- pull: returns the current row
The Kafka Streams counterpart of the push query reads the output topic, and the counterpart of the pull query reads the state store. The test driver gives direct access to the store; a running application would use an interactive query:
import ch.qos.logback.classic.Level;
import java.util.Properties;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.state.KeyValueStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Kafka Streams version of:
// CREATE TABLE orders_per_customer AS
// SELECT customer, COUNT(*) AS orders FROM orders GROUP BY customer EMIT CHANGES;
// SELECT * FROM orders_per_customer EMIT CHANGES; -- push query: every change
// SELECT * FROM orders_per_customer WHERE customer='ann'; -- pull query: the value now
public class PullAndPush {
public static void main(String[] args) {
quietLogs();
StreamsBuilder builder = new StreamsBuilder();
builder.stream("orders", Consumed.with(Serdes.String(), Serdes.String())) // key: customer
.groupByKey()
.count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as(
"ORDERS_PER_CUSTOMER").withKeySerde(Serdes.String()))
.toStream()
.to("ORDERS_PER_CUSTOMER", Produced.with(Serdes.String(), Serdes.Long()));
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "orders-per-customer");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "unused:9092");
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
try (var driver = new TopologyTestDriver(builder.build(), props)) {
var in = driver.createInputTopic("orders",
new StringSerializer(), new StringSerializer());
TestOutputTopic<String, Long> push = driver.createOutputTopic("ORDERS_PER_CUSTOMER",
new StringDeserializer(), new LongDeserializer());
for (String customer : new String[] {"ann", "bob", "ann", "ann"}) {
in.pipeInput(customer, "order");
}
System.out.println("push query, every change: " + push.readKeyValuesToList());
KeyValueStore<String, Long> table = driver.getKeyValueStore("ORDERS_PER_CUSTOMER");
System.out.println("pull query, ann now: " + table.get("ann"));
System.out.println("pull query, zoe now: " + table.get("zoe"));
}
}
static void quietLogs() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
}
}
push query, every change: [KeyValue(ann, 1), KeyValue(bob, 1), KeyValue(ann, 2), KeyValue(ann, 3)]
pull query, ann now: 3
pull query, zoe now: null
- The push side delivered all four changes in order: ann 1, bob 1, ann 2, ann 3. A subscriber sees the whole history of updates.
- The pull side returned only the current value, 3 for ann, and null for a customer with no orders.
The pull query reference lists its limits. By default only key lookups are allowed, with the key compared by equality to a literal; table scans need ksql.query.pull.table.scan.enabledJOINPARTITION BYGROUP BYWINDOW
How ksqlDB runs, and what that costs
- Server and CLI: ksqlDB runs as a cluster of servers. Statements arrive through its REST API, usually from the
command-line client, and are stored in a command topic named afterksql , so every server runs the same queries.ksql.service.id - Headless mode: for production, the documentation describes a mode where the queries come from a SQL file and the REST interface is off, so nobody can change them at run time.
- One topology per query: each persistent query is a Kafka Streams application with its own internal topics and state stores. A hundred queries mean a hundred sets of changelogs and repartition topics.
- Scaling: queries scale like Kafka Streams applications, by partitions. Adding servers adds capacity only up to the number of partitions of each query's input.
- Upgrades: changing a persistent query usually means creating a new one with a new output, because state and internal topics belong to the query.
supports a limited set of changes.CREATE OR REPLACE
Choosing between ksqlDB and Kafka Streams
| Situation | Better fit |
|---|---|
| Analysts or platform teams writing filters and aggregations without Java | ksqlDB |
| Quick exploration of a topic's contents | ksqlDB push queries |
| Processing that calls libraries, services or complex Java logic | Kafka Streams |
| Unit tests in the application's build | Kafka Streams with TopologyTestDriver |
| Processing deployed and versioned with a microservice | Kafka Streams, embedded in the service |
| A licence that must be Apache 2.0, or a project under active release | Kafka Streams; ksqlDB uses the Confluent Community License and its standalone releases stopped at 0.29.0 |
The Kafka Streams side of each query on this page is explained in depth on