KCache - An In-Memory Cache Backed by Apache Kafka

Build Status Maven Javadoc

KCache is a client library that provides an in-memory cache backed by a compacted topic in Kafka. It is one of the patterns for using Kafka as a persistent store, as described by Jay Kreps in the article It's Okay to Store Data in Apache Kafka.

Maven

Releases of KCache are deployed to Maven Central.

<dependency>
    <groupId>io.kcache</groupId>
    <artifactId>kcache</artifactId>
    <version>3.1.1</version>
</dependency>

Usage

An instance of KafkaCache implements the java.util.Map interface. Here is an example usage:

import io.kcache.*;

String bootstrapServers = "localhost:9092";
Cache<String, String> cache = new KafkaCache<>(
    bootstrapServers,
    Serdes.String(),  // for serializing/deserializing keys
    Serdes.String()   // for serializing/deserializing values
);
cache.init();   // creates topic, initializes cache, consumer, and producer
cache.put("Kafka", "Rocks");
String value = cache.get("Kafka");  // returns "Rocks"
cache.remove("Kafka");
cache.close();  // shuts down the cache, consumer, and producer

One can also use RocksDB to back the KafkaCache:

Cache<String, String> rocksDBCache =
    new RocksDBCache<>("rocksdb", "/tmp", Serdes.String(), Serdes.String());
Properties props = new Properties();
props.put(KafkaCacheConfig.KAFKACACHE_BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
Cache<String, String> cache = new KafkaCache<>(
    new KafkaCacheConfig(props),
    Serdes.String(),  // for serializing/deserializing keys
    Serdes.String()   // for serializing/deserializing values
    null,
    rocksDBCache);
cache.init();

Basic Configuration

KCache has a number of configuration properties that can be specified.

Configuration properties can be passed as follows:

Properties props = new Properties();
props.setProperty("kafkacache.bootstrap.servers", "localhost:9092");
props.setProperty("kafkacache.topic", "_mycache");
Cache<String, String> cache = new KafkaCache<>(
    new KafkaCacheConfig(props),
    Serdes.String(),  // for serializing/deserializing keys
    Serdes.String()   // for serializing/deserializing values
);
cache.init();
...

Security

KCache supports both SSL authentication and SASL authentication to a secure Kafka cluster. See the JavaDoc for more information.

Using KCache as a Replicated Cache

KCache can be used as a replicated cache, with some caveats. To ensure that updates are processed in the proper order, one instance of KCache should be designated as the sole writer, with all writes being forwarded to it. If the writer fails, another instance can then be elected as the new writer. The leader election is outside of KCache but can be implemented using ZooKeeper, for example. Reads of course can be served by any instance of KCache.