Kafka

KafkaStreams : Joining

Last time we look at Aggregating. This time we will continue to look at the streams DSL, and will look at joining. If you have ever done any standard SQL, this post will be very familiar

 

Where is the code?

The code for this post is all contained here

And the tests are all contained here

 

Joins

Types of join

KafkaStreams supports the following type of Joins, most of which we will look at using the KStream – KStream as our demo code, as its just easier to code tests up for

image

 

  • KStream-KStream joins are always windowed joins, because otherwise the size of the internal state store used to perform the join – e.g., a sliding window or “buffer” – would grow indefinite
  • KTable-KTable joins are always non-windowed joins. They are designed to be consistent with their counterparts in relational databases. The changelog streams of both KTables are materialized into local state stores to represent the latest snapshot of their table duals. The join result is a new KTable that represents the changelog stream of the join operation.
  • KStream-KTable joins are always non-windowed joins. They allow you to perform table lookups against a KTable (changelog stream) upon receiving a new record from the KStream (record stream).
  • KStream-GlobalKTable joins are always non-windowed joins. They allow you to perform table lookups against a GlobalKTable (entire changelog stream) upon receiving a new record from the KStream (record stream)

 

Join co-partitioning requirements

Before we look at the types of join, and the syntax for them, Kafka Streams does have the following requirements that need to be met in order to carry out the various Join operators

Input data must be co-partitioned when joining. This ensures that input records that have the same key on both sides of the join, are delivered to the same stream task during processing. It is the responsibility of the user to ensure data co-partitioning before applying join operators

The requirements for data co-partition

ing are:

  • The input topics on both sides of the join must have the same number of partitions.
    All applications that write to the input topics must have the same partitioning strategy. The keyspace of the input data must be distributed across partitions in the same manner. The partitioner may be set at various places, for example on the Producer API it can be set via the ProducerConfig.PARTITIONER_CLASS_CONFIG config value, and for the streams API can be used in #to or #through. The good news is that, if you happen to use the default partitioner-related settings across all applications, you do not need to worry about the partitioning strategy.

Inner Join

As with lots of other types of tools an inner join, will only join on inputs where there exists a key that is the same.

It should be noted that as I have chosen to use KStream-KStream joins for this demo code the following rules hold. However these rules may vary depending on if your inputs are KStream/KTable

 

  • The join is key-based, i.e. with the join predicate leftRecord.key == rightRecord.key, and window-based, i.e. two input records are joined if and only if their timestamps are “close” to each other as defined by the user-supplied JoinWindows, i.e. the window defines an additional join predicate over the record timestamps.
  • When it is triggered, the user-supplied ValueJoiner will be called to produce join output records.
  • Input records with a null key or a null value are ignored and do not trigger the join.

Anyway as is the way so far lets see the topology followed by the tests

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val left: KStream[Int, String] =
    builder.stream[Int, String]("LeftTopic")
  val right: KStream[Int, String] =
    builder.stream[Int, String]("RightTopic")

  def tryToInt( s: String ) = Try(s.toInt).toOption

  //do the join
  val joinedStream = left.join(right)( (l: String, r: String) => {
    val result = (tryToInt(l), tryToInt(r))
    result match {
      case (Some(a), Some(b)) => a + b
      case (None, Some(b)) => b
      case (Some(a), None) => a
      case (None, None) => 0
    }
  } , JoinWindows.of(Duration.ofSeconds(2)))


  val peeked = joinedStream.peek((k,v)=> {

    val theK = k
    val theV = v
  })

  peeked.to("innerJoinOutput")

  builder.build()
}

In this example, since we are not guaranteed to get a value for both sides, I am using some simple helper methods to get me some Option[Int] for both sides and finally using simple pattern matching to form a final Integer value, which the tests will use to verify against

We can also see the JoinWindows of 2 seconds, again we will try and use that in our tests. I have used this pattern for all 3 of the KStream join examples for this post. Here are the relevant tests

//arrange
val recordFactory: ConsumerRecordFactory[java.lang.Integer, java.lang.String] =
  new ConsumerRecordFactory[java.lang.Integer, java.lang.String](new IntegerSerializer, new StringSerializer)
val innerJoinTopology = new InnerJoinTopology()
val testDriver = new TopologyTestDriver(innerJoinTopology.createTopolgy(), props)

//act
testDriver.pipeInput(recordFactory.create("LeftTopic", 1, null, 1900L))
testDriver.pipeInput(recordFactory.create("RightTopic", 1, null, 1901L))

testDriver.pipeInput(recordFactory.create("LeftTopic", 1, "1", 2902L))
testDriver.pipeInput(recordFactory.create("RightTopic", 1, "2",2903L ))

OutputVerifier.compareValue(testDriver.readOutput("innerJoinOutput", integerDeserializer, integerDeserializer),
  3.asInstanceOf[Integer])


//push these out past 2 seconds (which is what Topology Join Window duration is)
Thread.sleep(2500)

testDriver.pipeInput(recordFactory.create("LeftTopic", 1, "2", 5916L))
testDriver.pipeInput(recordFactory.create("RightTopic", 1, "4", 5917L))
OutputVerifier.compareValue(testDriver.readOutput("innerJoinOutput", integerDeserializer, integerDeserializer),
  6.asInstanceOf[Integer])

val result1 = testDriver.readOutput("innerJoinOutput", integerDeserializer, integerDeserializer)
assert(result1 == null)

It can be seen that we expect the following to hold true

  • Both inputs null within the time windows, doesn’t yield anything
  • That a matched key in the time window yields a combined value of both stream values converted to an Int and added together (so 3 in this case)
  • That if we wait 2 seconds, to exceed the join window, and then push 2 new values through, That a newly matched key in the new time window yields a combined value of both stream values converted to an Int and added together (so 6 in this case)

LeftJoin

As with lots of other types of tools an left join, will include the original left input even when the right input has no value where there exists a key that is the same.

It should be noted that as I have chosen to use KStream-KStream joins for this demo code the following rules hold. However these rules may vary depending on if your inputs are KStream/KTable

  • The join is key-based, i.e. with the join predicate leftRecord.key == rightRecord.key, and window-based, i.e. two input records are joined if and only if their timestamps are “close” to each other as defined by the user-supplied JoinWindows, i.e. the window defines an additional join predicate over the record timestamps.
  • The join will be triggered under the conditions listed below whenever new input is received. When it is triggered, the user-supplied ValueJoiner will be called to produce join output records.
  • Input records with a null key or a null value are ignored and do not trigger the join.
    For each input record on the left side that does not have any match on the right side, the ValueJoiner will be called with ValueJoiner#apply(leftRecord.value, null); this explains the row with timestamp=3 in the table below, which lists [A, null] in the LEFT JOIN column.

As before we start with the topology which looks like this

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val left: KStream[Int, String] =
    builder.stream[Int, String]("LeftTopic")
  val right: KStream[Int, String] =
    builder.stream[Int, String]("RightTopic")

  //do the join
  val joinedStream = left.leftJoin(right)( (l: String, r: String) => {
    val result = s"Left='${l}', Right='${r}'"
    result
  } , JoinWindows.of(Duration.ofSeconds(2)))

  val peeked = joinedStream.peek((k,v)=> {

    val theK = k
    val theV = v
  })

  peeked.to("leftJoinOutput")

  builder.build()
}

Where we know we may not have a value on the 2nd input, but we may on the original input. So for this example I use a String, where KafkaStreams will emit “null” should there be no value on one of the inputs

Here are the relevant tests

//arrange
val recordFactory: ConsumerRecordFactory[java.lang.Integer, java.lang.String] =
  new ConsumerRecordFactory[java.lang.Integer, java.lang.String](new IntegerSerializer, new StringSerializer)
val leftJoinTopology = new LeftJoinTopology()
val testDriver = new TopologyTestDriver(leftJoinTopology.createTopolgy(), props)

//act
testDriver.pipeInput(recordFactory.create("LeftTopic", 1, null, 1900L))
testDriver.pipeInput(recordFactory.create("RightTopic", 1, null, 1901L))

testDriver.pipeInput(recordFactory.create("LeftTopic", 1, "1", 2902L))


OutputVerifier.compareValue(testDriver.readOutput("leftJoinOutput", integerDeserializer, stringDeserializer),
  "Left='1', Right='null'")


//push these out past 2 seconds (which is what Topology Join Window duration is)
Thread.sleep(2500)

testDriver.pipeInput(recordFactory.create("LeftTopic", 1, "2", 5916L))
testDriver.pipeInput(recordFactory.create("RightTopic", 1, "4", 5916L))
OutputVerifier.compareValue(testDriver.readOutput("leftJoinOutput", integerDeserializer, stringDeserializer),
  "Left='2', Right='4'")
OutputVerifier.compareValue(testDriver.readOutput("leftJoinOutput", integerDeserializer, stringDeserializer),
  "Left='2', Right='4'")
val result1 = testDriver.readOutput("leftJoinOutput", integerDeserializer, stringDeserializer)
assert(result1 == null)

It can be seen that we expect the following to hold true

  • Both inputs null within the time windows, doesn’t yield anything
  • That a single input with no matching right input in the time window yields a sinngle value for the left input, but null for the right
  • That if we wait 2 seconds, to exceed the join window, and then push 2 new values through, That we see oututs for the newly matched keys in the new time window

OuterJoin

As with lots of other types of tools an outer join, will include the original left input or the original right value providing at least one of them is not null, where there exists a key that is the same.

It should be noted that as I have chosen to use KStream-KStream joins for this demo code the following rules hold. However these rules may vary depending on if your inputs are KStream/KTable

  • The join is key-based, i.e. with the join predicate leftRecord.key == rightRecord.key, and window-based, i.e. two input records are joined if and only if their timestamps are “close” to each other as defined by the user-supplied JoinWindows, i.e. the window defines an additional join predicate over the record timestamps.
  • The join will be triggered under the conditions listed below whenever new input is received. When it is triggered, the user-supplied ValueJoiner will be called to produce join output records.
  • Input records with a null key or a null value are ignored and do not trigger the join.
    For each input record on one side that does not have any match on the other side, the ValueJoiner will be called with ValueJoiner#apply(leftRecord.value, null) or ValueJoiner#apply(null, rightRecord.value), respectively

As before we start with the topology which looks like this

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val left: KStream[Int, String] =
    builder.stream[Int, String]("LeftTopic")
  val right: KStream[Int, String] =
    builder.stream[Int, String]("RightTopic")

  //do the join
  val joinedStream = left.outerJoin(right)( (l: String, r: String) => {
    val result = s"Left='${l}', Right='${r}'"
    result
  } , JoinWindows.of(Duration.ofSeconds(2)))

  val peeked = joinedStream.peek((k,v)=> {

    val theK = k
    val theV = v
  })

  peeked.to("outerJoinOutput")

  builder.build()
}

Here are the relevant tests

test("Should produce correct output") {

  //arrange
  val recordFactory: ConsumerRecordFactory[java.lang.Integer, java.lang.String] =
    new ConsumerRecordFactory[java.lang.Integer, java.lang.String](new IntegerSerializer, new StringSerializer)
  val outerJoinTopology = new OuterJoinTopology()
  val testDriver = new TopologyTestDriver(outerJoinTopology.createTopolgy(), props)

  //act
  testDriver.pipeInput(recordFactory.create("LeftTopic", 1, null, 1900L))
  testDriver.pipeInput(recordFactory.create("RightTopic", 1, null, 1901L))

  testDriver.pipeInput(recordFactory.create("LeftTopic", 1, "1", 2902L))


  OutputVerifier.compareValue(testDriver.readOutput("outerJoinOutput", integerDeserializer, stringDeserializer),
    "Left='1', Right='null'")


  //push these out past 2 seconds (which is what Topology Join Window duration is)
  Thread.sleep(2500)

  testDriver.pipeInput(recordFactory.create("RightTopic", 1, "4", 5916L))
  OutputVerifier.compareValue(testDriver.readOutput("outerJoinOutput", integerDeserializer, stringDeserializer),
    "Left='null', Right='4'")
  val result1 = testDriver.readOutput("outerJoinOutput", integerDeserializer, stringDeserializer)
  assert(result1 == null)

  cleanup(props, testDriver)
}

It can be seen that we expect the following to hold true

  • Both inputs null within the time windows, doesn’t yield anything
  • That a single input from either side with in the time window yields a single value for the input, but null for the other

 

As I say this post is all about KStream-KStream joins, but this table may help to compound what this post has shown so far

image

 

So other types of joins such as KStream-KTable you should consult the official documentation

 

That’s it for now

So that’s all I wanted to say this time, so until the next time, hope this has shown you just how cool KafkaStreams is

Advertisements
Kafka

KafkaStreams : Aggregating

So last time we looked at a whole bunch of stateless operations. This time we will continue our journey to look at how we can start to do aggregations, and make use of state stores.

Where is the code?

The code for this post is all contained here

And the tests are all contained here

Introduction to Stateful operations

Stateful operations (unlike stateless operations) require a state store for processing purposes. We briefly touched on state stores last time, but today I wanted to drill in a bit more into this.

 

Kafka comes with some inbuilt state stores

  • PersistentKeyValueStore<K, V>
    • Storage Engine : Rocks DB
    • Fault Tolerant : Yes by default
      • The recommended store type for most use cases.
      • Stores its data on local disk.
      • Storage capacity: managed local state can be larger than the memory (heap space) of an application instance, but must fit into the available local disk space.
      • RocksDB settings can be fine-tuned, see RocksDB configuration.
      • Available store variants: time window key-value store, session window key-value store.
  • InMemoryKeyValueStore<K,V>
    • Storage Engine: None
    • Fault Tolerant : Yes by default
      • Stores its data in memory.
      • Storage capacity: managed local state must fit into memory (heap space) of an application instance.
      • Useful when application instances run in an environment where local disk space is either not available or local disk space is wiped in-between app instance restarts.

 

So how do we create these stores? Well we will be seeing some examples of these, but it is as easy as this using the high level DSL (which is what we have been using until now)

//The "persistentKeyValueStore" is one of the pre-canned state store types
//and as such logging is enabled, so the ChangeLog topic to persist state
import org.apache.kafka.streams.state.Stores
val wordCountStoreName = "wordCountStore"
val wordCountStoreSupplied = Stores.persistentKeyValueStore(wordCountStoreName)

Now some of you may have noticed the bullet point above where it mentions “Fault Tolerant”. How exactly is that done? Well the inbuilt stores actually write to a specialized topic behind the scenes. This topic is sometimes called the changelog topic, and can be used to restore state. By default, persistent key-value stores are fault-tolerant. They are backed by a compacted changelog topic. The purpose of compacting this topic is to prevent the topic from growing indefinitely, to reduce the storage consumed in the associated Kafka cluster, and to minimize recovery time if a state store needs to be restored from its changelog topic.

 

Similarly, persistent window stores are fault-tolerant. They are backed by a topic that uses both compaction and deletion. Because of the structure of the message keys that are being sent to the changelog topics, this combination of deletion and compaction is required for the changelog topics of window stores. For window stores, the message keys are composite keys that include the “normal” key and window timestamps. For these types of composite keys it would not be sufficient to only enable compaction to prevent a changelog topic from growing out of bounds. With deletion enabled, old windows that have expired will be cleaned up by Kafka’s log cleaner as the log segments expire. The default retention setting is Materialized#withRetention() + 1 day. You can override this setting by specifying StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG in the StreamsConfig.

 

So how can we turn this feature on/off?

You can enable or disable fault tolerance for a state store by enabling or disabling the change logging of the store through withLoggingEnabled() and withLoggingDisabled(). You can also fine-tune the associated topic’s configuration if needed.

Example for enabled fault-tolerance, and passing through some other useful values

  val logConfig = new util.HashMap[String, String]
  logConfig.put("retention.ms", "172800000")
  logConfig.put("retention.bytes", "10000000000")
  logConfig.put("cleanup.policy", "compact,delete")
  val wordCountStoreSupplier = Stores.inMemoryKeyValueStore(wordCountStoreName)
  val wordCountStoreBuilder = Stores.keyValueStoreBuilder(wordCountStoreSupplier, Serdes.String, Serdes.Long)
    .withLoggingEnabled(logConfig)
    .withCachingEnabled()

As I mentioned in the previous post there are a number of config values that will effect how your stateless apps emit values down stream, just to remind ourselves of those

  • COMMIT_INTERVAL_MS_CONFIG : the number of milliseconds before a commit occurs. When a commit occur state store values are emitted downstream
  • CACHE_MAX_BYTES_BUFFERING_CONFIG : The max number of bytes to cache before state store values are emitted downstream

So you may find you need to fiddle with those to get what you want in terms of max cache size, commit interval

 

Aggregating

After records are grouped by key via groupByKey or groupBy – they become either a KGroupedStream or a KGroupedTable,  they can be aggregated. Aggregations are key-based operations, which means that they always operate over records where the key is the same. You can perform aggregations on windowed or non-windowed data.

Aggregate

Rolling aggregation. Aggregates the values of (non-windowed) records by the grouped key. Aggregating is a generalization of reduce and allows, for example, the aggregate value to have a different type than the input values. (KGroupedStream details, KGroupedTable details)

When aggregating a grouped stream, you must provide an initializer (e.g., aggValue = 0) and an “adder” aggregator (e.g., aggValue + curValue). When aggregating a grouped table, you must provide a “subtractor” aggregator (think: aggValue – oldValue).

Detailed behavior of KGroupedStream:

  • Input records with null keys are ignored.
  • When a record key is received for the first time, the initializer is called (and called before the adder).
    Whenever a record with a non-null value is received, the adder is called.

Detailed behavior of KGroupedTable:

  • Input records with null keys are ignored.
  • When a record key is received for the first time, the initializer is called (and called before the adder and subtractor). Note that, in contrast to KGroupedStream, over time the initializer may be called more than once for a key as a result of having received input tombstone records for that key
  • When the first non-null value is received for a key (e.g., INSERT), then only the adder is called.
  • When subsequent non-null values are received for a key (e.g., UPDATE), then the subtractor is called with the old value as stored in the table and the adder is called with the new value of the input record that was just received. The order of execution for the subtractor and adder is not defined
  • When a tombstone record – i.e. a record with a null value – is received for a key (e.g., DELETE), then only the subtractor is called. Note that, whenever the subtractor returns a null value itself, then the corresponding key is removed from the resulting KTable. If that happens, any next input record for that key will trigger the initializer again.
package stateful.transformations.aggregating

import java.time.Duration
import java.util.Properties

import common.PropsHelper
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream.{Materialized, _}
import org.apache.kafka.streams.{KafkaStreams, Topology}


/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class AggregateTopology extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-aggregate-application", "localhost:9092")

  run()

  private def run(): Unit = {
    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[Int, Int] =
      builder.stream[Int, Int]("AggregateKeyInputTopic")

    implicit val matererlized: Materialized[Int, Long, ByteArrayKeyValueStore]
      = Materialized.as("aggregated-stream-store")

    //Rolling aggregation. Aggregates the values of (non-windowed) records by the grouped key.
    //Aggregating is a generalization of reduce and allows, for example, the aggregate value to
    //have a different type than the input values. (KGroupedStream details, KGroupedTable details)
    //
    //When aggregating a grouped stream, you must provide an initializer (e.g., aggValue = 0)
    //and an “adder” aggregator (e.g., aggValue + curValue). When aggregating a grouped table,
    //you must provide a “subtractor” aggregator (think: aggValue - oldValue).
    val groupedBy = textLines.groupByKey
    val aggregatedTable =
      groupedBy
        .aggregate[Long](0L)((aggKey, newValue, aggValue) => aggValue + newValue)(matererlized)
    aggregatedTable
        .toStream
          .peek((k,v) =>
          {
            val theKey = k
            val theValue =v
          })
        .to("aggregateOutputTopic")
    builder.build()
  }
}


Count

Rolling aggregation. Counts the number of records by the grouped key.

Detailed behavior for KGroupedStream:

Input records with null keys or values are ignored.
Detailed behavior for KGroupedTable:

Input records with null keys are ignored. Records with null values are not ignored but interpreted as “tombstones” for the corresponding key, which indicate the deletion of the key from the table.

package stateful.transformations.aggregating

import java.time.Duration
import java.util.Properties

import common.PropsHelper
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream.{Materialized, _}
import org.apache.kafka.streams.{KafkaStreams, Topology}


/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class CountTopology extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-count-application", "localhost:9092")

  run()

  private def run(): Unit = {
    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[String, String] =
      builder.stream[String, String]("CountInputTopic")


    //lets create a named wordCountStore state store
    //The "persistentKeyValueStore" is one of the pre-canned state store types
    //and as such logging is enabled, so the ChangeLog topic to persist state
    import org.apache.kafka.streams.state.Stores
    val wordCountStoreName = "wordCountStore"
    val wordCountStoreSupplied = Stores.persistentKeyValueStore(wordCountStoreName)

    val wordCounts = textLines
      .flatMapValues(x => x.toLowerCase.split("\\W+"))
      .groupBy((key, word) => word)
      .count()(Materialized.as(wordCountStoreSupplied))
    wordCounts
      .toStream
      .peek((k,v) =>
      {
        val theKey = k
        val theValue =v
      })
      .to("WordsWithCountsOutputTopic")

    builder.build()
  }
}


Reduce

Combines the values of (non-windowed) records by the grouped key. The current record value is combined with the last reduced value, and a new reduced value is returned. The result value type cannot be changed, unlike aggregate.

When reducing a grouped stream, you must provide an “adder” reducer (e.g., aggValue + curValue). When reducing a grouped table, you must additionally provide a “subtractor” reducer (e.g., aggValue – oldValue).

Detailed behavior for KGroupedStream:

  • Input records with null keys are ignored in general.
  • When a record key is received for the first time, then the value of that record is used as the initial aggregate value.
  • Whenever a record with a non-null value is received, the adder is called.

Detailed behavior for KGroupedTable:

  • Input records with null keys are ignored in general.
  • When a record key is received for the first time, then the value of that record is used as the initial aggregate value. Note that, in contrast to KGroupedStream, over time this initialization step may happen more than once for a key as a result of having received input tombstone records for that key.
  • When the first non-null value is received for a key (e.g., INSERT), then only the adder is called.
  • When subsequent non-null values are received for a key (e.g., UPDATE), then the subtractor is called with the old value as stored in the table and the adder is called with the new value of the input record that was just received. The order of execution for the subtractor and adder is not defined.
  • When a tombstone record – i.e. a record with a null value – is received for a key (e.g., DELETE), then only the subtractor is called. Note that, whenever the subtractor returns a null value itself, then the corresponding key is removed from the resulting KTable. If that happens, any next input record for that key will re-initialize its aggregate value.

 

In this example we build a KTable from a KStream directly by using a little trick of going through an intermediate topic

package stateful.transformations.aggregating

import java.time.Duration
import java.util.Properties

import common.PropsHelper
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream.{Materialized, _}
import org.apache.kafka.streams.{KafkaStreams,  Topology}


/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class ReduceTopology extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-reduce-application", "localhost:9092")

  run()

  private def run(): Unit = {
    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[String, String] =
      builder.stream[String, String]("ReduceInputTopic")


    //lets create a named reduceStore state store
    //The "persistentKeyValueStore" is one of the pre-canned state store types
    //and as such logging is enabled, so the ChangeLog topic to persist state
    import org.apache.kafka.streams.state.Stores
    val reduceStoreName = "reduceStore"
    val reduceStoreSupplied = Stores.persistentKeyValueStore(reduceStoreName)

    //by using this dummy topic we can go straight from a KSTream to kTable
    textLines.to("Dummy-ReduceInputTopic")
    val userProfiles : KTable[String, String] = builder.table("Dummy-ReduceInputTopic")


    val groupedTable = userProfiles.groupBy((user, region) => (region, user.length()))
    val reduced: KTable[String, Integer] =
      groupedTable.reduce(
        (aggValue : Int, newValue: Int) => aggValue + newValue,
        (aggValue: Int, oldValue: Int) => aggValue - oldValue)
      .mapValues(v => new Integer(v))

    val finalStream = reduced.toStream
    finalStream.to("ReduceOutputTopic")

    builder.build()
  }
}


Custom State Stores

You should not to create custom state stores really, but if you find you do want/need to do this, the starting place for this is by implementing the following interfaces

  • org.apache.kafka.streams.state.KeyValueBytesStoreSupplier which expects you to implement the following
    • /**
       * Return the name of this state store supplier.
       * This must be a valid Kafka topic name; valid characters are ASCII alphanumerics, '.', '_' and '-'.
       *
       * @return the name of this state store supplier
       */
      String name();
      
      /**
       * Return a new {@link StateStore} instance.
       *
       * @return a new {@link StateStore} instance of type T
       */
      T get();
      
      /**
       * Return a String that is used as the scope for metrics recorded by Metered stores.
       * @return metricsScope
       */
      String metricsScope();
      
  • org.apache.kafka.streams.state.KeyValueStore<K, V>
    • /**
       * Update the value associated with this key.
       *
       * @param key The key to associate the value to
       * @param value The value to update, it can be {@code null};
       *              if the serialized bytes are also {@code null} it is interpreted as deletes
       * @throws NullPointerException If {@code null} is used for key.
       */
      void put(K key, V value);
      
      /**
       * Update the value associated with this key, unless a value is already associated with the key.
       *
       * @param key The key to associate the value to
       * @param value The value to update, it can be {@code null};
       *              if the serialized bytes are also {@code null} it is interpreted as deletes
       * @return The old value or {@code null} if there is no such key.
       * @throws NullPointerException If {@code null} is used for key.
       */
      V putIfAbsent(K key, V value);
      
      /**
       * Update all the given key/value pairs.
       *
       * @param entries A list of entries to put into the store;
       *                if the serialized bytes are also {@code null} it is interpreted as deletes
       * @throws NullPointerException If {@code null} is used for key.
       */
      void putAll(List<KeyValue<K, V>> entries);
      
      /**
       * Delete the value from the store (if there is one).
       *
       * @param key The key
       * @return The old value or {@code null} if there is no such key.
       * @throws NullPointerException If {@code null} is used for key.
       */
      V delete(K key);
      
      /**
       * The name of this store.
       * @return the storage name
       */
      String name();
      
      /**
       * Initializes this state store.
       * <p>
       * The implementation of this function must register the root store in the context via the
       * {@link ProcessorContext#register(StateStore, StateRestoreCallback)} function, where the
       * first {@link StateStore} parameter should always be the passed-in {@code root} object, and
       * the second parameter should be an object of user's implementation
       * of the {@link StateRestoreCallback} interface used for restoring the state store from the changelog.
       * <p>
       * Note that if the state store engine itself supports bulk writes, users can implement another
       * interface {@link BatchingStateRestoreCallback} which extends {@link StateRestoreCallback} to
       * let users implement bulk-load restoration logic instead of restoring one record at a time.
       *
       * @throws IllegalStateException If store gets registered after initialized is already finished
       * @throws StreamsException if the store's change log does not contain the partition
       */
      void init(ProcessorContext context, StateStore root);
      
      /**
       * Flush any cached data
       */
      void flush();
      
      /**
       * Close the storage engine.
       * Note that this function needs to be idempotent since it may be called
       * several times on the same state store.
       * <p>
       * Users only need to implement this function but should NEVER need to call this api explicitly
       * as it will be called by the library automatically when necessary
       */
      void close();
      
      /**
       * Return if the storage is persistent or not.
       *
       * @return  {@code true} if the storage is persistent&mdash;{@code false} otherwise
       */
      boolean persistent();
      
      /**
       * Is this store open for reading and writing
       * @return {@code true} if the store is open
       */
      boolean isOpen();|
      
      /**
       * Get the value corresponding to this key.
       *
       * @param key The key to fetch
       * @return The value or null if no value is found.
       * @throws NullPointerException If null is used for key.
       * @throws InvalidStateStoreException if the store is not initialized
       */
      V get(K key);
      
      /**
       * Get an iterator over a given range of keys. This iterator must be closed after use.
       * The returned iterator must be safe from {@link java.util.ConcurrentModificationException}s
       * and must not return null values. No ordering guarantees are provided.
       * @param from The first key that could be in the range
       * @param to The last key that could be in the range
       * @return The iterator for this range.
       * @throws NullPointerException If null is used for from or to.
       * @throws InvalidStateStoreException if the store is not initialized
       */
      KeyValueIterator<K, V> range(K from, K to);
      
      /**
       * Return an iterator over all keys in this store. This iterator must be closed after use.
       * The returned iterator must be safe from {@link java.util.ConcurrentModificationException}s
       * and must not return null values. No ordering guarantees are provided.
       * @return An iterator of all key/value pairs in the store.
       * @throws InvalidStateStoreException if the store is not initialized
       */
      KeyValueIterator<K, V> all();
      
      /**
       * Return an approximate count of key-value mappings in this store.
       *
       * The count is not guaranteed to be exact in order to accommodate stores
       * where an exact count is expensive to calculate.
       *
       * @return an approximate count of key-value mappings in the store.
       * @throws InvalidStateStoreException if the store is not initialized
       */
      long approximateNumEntries();
      

 

The best place to look at how to implement these is to look at the existing classes, for example

  • RocksDbKeyValueBytesStoreSupplier
  • RocksDBStore

That’s it for now

So that is all I wanted to talk about this time. Next time we will continue our journey and look at joining operations

WPF

MVVMDiagramDesigner now supports grouping

A while back when I was more UI focusssed, and the web was nice as it is now, I wrote a WPF diagramming tool (using MVVM).

This was quite popular and looked like this

Thing is a lot of people wanted it to support grouping. Someone took on this noble task, and sent me a nice PR for that which I have merged. So it now supports grouping/ungrouping too : https://github.com/sachabarber/MVVMDiagramDesigner

Thanks “vRage” for the PR

 

 

 

Kafka

KafkaStreams : Stateless operations

Ok so our journey now continues with Kafka Streams. Last time we introduced a few key concepts, such as

  • Props
  • Topologies
  • How to test streams apps

This time we will continue to look at stateless operations. If you have ever using C# LINQ operators this post will probably be quite familiar looking, or at least the concepts will. The main difference is that we are using these operators on  streams of data coming from Kafka topics.

 

We will be using the same approach from the 1st article, where we will build a topology and then proceed to test it using the previously introduced TopologyTestDriver / OutputVerifier test tools from Confluent. As before the code is written in Scala.

 

Where is the code?

The code for this post is all contained here

And the tests are here

 

I will not be bothering to walk through every test, but you will find a set of tests for each new Topology that is introduced in this post. As this post is mainly around stateless transforms, I will not be spending too much time on talking about state, it is however not completely avoidable as some of the operations do require us to create state to demonstrate the stateless side of it

 

Branch

Allows us to apply one (or more) predicates to an initial KStream, to create one or more KStream objects for the matched predicates. If no match is found the input record is dropped.

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val textLines: KStream[String, String] =
    builder.stream[String, String]("InputTopic")

  val predicates : List[(String, String) => Boolean] = List(
    (k,v) => v.startsWith("Odd"),
    (k,v) => v.startsWith("Even")
  )

  val branches : Array[KStream[String, String]] = textLines.branch(predicates:_*)
  branches(0).to("OddTopic")
  branches(1).to("EvenTopic")
  builder.build()
}

So for this example we could potentially end up with values written to the 2 output topics OddTopic/EvenTopic.

Filter/Inverse Filter

Filter keeps the records for which the predicate is satisfied, while filterNot (inverse filter) drops the records for which the predicate returns true.

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val textLines: KStream[String, Long] =
    builder.stream[String, Long]("InputTopic")

  //Evaluates a boolean function for each element and retains those
  //for which the function returns true
  val above5 = textLines.filter((k,v) => v > 5)
  above5.to("Above5OutputTopic")

  //Evaluates a boolean function for each element and drops those
  //for which the function returns true.
  val belowOrEqualTo5 = textLines.filterNot((k,v) => v > 5)
  belowOrEqualTo5.to("BelowOrEqualTo5OutputTopic")

  builder.build()
}

FlatMap / FlatMap (Values only)

FlatMap allows you to produce 0-* items from an original KeyValue record tuple. You can create a new Key or Value or both, and alter the types of both. As this operation is capable of changing the key, it will cause re-partitioning to keep the data in the correct partition. So you should be wary of using this operation, and prefer flatMapValues

 

FlatMapValues allows you to produce 0-* items from an original KeyValue record tuple where you can create a new Value and alter its type, but maintain the original key. As the original key is maintained, this operation does not cause a re-partition to occur

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val textLines: KStream[Int, Int] =
    builder.stream[Int, Int]("InputTopic")

  //Takes one record and produces zero, one, or more records.
  //You can modify the record keys and values, including their types
  val flatMapped = textLines.flatMap((k,v) => {
    List(
      (k + 1, v + 2),
      (k + 3, v + 4)
    )
  })
  flatMapped.to("flatMappedOutputTopic")


  //Takes one record and produces zero, one, or more records, while retaining the key of the original record.
  //You can modify the record values and the value type.
  //flatMapValues is preferable to flatMap because it will not cause data re-partitioning.
  //However, you cannot modify the key or key type like flatMap does
  val flatMappedValues = textLines.flatMapValues((k,v) => {
    List(
      v + 10,
      v + 20
    )
  })
  flatMappedValues.to("flatMappedValuesOutputTopic")

  builder.build()
}

Foreach

Foreach allows us to run some side effect on the input records. This is however a terminal state. These “side effects” cant be tracked by Kafka, and as this is a terminal state, nothing else is possible after a foreEach has been performed. For this one I am showing the entire app, as its easier to read the flow. But essentially what happens is that I am using forEach to write the input records to a file which the tests will read after running the topology

package stateless.transformations

import java.io.{File, PrintWriter}
import java.time.Duration
import java.util.Properties

import common.PropsHelper
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream._
import org.apache.kafka.streams.{KafkaStreams, Topology}


/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class ForEachTopology(val pw: PrintWriter) extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-foreach-application", "localhost:9092")

  run()

  def stop() : Unit = {
    pw.close()
  }

  private def run(): Unit = {


    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[Int, Int] =
      builder.stream[Int, Int]("InputTopic")

    //Terminal operation. Performs a stateless action on each record.

    //You would use foreach to cause side effects based on the input data (similar to peek)
    //and then stop further processing of the input data (unlike peek, which is not a terminal operation).
    //Note on processing guarantees: Any side effects of an action (such as writing to
    //external systems) are not trackable by Kafka, which means they will typically not
    //benefit from Kafka’s processing guarantees.
    val flatMapped = textLines.foreach((k,v)=> {
      pw.write(s"Saw input value line '$v'\r\n")
      pw.flush()
    })

    builder.build()
  }
}


Map/Map Values Only

Map works much the same as flatMap above apart from the fact that it emits a single new KeyValue tuple. As before this causes re-partitoning, so you should prefer mapValues instead.

MapValues works much the same as flatMapValues above apart from the fact that it emits a single new KeyValue tuple, where the original Key is maintained.

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val textLines: KStream[Int, Int] =
    builder.stream[Int, Int]("InputTopic")

  //Takes one record and produces one record. You can modify the record key and value, including their types.
  //Marks the stream for data re-partitioning: Applying a grouping or a join after map will result in re-partitioning
  //of the records. If possible use mapValues instead, which will not cause data re-partitioning.
  val mapped = textLines.map((k,v) => {
      (k + 1, v + 2)
  })
  mapped.to("mappedOutputTopic")


  //Takes one record and produces one record, while retaining the key of the original record.
  //You can modify the record value and the value type. (KStream details, KTable details)
  //mapValues is preferable to map because it will not cause data re-partitioning. However, it
  //does not allow you to modify the key or key type like map does.
  val mappedValues = textLines.mapValues((k,v) => {
      v + 10
  })
  mappedValues.to("mappedValuesOutputTopic")

  builder.build()
}

 

Peek

Peek is an extremely useful operation that allows you to wire tap the stream, and cause side effects, whilst maintaining the stream values. It is like a better forEach that still emits values into the output stream processing. As with the forEach I have decided to show you the whole application here, it’s the same idea we write to a text file in the application code, and the tests can do assertions on the values in the text file at the end of the application run

package stateless.transformations

import java.io.PrintWriter
import java.time.Duration
import java.util.Properties

import common.PropsHelper
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream._
import org.apache.kafka.streams.{KafkaStreams, Topology}


/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class PeekTopology(val pw: PrintWriter) extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-peek-application", "localhost:9092")

  run()

  def stop() : Unit = {
    pw.close()
  }

  private def run(): Unit = {


    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[Int, Int] =
      builder.stream[Int, Int]("InputTopic")

    // Performs a stateless action on each record, and returns an unchanged stream.
    //
    // You would use peek to cause side effects based on the input data (similar to foreach)
    // and continue processing the input data (unlike foreach, which is a terminal operation).
    // Peek returns the input stream as-is; if you need to modify the input stream, use map or mapValues instead.
    // peek is helpful for use cases such as logging or tracking metrics or for debugging and troubleshooting.
    //
    // Note on processing guarantees: Any side effects of an action (such as writing to external systems)
    // are not trackable by Kafka, which means they will typically not benefit from Kafka’s processing guarantees.
    val peeked = textLines.peek((k,v)=> {
      pw.write(s"Saw input value line '$v'\r\n")
      pw.flush()
    })
    peeked.to("peekedOutputTopic")


    builder.build()
  }
}


SelectKey

Allows you to create a new key and possibly new type for the Key to the input records. As this changed the Key it will cause re-partitioning

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val textLines: KStream[Int, Int] =
    builder.stream[Int, Int]("InputTopic")

  // Assigns a new key - possibly of a new key type - to each record.
  // Calling selectKey(mapper) is the same as calling map((key, value) -> mapper(key, value), value).
  // Marks the stream for data re-partitioning: Applying a grouping or a join after selectKey will
  // result in re-partitioning of the records.
  val mapped = textLines.selectKey((k,v) => {
      k.toString
  })
  mapped.to("selectKeyOutputTopic")

  builder.build()
}

 

GroupBy/GroupByKey

Before we get into this one, I just wanted to talk a little bit about stores and how they effect/are effected by some of the possible settings you could apply.

Stores

We will cover this in more detail in the next post, but for now its worth mentioning, that state stores as seen in these GroupBy/GroupByKey .Count() examples, which will create a KTable, will by default start out with Logging enabled, which means that an a special changelog Kafka topic will be used to store the state of the state stores.

In the next post we will see how we can setup our own state stores, and how we can provide more fine grained details over their creation such as

  • retension.ms
  • retention.bytes
  • cleanup.policy

But for now its just good to be aware that when you do find yourself performing some operation that takes you from a KStream –> KTable, the Kafka default is to use changelog logging, which persists your state store values, which  should protect you, should you Kafka Streams application need to be restarted. It should pick up again from its last committed offset using the previously saved changelog values.

As I say we will be seeing this in much more detail in the next posts.

Ok lets see an example

GroupBy

Groups the records by the existing key. To fully illustrate this, we need to perform some sort of aggregation, which takes us into Stateful operations. We end up with a KTable. But lets see the example which should help us in the next posts

def createTopolgy(): Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val groupByKeyTextLines: KStream[Int, String] =
      builder.stream[Int, String]("GroupByKeyInputTopic")

	//NOTE : You may find you need to play with these Config values in order
    //to get the stateful operation to work correctly/how you want it to
    //    props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10000.asInstanceOf[Object])
    //    props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 10485760.asInstanceOf[Object])
    //    props.put(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG, 50000.asInstanceOf[Object])
    //By playing around with these values you should be able to find the values that work for you
    groupByKeyTextLines.groupByKey
        .count()
        .mapValues(x => x.toString)
        .toStream
        .to("groupedByKeyOutputTopic")


    builder.build()
  }

It can be seen that we start with a KSTream[int, String] and then when we use count() we would end up with a KTable[Int,Long]. This will use a state store behind the scenes. I think convert that into a KTable[Int, String] using mapValues(…) before using toStream to turn it back into a KStream[Int, String] and write it to the output topic.

Causes data re-partitioning if and only if the stream was marked for re-partitioning. groupByKey is preferable to groupBy because it re-partitions data only if the stream was already marked for
re-partitioning. However, groupByKey does not allow you to modify the key or key type like groupBy does.

 

As you can see in the comments above in the code. There are a number of values that effect how the state store values are emitted to downstream topologies

  • COMMIT_INTERVAL_MS_CONFIG : the number of milliseconds before a commit occurs. When a commit occur state store values are emitted downstream
  • CACHE_MAX_BYTES_BUFFERING_CONFIG : The max number of bytes to cache before state store values are emitted downstream

So for a given input record of (1, “one”)..(1,”one”)..(2, “two”) we may see something like (1, “2”)…(“two”,”1”) in the output topic (depending on the settings I talked about above)

GroupByKey

Groups the records by a new key, which may be of a different key type. When grouping a table, you may also specify a new value and value type. Always causes data re-partitioning: groupBy always causes data re-partitioning. If possible use groupByKey instead, which will re-partition data only if required.

def createTopolgy(): Topology = {

  val builder: StreamsBuilder = new StreamsBuilder
  val groupByTextLines: KStream[Int, String] =
    builder.stream[Int, String]("GroupByInputTopic")


  //Groups the records by a new key, which may be of a different key type.
  // 
  //NOTE : You may find you need to play with these Config values in order
  //to get the stateful operation to work correctly/how you want it to
  //    props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10000.asInstanceOf[Object])
  //    props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 10485760.asInstanceOf[Object])
  //    props.put(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG, 50000.asInstanceOf[Object])
  //By playing around with these values you should be able to find the values that work for you
  groupByTextLines.flatMapValues(x => x.toLowerCase.split("\\W+"))
    .groupBy((key, word) => word)
    .count()
    .mapValues(x => x.toString)
    .toStream
    .to("groupedByOutputTopic")

  builder.build()
}

Much the same as above, however this time we take an input string, split it on words, use each word as the key, and then count the words.

So for a given input record of (1, “one two three one”) we may see something like (“one”, “2”)…(“two”,”1”)..(“three”, “1”) in the output topic (depending on the settings I talked about above)

Custom Partitioner

There may be times where you do not have a key, and you MUST come up with a way to partition your data on the fly. KafkaStreams allows this by using an intermediate topic, and a custom partitioner which you may write. In this trivial example I will always return partition 1, but you can imagine your own code here

I will show the complete example of how to do this, as I think it’s a lot clearer to see what’s going on. The full code is shown below. The important parts are

  • Using through with Produces where we pass in the custom StreamPartitioner
  • Custom StreamPartitioner class that decides what partition (1 in my case) to use
package stateless.transformations

import java.time.Duration
import java.util.Properties
import common.PropsHelper
import org.apache.kafka.common.serialization.Serdes
import org.apache.kafka.streams.processor.StreamPartitioner
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream._
import org.apache.kafka.streams.{KafkaStreams, Topology}


class ThroughCustomPartitionerTopology() extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "stateless-custompartitioner-application", "localhost:9092")

  run()

  private def run(): Unit = {


    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy(): Topology = {

    implicit val keySerde =  Serdes.Integer
    implicit val valueSerde =  Serdes.String

    val builder: StreamsBuilder = new StreamsBuilder
    implicit val consumed = kstream.Consumed.`with`(keySerde, valueSerde)

    val textLines: KStream[java.lang.Integer, String] =
      builder.stream[java.lang.Integer, String]("InputTopic")

    //should use implicit Produced with the through
    val repartitoned = textLines.through("InputTopic-RePartitioned")
      (Produced.`with`(new AlwaysOneCustomPartitioner()))

    val finalStream = repartitoned
      .mapValues((x) => s"${x} Through")

    finalStream.to("OutputTopic")
    builder.build()
  }
}

//Custom StreamPartitioner that ALWAYS just returns 1 for Partition
class AlwaysOneCustomPartitioner extends StreamPartitioner[java.lang.Integer, String] {
  override def partition(topic: String, key: java.lang.Integer, value: String, numPartitions: Int): Integer = {
    //just default it to 1
    1
  }
}

That’s It

And that is all I have for this one. In the next post we will be looking at stateful operations, namely Aggregating.

Kafka

Kafka Streams : Example 1 straight through processing / How to test Kafka Streams

Introduction

In this post we will look at some of the key objects we looked at last time, and we will also see what a typical Scala (though Kafkas libraries are mainly Java, I just prefer Scala) app looks like. It is not a complicated application, which is exactly what you want when you are starting to learn something. I have deliberately started simple, and we will expand our knowledge as we go

Where is the code?

The code will all be in this single repo : https://github.com/sachabarber/KafkaStreamsDemo

What tools will I need to follow along

As I am using Scala, if you really want to download and try the examples that will go with this series, you will need the following

  • Scala 2.12
  • SBT
  • Java 1.8 SDK
  • A Scala IDE (I like the community edition of IntelliJ IDEA myself)

A typical Kafka Streams application

So last time we talked about a few common objects you might expect to see when working with KafkaStreams such as

  • KStream
  • KTable
  • Global KTable
  • State Store

But we did not talk about what a typical app would look like. So lets do that now shall we.

So the good news is that KafkaStreams is not a massive bloated thing that just takes over. It is a simple library that you reference and you can just run it in your own application code. There are obviously a few things that it needs to run, so we will have a brief talk about that

Props

KafkaStreams just like Kafka works by being gives a set of Key/Value properties that it needs to configure itself. These are standard properties that are well known, and you can read all about them here

You can configure Kafka Streams by specifying parameters in a java.util.Properties instance.

Create a java.util.Properties instance.

Set the parameters. For example (this is Java, Scala syntax is a little different)

import java.util.Properties;
import org.apache.kafka.streams.StreamsConfig;

Properties props = new Properties();
// Set a few key parameters
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "my-first-streams-application");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka-broker1:9092");
// Any further settings
props.put(... , ...);

 

These MUST be setup before you attempt to use a Streams application

Topology

The next thing you need, is to actual build how your streams topology should be wired up, and how you want processing to occur. To do this, there is a DSL, that looks like this (this is Scala example)

val builder: StreamsBuilder = new StreamsBuilder
val theInputStream = builder.stream[String, String]("InputTopic")
//stream DSL operations you want here
builder.build()

Start the streams

The final thing you would want to do is to actually start the streams processing, which can easily be done as follows:

val topology = createTopolgy()
val streams: KafkaStreams = new KafkaStreams(topology, props)
streams.start()
sys.ShutdownHookThread {
  streams.close(Duration.ofSeconds(10))
}

It’s a good idea to also add a shutdownHook to close the streams, which is shown above

Walkthrough of the example topology

Ok so believe it or not that small set of 3 points, plus the knowledge gained in the 1st post, are enough for us to write a fully working KafkaStreams Scala application.

The code for this example is this one, and the basic idea for this one works as follows

 

As you can see this is about as simple as I could make it. So now lets have a look at the code for this trivial example

SBT file

As I am using Scala there is a SBT file to manage the build, this is it in full

name := "ScalaKafkaStreamsDemo"

version := "1.0"

scalaVersion := "2.12.1"

libraryDependencies += "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1" artifacts(Artifact("javax.ws.rs-api", "jar", "jar"))
libraryDependencies += "org.apache.kafka" %% "kafka" % "2.1.0"
libraryDependencies += "org.apache.kafka" % "kafka-clients" % "2.1.0"
libraryDependencies += "org.apache.kafka" % "kafka-streams" % "2.1.0"
libraryDependencies += "org.apache.kafka" %% "kafka-streams-scala" % "2.1.0"

//TEST
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test
libraryDependencies += "org.apache.kafka" % "kafka-streams-test-utils" % "2.1.0" % Test

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.1.3"

 

As you can see there is a specific JAR for Scala, this is fairly new thing, and the current recommendation is to make sure you have at least Kafla 2.1.0 to work with the kafka-streams-scala JAR. There are also some test scoped JARs there, we will see how they get used in the next section. You may be asking yourself what the specific scala JAR brings to the table, well it makes working with Serdes/lambdas and implicits more Scala friendly.

One thing that is extremely weird in the javax.ws.rs-api dependency. There was a issue with a transitive dependency in Kafka itself, brought in by a Kafka Connect client, and it doesn’t resolve correctly unless you use a line something like the one shown here. I have raised a support ticket for this, and they were all over it, so I expect this will get fixed in subsequent releases

Anyway moving on to the Props, lets see what that looks like for this simple demo app. Here is my class (I will probably reuse this for all posts in this series)

import java.util.Properties
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.StreamsConfig


object PropsHelper  {

  def createBasicStreamProperties(applicationId: String, bootStrapServers: String) : Properties = {

    val props = new Properties()
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationId)
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServers)
    props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String.getClass)
    props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String.getClass)
    // Records should be flushed every 10 seconds. This is less than the default
    // in order to keep this example interactive.
    props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10000.asInstanceOf[Object])
    // For illustrative purposes we disable record caches
    props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0.asInstanceOf[Object])
    props.put(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG, 50000.asInstanceOf[Object])
    props.put(StreamsConfig.STATE_DIR_CONFIG, s"C:\\data\\kafka-streams".asInstanceOf[Object])
    props
  }
}

image

You can change these to suit your own requirements.

Ok so now on to the code. This is it, in full

import java.time.Duration
import org.apache.kafka.streams.Topology
import java.util.Properties
import org.apache.kafka.streams.scala.ImplicitConversions._
import org.apache.kafka.streams.scala._
import org.apache.kafka.streams.scala.kstream._
import org.apache.kafka.streams.KafkaStreams

/**
  * This example simply maps values from 'InputTopic' to 'OutputTopic'
  * with no changes
  */
class StraightThroughTopology extends App {

  import Serdes._

  val props: Properties = PropsHelper.createBasicStreamProperties(
    "straight-through-application","localhost:9092")

  run()

  private def run(): Unit = {
    val topology = createTopolgy()
    val streams: KafkaStreams = new KafkaStreams(topology, props)
    streams.start()
    sys.ShutdownHookThread {
      streams.close(Duration.ofSeconds(10))
    }
  }

  def createTopolgy() : Topology = {

    val builder: StreamsBuilder = new StreamsBuilder
    val textLines: KStream[String, String] = 
      builder.stream[String, String]("InputTopic")
    textLines.mapValues(v => v).to("OutputTopic")
    builder.build()
  }

}

 

So this is inline with what we just discussed. The only addition is the line that does the mapValues(..). Now you may be wondering why I chose to use mapValues(..), and not map(..). Well the reason for that is if you had a lot of partitions and you used a map(..), that would cause the key to possibly change, which would involve re-partitioning, which is an expensive operation, and should be avoided if possible. 

And believe it or not that is enough to get your 1st streams app up and running.

Testing the example topology

Now if you did read the 1st post in this series you would have seen a diagram that looks like this

Image result for kafka partitions

And you are probably thinking how on earth am I going to test all that, I need

  • At least 1 Kafka broker
  • At least 1 Kafka producer
  • At least 1 Kafka consumer
  • Zookeeper
  • And my own Stream app in the middle somehow

This is indeed a daunting task. Luckily help is at hand by way of the VERY hand kafka-streams-tests-utils JAR. This handy JAR comes with a very cool class called TopologyTestDriver which allows you to test your Streams code without needing the full setup shown above. I wont repeat all the official docs here but you can think of this class as a handy little helper that can simulate ConsumerRecords which can be sent to a topic using the pipeInput(..) method, and to also be able to verify values written to output topics using the readOutput(..) method

The official docs do a rather fine job of talking about this in fine detail, but for now, here is the code that tests the simple demo topology (code is here should you want to know where it is)

import org.scalatest._
import Matchers._
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import java.io._
import java.util.Properties
import org.apache.kafka.streams.TopologyTestDriver
import org.apache.kafka.streams.test.ConsumerRecordFactory
import org.apache.kafka.streams.test.OutputVerifier

class StaightThoughStreamsTests
  extends FunSuite
  with BeforeAndAfter
  with Matchers {

  val props = PropsHelper.createBasicStreamProperties("straight-through-application-tests","localhost:9092")
  val stringDeserializer: StringDeserializer = new StringDeserializer

  before {
  }

  after {
  }


  test("Should produce correct output") {

    //arrange
    val recordFactory: ConsumerRecordFactory[String, String] =
      new ConsumerRecordFactory[String, String](new StringSerializer, new StringSerializer)
    val straightThroughTopology = new StraightThroughTopology()
    val testDriver = new TopologyTestDriver(straightThroughTopology.createTopolgy(), props)

    //act
    val consumerRecord = recordFactory.create("InputTopic", "key", "this is the input", 9999L)
    testDriver.pipeInput(consumerRecord)

    //assert
    OutputVerifier.compareKeyValue(testDriver.readOutput("OutputTopic", stringDeserializer, stringDeserializer), "key", "this is the input")
    val result = testDriver.readOutput("OutputTopic", stringDeserializer, stringDeserializer)
    assert(result == null)
    cleanup(props, testDriver)
  }


  def cleanup(props:Properties, testDriver: TopologyTestDriver) = {

    try {
	  //there is a bug on windows which causes this line to throw exception
      testDriver.close
    } catch {
      case e: Exception => {
        delete(new File("C:\\data\\kafka-streams"))
      }
    }
  }

  def delete(file: File) {
    if (file.isDirectory)
      Option(file.listFiles).map(_.toList).getOrElse(Nil).foreach(delete(_))
    file.delete
  }
}

And just to prove it all works lets see a screen shot of this test

image

The eagle eyed amongst you will see what looks like an Exception stack trace in the right hand panel. This is due to a bug in windows where the data directory cant be deleted correctly due to some file handle issue. This seems to be quite well documented

See you next time.

So hopefully I have wet your appetite of what Kafka Streams could do for you. This is a introductory article, so we saw hardly anything of the DSL that Kafka Streams offers, but in subsequent posts we will see lots more of these

Kafka

Kafka Streams Introduction

So this post will be an introductory one on Kafka Streams. It is not intended to be one on Apache Kafka itself. For that there are many interesting books/posts/documents available which cover this topic.

 

That said there are still a few key concepts that we will need to introduce before we can start talking about Kafka Streams, such as

 

  • Kafka overall architecture
  • Topics
  • Commit Log
  • Consumer group

 

After we have talked about these (and I will only be skimming the surface of these, you really would be better off reading about Kafka if this is brand new territory for you), I will then move on to talk about some of the basic building blocks of Kafka Streams

 

Kafka overall architecture

Image result for kafka partitions

 

As shown in the diagram above, Kafka is a broker and is intended to run in a cluster (which might be a single broker, but that is obviously not what’s recommended). It also makes use of Zookeeper for various state storage/metadata.

 

Topics

Kafka uses topics as a way of organizing what data is produced/read. Producers push data to topics, whilst consumers read data from topics.

 

Topics are divided into a number of partitions (there is some default partitioning strategy at play, but you can write you own). Partitions allow you to parallelize the data by potentially storing it across multiple machines. It may also be read in parallel

 

Another key part of a topic is the offset, which is maintained by the consumer, and it’s a indicator at to where the consumer should start reading data from within the topic. As one could imagine for this to be possible the messages must be ordered, this is something that Kafka guarantees for you.

 

Image result for kafka topic

Commit Log

Kafka maintains message for a configurable amount of time. Meaning that a consumer may go down, and restart again, and providing its within the period of log retention, it will just start reading messages from where it left of.

 

Consumer Groups

Kafka has Consumers, which read from a single partition. However Consumers can also be organized into Consumer groups for a Topic. Each Consumer will read from a partition, and the Consumer group as a whole will read the entire Topic. If you organize your consumers in such as way that you have more consumers than partitions, some will go idle. However if you have more partitions than consumers, some consumers will get messages from multiple partitions

 

Image result for kafka consumer group

 

Further Reading

 

As I say I did not want to get too bogged down with the Kafka fundamentals, as this series is really about Kafka Streams, but the few points above as well as the “further reading” section should get you to a pretty decent position to understand the rest of this post.

 

Kafka Streams Introduction

Kafka Streams is a client library for processing and analyzing data stored in Kafka. It builds upon important stream processing concepts such as properly distinguishing between event time and processing time, windowing support, and simple yet efficient management and real-time querying of application state.

Kafka Streams has a low barrier to entry: You can quickly write and run a small-scale proof-of-concept on a single machine; and you only need to run additional instances of your application on multiple machines to scale up to high-volume production workloads. Kafka Streams transparently handles the load balancing of multiple instances of the same application by leveraging Kafka’s parallelism model.

 

Stream Processing Topology

  • A stream is the most important abstraction provided by Kafka Streams: it represents an unbounded, continuously updating data set. A stream is an ordered, replayable, and fault-tolerant sequence of immutable data records, where a data record is defined as a key-value pair.
  • A stream processing application is any program that makes use of the Kafka Streams library. It defines its computational logic through one or more processor topologies, where a processor topology is a graph of stream processors (nodes) that are connected by streams (edges).
  • A stream processor is a node in the processor topology; it represents a processing step to transform data in streams by receiving one input record at a time from its upstream processors in the topology, applying its operation to it, and may subsequently produce one or more output records to its downstream processors.
    There are two special processors in the topology:
    Source Processor: A source processor is a special type of stream processor that does not have any upstream processors. It produces an input stream to its topology from one or multiple Kafka topics by consuming records from these topics and forwarding them to its down-stream processors.
    Sink Processor: A sink processor is a special type of stream processor that does not have down-stream processors. It sends any received records from its up-stream processors to a specified Kafka topic.
    Note that in normal processor nodes other remote systems can also be accessed while processing the current record. Therefore the processed results can either be streamed back into Kafka or written to an external system.

Although this post will not show any code at all, I want to introduce a couple of things that will be coming up in the next posts, namely

  • KStream
  • KTable
  • Global KTable
  • State Stores

 

KStream

A KStream is an abstraction of a record stream, where each data record represents a self-contained datum in the unbounded data set. Using the table analogy, data records in a record stream are always interpreted as an “INSERT” — think: adding more entries to an append-only ledger — because no record replaces an existing row with the same key. Examples are a credit card transaction, a page view event, or a server log entry.

To illustrate, let’s imagine the following two data records are being sent to the stream:

(“alice”, 1) –> (“alice”, 3)

If your stream processing application were to sum the values per user, it would return 4 for alice. Why? Because the second data record would not be considered an update of the previous record.

https://kafka.apache.org/21/documentation/streams/developer-guide/dsl-api.html#streams_concepts_kstream

 

KTable

A KTable is an abstraction of a changelog stream, where each data record represents an update. More precisely, the value in a data record is interpreted as an “UPDATE” of the last value for the same record key, if any (if a corresponding key doesn’t exist yet, the update will be considered an INSERT). Using the table analogy, a data record in a changelog stream is interpreted as an UPSERT aka INSERT/UPDATE because any existing row with the same key is overwritten. Also, null values are interpreted in a special way: a record with a null value represents a “DELETE” or tombstone for the record’s key.

To illustrate, let’s imagine the following two data records are being sent to the stream:

(“alice”, 1) –> (“alice”, 3)

If your stream processing application were to sum the values per user, it would return 3 for alice. Why? Because the second data record would be considered an update of the previous record.

https://kafka.apache.org/21/documentation/streams/developer-guide/dsl-api.html#streams_concepts_ktable

 

GlobalKTable

Like a KTable, a GlobalKTable is an abstraction of a changelog stream, where each data record represents an update.

A GlobalKTable differs from a KTable in the data that they are being populated with, i.e. which data from the underlying Kafka topic is being read into the respective table. Slightly simplified, imagine you have an input topic with 5 partitions. In your application, you want to read this topic into a table. Also, you want to run your application across 5 application instances for maximum parallelism.

  • If you read the input topic into a KTable, then the “local” KTable instance of each application instance will be populated with data from only 1 partition of the topic’s 5 partitions.
  • If you read the input topic into a GlobalKTable, then the local GlobalKTable instance of each application instance will be populated with data from all partitions of the topic.

GlobalKTable provides the ability to look up current values of data records by keys.

https://kafka.apache.org/21/documentation/streams/developer-guide/dsl-api.html#streams_concepts_globalktable

 

State Stores

Kafka Streams provides so-called state stores, which can be used by stream processing applications to store and query data. This is an important capability when implementing stateful operations. Every task in Kafka Streams embeds one or more state stores that can be accessed via APIs to store and query data required for processing. These state stores can either be a persistent key-value store, an in-memory hashmap, or another convenient data structure. Kafka Streams offers fault-tolerance and automatic recovery for local state stores.

Kafka Streams allows direct read-only queries of the state stores by methods, threads, processes or applications external to the stream processing application that created the state stores. This is provided through a feature called Interactive Queries. All stores are named and Interactive Queries exposes only the read operations of the underlying implementation.

https://kafka.apache.org/21/documentation/streams/core-concepts#streams_state

 

That’s It

So that’s it for now. I have borrowed a lot of material from the official docs for this post, but as we move through the series we will start to form our own code/topologies, and as such our own tests/descriptions. So please forgive me this one.

AWS

AWS : ElastiCache

What are we talking about this time?

Last time we talked about AWS DynamoDB, this time we will talk about AWS ElasticCache

Initial setup

If you did not read the very first part of this series of posts, I urge you to go and read that one now as it shows you how to get started with AWS, and create an IAM user : https://sachabarbs.wordpress.com/2018/08/30/aws-initial-setup/

Where is the code

The code for this post can be found here in GitHub :

What are we talking about this time?

This time we will be talking about ElasticCache.

So what exactly is ElasticCache?

ElastiCache is AWSs cache cluster. This comes in 2 flavours

  • Redis
  • MemCached

Where you may use the console to pick your cluster size/VMs

image

I have chosen to use MemCached for this example. So once you have setup a cluster, you will see the nodes created for you in the AWS console. If you go and examine the nodes you can click on one of them, and you should see a dialog similar to this. It shows the nodes configuration end point, and also the actual nodes in the cluster. But it also shows you how to download a client library for use with .NET.

 

image

 

For .NET AWS used the following .NET Memcached client : https://github.com/enyim/EnyimMemcached. So if you did download using the link shown in the above dialog, you should see some DLLs like this

image

So once you have them its really just a job of referencing these 2 Dlls

  • Amazon.ElastiCacheCluster.dll
  • Enyim.Caching.dll

 

The  you should be able to add a App.Config like this (make sure you use the address with the “cfg” in it)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section 
            name="clusterclient" 
            type="Amazon.ElastiCacheCluster.ClusterConfigSettings, Amazon.ElastiCacheCluster" />
    </configSections>

    <clusterclient>
        <!-- the hostname and port values are from step 1 above -->
        <endpoint hostname="sachaXXXXXX.cfg.XXXXXXXXX.cache.amazonaws.com" port="11211" />
    </clusterclient>
</configuration>

And use some simple C# code to write/read from the cache like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.ElastiCacheCluster;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;

namespace ElastiCache.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // instantiate a new client.
            ElastiCacheClusterConfig config = new ElastiCacheClusterConfig();
            MemcachedClient memClient = new MemcachedClient(config);

            // Store the data for 3600 seconds (1hour) in the cluster. 
            // The client will decide which cache host will store this item.
            memClient.Store(StoreMode.Set,"mykey","This is the data value.", TimeSpan.FromMinutes(10));

            var mykey = memClient.Get<string>("mykey");




            Console.ReadLine();
        }
    }
}

And to be honest that is all there really is to it.

 

I guess the final point is, if you do not like this MemCached .NET client, AWS Elasticache is “memcached compatible” so that really means you can use any memcached library of your choosing.

 

Anyway another nice short one, I am saving the AWS Batch one for a rainy day, that post will be quite indepth believe me