Connect to a Kafka stream
Kafka is a distributed event streaming platform that lets you read, write, store, and process events, also called records.
Deephaven turns a Kafka topic into a live table that updates as records arrive, so you can filter, join, and aggregate a stream with the same table operations you use on static data.
Kafka record keys and values come in many formats, such as simple types like strings and numbers, JSON, Avro, or Protobuf. In this guide, we show you how to read each of these formats into Deephaven tables, and how to write a Deephaven table to Kafka.
See A Kafka introduction: basic terms for a detailed discussion of Kafka topics and supported formats. See the Apache Kafka documentation for full details on how to use Kafka.
Launch Kafka with Deephaven
Deephaven has an official Docker Compose file that runs the Deephaven images alongside Redpanda, one of many Kafka-compatible event streaming platforms that work with Deephaven. Redpanda's command-line tool lets you send records to a Kafka topic from the terminal.
Save the Docker Compose file locally as docker-compose.yml, and start it with docker compose up. The Deephaven IDE is then at http://localhost:10000/ide.
Key and value
Each Kafka record has a key and a value. Kafka writes each record to a partition at an offset, with a timestamp. For example, a list of Kafka records might have a stock ticker as the key and its price as the value.
The key and the value can each be nearly any sequence of bytes.
A key spec and a value spec tell Deephaven how to turn the key and the value into table columns. You pass them to consumeToTable as its fifth and sixth arguments, and you create them with methods of KafkaTools.Consume.
The key and the value can each be:
- read as a simple type
- decoded from JSON
- decoded from Avro
- decoded from Protobuf
- parsed by an object processor, such as a Jackson JSON provider
- read with a custom Kafka deserializer
- named and typed from consumer properties, with
KafkaTools.FROM_PROPERTIES, as described in Name key and value columns with properties - ignored, with
KafkaTools.Consume.IGNORE
You can't ignore both the key and the value.
Table types
Deephaven Kafka tables can be append-only, blink, or ring. Pass a KafkaTools.TableType as the last argument to consumeToTable.
- Append-only tables keep every row. The table and its memory use can grow without limit. To use this type, pass
KafkaTools.TableType.append(). - Blink tables keep only the rows from the current update cycle. Each new record appears as a row for one update cycle and then disappears. To use this type, pass
KafkaTools.TableType.blink(). - Ring tables keep only the last
Nrows. When the table grows beyondNrows, it discards the oldest rows untilNremain. To use this type, passKafkaTools.TableType.ring(N).
To keep results after blink rows disappear, see the lastBy example in Ring and blink tables.
Consume a Kafka stream
In this example, we consume a Kafka topic (test.topic) as a Deephaven table. You populate the Kafka topic by entering commands in the terminal.
For demonstration purposes, we use an append-only table and ignore the Kafka key.
consumeToTable creates a Deephaven table from a Kafka topic. Its arguments do the following:
- The connection properties,
kafkaProps, describe how to connect to Kafka.bootstrap.serverslists the initial hosts that a Kafka client connects to. The valueredpanda:9092is the address of the Redpanda service from the Docker Compose file. To connect to your own Kafka cluster, replaceredpanda:9092with your brokers'host:portlist. - The partition filter,
KafkaTools.ALL_PARTITIONS, reads every partition. - The initial offset,
KafkaTools.ALL_PARTITIONS_DONT_SEEK, starts where Kafka's consumer settings say. Read the key and choose partitions and offsets covers other choices. - The key spec,
KafkaTools.Consume.IGNORE, ignores the Kafka key. - The value spec uses
simpleSpecto read each record's value into aStringcolumn namedCommand. - The table type,
KafkaTools.TableType.append(), creates an append-only table.
The resultAppend table now reads from every partition that the test.topic topic has when the table is created.
Input Kafka data for testing
To send data to the test.topic topic that the resultAppend table consumes, run the following command in a terminal:
The command waits for input from the terminal and sends each line you enter to the test.topic topic as a record. Press Ctrl + D when you're done to stop producing.
Each record you send appears in the resultAppend table without rerunning the query.
Ring and blink tables
The following example shows how to create ring and blink tables to read from the test.topic topic:
Run docker compose exec redpanda rpk topic produce test.topic again and enter a few more lines. The resultAppend table contains all the records, the resultRing table contains the last three, and the resultBlink table shows each new row for only one update cycle.
Because rows disappear from the resultBlink table after one update cycle, let's add a table that uses lastBy to keep the last row added to the resultBlink table.
Read the key and choose partitions and offsets
In this example, consumeToTable reads the Kafka topic share.price into an append-only table. Unlike the previous examples, it reads both the key and the value.
When reading a Kafka topic, you can choose which partitions to read and where reading starts in each one:
- Partitions: You can read all partitions or only some of them.
- Starting point: Reading can start at the beginning of each partition, at the end, or at a specific offset. Kafka calls moving the read position seeking. If you don't seek, reading starts where Kafka's consumer settings say.
Let's walk through the arguments in this query.
- The partition filter is
KafkaTools.ALL_PARTITIONS, which reads all partitions. - The initial offset is
KafkaTools.ALL_PARTITIONS_DONT_SEEK, which doesn't seek. Kafka then picks the starting point:- If you set the
group.idproperty and that consumer group has a committed offset, reading starts there. - Otherwise, Kafka's
auto.offset.resetproperty decides. Its default,latest, reads only new records. This example doesn't setgroup.id, so the table shows only records sent after you create it.
- If you set the
- The key spec uses
simpleSpecto read each record's key into aStringcolumn namedSymbol. To drop theSymbolcolumn, passKafkaTools.Consume.IGNOREas the key spec instead, as in the first example. - The value spec uses
simpleSpecto read each record's value into aStringcolumn namedPrice. The column is a string becauserpk, Redpanda's command-line tool, sends135.60as text. Withdouble, Deephaven would decode the value with Kafka'sDoubleDeserializer, which expects 8 binary bytes, so text input fails. - The table type is
KafkaTools.TableType.append(), which creates an append-only table.
To change which partitions the example reads or where it starts, change the partition filter and the initial offset.
To read specific partitions, pass KafkaTools.partitionFilterFromArray(new int[]{1, 3, 5}) as the partition filter.
To choose a different starting point, pass one of these values as the initial offset:
KafkaTools.ALL_PARTITIONS_SEEK_TO_ENDalways starts with new records only.KafkaTools.ALL_PARTITIONS_SEEK_TO_BEGINNINGstarts at the beginning of every partition.KafkaTools.partitionToOffsetFromParallelArrays(new int[]{0, 1}, new long[]{100, 250})starts at the given offset in each listed partition. Partitions that aren't listed don't seek.
Note
Starting at the beginning of a partition reads only the records Kafka still retains. Kafka's retention settings delete older records once a topic passes a configured age or size, and log compaction can remove older records for a key, keeping at least the latest one.
Now let's add some entries to our Kafka stream.
Run the following command:
Enter as many key-value pairs as you want. Put a space between each key and its value, and put each pair on its own line:
Each pair you enter appears as a row in the result table.
Read Kafka topic in JSON format
The following two examples read a Kafka topic called orders in JSON format.
The first example uses jsonSpec:
Here, the value spec uses jsonSpec, which parses each record's value as JSON.
The first argument to jsonSpec is an array of ColumnDefinition objects that gives each column's name and type in the result table.
The second argument, mapping, is a Map from JSON field names to table column names. Each column name must appear in the array from the first argument.
In the example, the entry 'price': 'Price' reads the JSON field price into the Price column of the result table. For any column that the map doesn't mention, or for every column when you omit mapping, Deephaven reads the JSON field with the same name as the column.
The third argument is a custom Jackson ObjectMapper. Pass null to use the default.
The second example uses objectProcessorSpec with a Jackson provider:
Here, objectProcessorSpec takes a Jackson provider built from an ObjectValue that names each JSON field and its type. The resulting columns take the JSON field names, so the example renames them with renameColumns.
To test either example, run the following command:
Then enter the following values:
Read Kafka topic in Avro format
A schema registry stores each Kafka event schema under a subject name and tracks the subject's versions, so that producers and consumers can share them. To register a schema, see Redpanda's schema registry documentation.
In this example, consumeToTable reads the Kafka topic share.price.avro in Avro format. This example assumes that a schema with the subject name share.price.avro.record is registered in the schema registry of the Redpanda instance from the Docker Compose file.
The Properties object in this query also includes a schema.registry.url entry. It gives the URL of a schema registry that has a REST API compatible with Confluent's schema registry specification.
The value spec uses avroSpec, which reads each record's value as Avro.
The first positional argument in the avroSpec call specifies the Avro schema to use. In this case, avroSpec gets the schema named share.price.avro.record from the schema registry. Alternatively, the first argument can be an org.apache.avro.Schema object obtained from getAvroSchema.
When the schema comes from the schema registry, avroSpec overloads include:
avroSpec(schemaName)fetches the latest version of the schema.avroSpec(schemaName, schemaVersion)fetches the given version of the schema, as in the example above.avroSpec(schemaName, schemaVersion, fieldNameToColumnName)also takes aFunction<String, String>that maps each Avro field path, such asparent.childfor a nested field, to a column name. The resulting table omits any field that the function maps tonull. If the function maps a nested record's own path, such asparent, tonull, the table omits every field inside that record.
Without a fieldNameToColumnName function, Deephaven maps each top-level Avro field to a column with the same name, and each field of a nested record to a column named with the field path joined by __, such as parent__child.
Read Kafka topic in Protobuf format
In this example, consumeToTable reads the Kafka topic share.price.proto in Protobuf format. Protobuf is Google's open-source, language-neutral format for serializing structured data.
This example assumes that a schema with the subject name share.price.proto.record is registered in the schema registry of the Redpanda instance from the Docker Compose file. To register a schema, see Redpanda's schema registry documentation.
The Properties object in this query also includes a schema.registry.url entry. It gives the URL of a schema registry that has a REST API compatible with Confluent's schema registry specification.
The only argument to protobufSpec is a ProtobufConsumeOptions object, created with ProtobufConsumeOptions.builder.
The example builds a DescriptorSchemaRegistry, which fetches the Protobuf message descriptor from the schema registry. Its builder methods are:
subject: the schema subject name,share.price.proto.recordin the example.version: the schema version. When not set, Deephaven fetches the latest version. We recommend setting it so that the resulting table definition doesn't change across restarts.messageName: the fully qualified Protobuf message name, for examplecom.example.MyMessage. When not set, Deephaven uses the first message descriptor in the schema. We recommend setting it for the same reason.
ProtobufConsumeOptions.builder takes that provider and these other options:
descriptorProvidersets where the Protobuf message descriptor comes from, and it is required. The example passes aDescriptorSchemaRegistry. To read the descriptor from a Protobuf message class on the current classpath instead, passDescriptorMessageClass.of(MyMessage.class). ADescriptorMessageClassdoesn't contact the schema registry.parserOptionstakes aProtobufDescriptorParserOptionsobject, which controls how the descriptor is parsed, such as which field paths to include.protocolsets the wire protocol of the payload, as anio.deephaven.kafka.protobuf.Protocol. The default isProtocol.serdes()withDescriptorSchemaRegistryandProtocol.raw()withDescriptorMessageClass.
Protocol.serdes() is the Kafka Protobuf serializer/deserializer (serdes) format, which puts a magic byte, a 4-byte schema ID, and message indexes before the Protobuf data. Protocol.raw() is the Protobuf binary encoding with no header.
Each resulting column is named with the field path joined by _, such as foo_bar for the field bar inside foo. If the parser produces more than one column for a field path, the second and later columns get the suffixes _2, _3, and so on, such as foo_bar_2. Set pathToColumnName on the builder to change this naming.
Name key and value columns with properties
Deephaven can take a key or value column's name and type from consumer properties instead of from the spec:
KafkaTools.FROM_PROPERTIEStakes both the column name and the type from properties.simpleSpec(columnName)sets the column name and takes the type from properties.
With KafkaTools.FROM_PROPERTIES as the key spec or value spec, Deephaven reads the key or value into a single column. These properties in the Properties object passed to consumeToTable name it:
deephaven.key.column.namenames the key column. The default isKafkaKey.deephaven.value.column.namenames the value column. The default isKafkaValue.
Deephaven chooses the column type in this order:
- The class passed to
simpleSpec(columnName, dataType), if there is one. - The
deephaven.key.column.typeordeephaven.value.column.typeproperty. It acceptsshort,int,long,float,double,byte[], orString(also accepted asstring). - The Kafka deserializer set in the
key.deserializerorvalue.deserializerconsumer property. Deephaven recognizes the numeric, byte-array,UUID,ByteBuffer, andBytesdeserializers.
For a String column, set the type property or pass java.lang.String to simpleSpec.
If none of these sets a type, consumeToTable throws an error that names the column.
Standard data fields
Besides the key and value, each record's partition, offset, and timestamp become columns in the table that Deephaven creates when it consumes the topic. You can rename these columns, but you can't change their types.
You can also add optional columns for the receive time and for the key and value sizes. The receive time is the date-time immediately after Deephaven observes the record.
| Column | Type | Property | Default name |
|---|---|---|---|
| Partition | int | deephaven.partition.column.name | KafkaPartition |
| Offset | long | deephaven.offset.column.name | KafkaOffset |
| Kafka timestamp | Instant | deephaven.timestamp.column.name | KafkaTimestamp |
| Receive time | Instant | deephaven.receivetime.column.name | Not present |
| Key size | int (bytes) | deephaven.keybytes.column.name | Not present |
| Value size | int (bytes) | deephaven.valuebytes.column.name | Not present |
Consumer properties control these columns. Set them in the Properties object passed as the first argument to consumeToTable:
- To add an optional column, set its property to the column name you want.
- To disable a column that is present by default, set its property to an empty string. The property doesn't accept a null value.
For example, you might disable the partition column when the topic has only one partition.
The resultNoPartition table has KafkaOffset, KafkaTimestamp, and Command columns, and no KafkaPartition column.
Join and aggregate two Kafka streams
In this example, consumeToTable reads two Kafka topics, quotes and orders, into Deephaven as blink tables. The example uses lastBy to track the latest data from each topic, naturalJoin to join the streams, and AggSum and AggWSum to aggregate the results.
The quotes consumer passes KafkaTools.FROM_PROPERTIES as the key spec, so the deephaven.key.column.name and deephaven.key.column.type properties read each record's key into a String column named Symbol (see Name key and value columns with properties).
Next, let's add records to the two topics. In a terminal, first run the following command to start writing to the quotes topic:
Then add the following entries:
After submitting these entries to the quotes topic, use the following command to write to the orders topic:
Then add the following entries in the terminal:
The tables update as you add each entry to the Kafka streams. The final results are in the totalNotional table.
Consume a Kafka stream into a partitioned table
consumeToPartitionedTable consumes a topic into a partitioned table with one subtable for each Kafka partition. Its key column, Partition, holds the Kafka partition number. See the partitioned tables guide for the operations you can run on it.
consumeToPartitionedTable takes the same arguments as consumeToTable. To read every partition, pass KafkaTools.ALL_PARTITIONS as the partition filter, as in the example below. To read specific partitions, pass a filter such as KafkaTools.partitionFilterFromArray(new int[]{1, 3, 5}).
Custom Kafka parser
Some use cases call for custom parsing of Kafka streams, such as when payloads use non-standard encodings or need complex transformation.
See the dedicated guide, Write your own custom parser for Kafka, for a step-by-step walkthrough and complete examples.
Write to a Kafka stream
Deephaven can write tables to Kafka streams as well. When data in a table changes with real-time updates, Deephaven also writes those changes to Kafka. The KafkaTools.Produce class and produceFromTable method do this. You describe what to write with a KafkaPublishOptions object.
When producing, a key spec and a value spec work in the other direction. They say which table columns Deephaven writes as each record's key and value.
Kafka's default partitioner hashes a non-null key to choose a partition. All records with the same key go to the same partition as long as the topic's partition count doesn't change.
In this example, we write a time table to a topic called time-topic. The example writes column X as each record's key and ignores the value.
To see the records arrive, run docker compose exec redpanda rpk topic consume time-topic in a terminal.
produceFromTable returns a Runnable. Keep a reference to it, such as runnable, for as long as you want to publish. Call runnable.run() to stop publishing and release its resources.
Now we write a time table to a topic called time-topic_group. The KafkaPublishOptions builder's lastBy(true) option tells the producer to perform a lastBy on the key columns before writing to the stream.
Related documentation
- Kafka basic terminology
- Table types
- Incremental update model
- Custom parser for Kafka
- Kafka overview
- Partitioned tables
- Create a time table
- Filter table data
- Exact and relational joins
- Multi-aggregation
consumeToTableconsumeToPartitionedTableproduceFromTabletimeTableupdatelastBynaturalJoinaggByAggSumAggWSumrenameColumns- Date-times
KafkaToolsJavadocKafkaPublishOptionsJavadocProtobufConsumeOptionsJavadoc