How can you filter out duplicate events from a Kafka topic based on a field in the event, producing a new stream of unique events per time window?
This tutorial installs Confluent Platform using Docker. Before proceeding:
• Install Docker Desktop (version 4.0.0
or later) or Docker Engine (version 19.03.0
or later) if you don’t already have it
• Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.
• Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd
, via systemctl
• Verify that Docker is set up properly by ensuring no errors are output when you run docker info
and docker compose version
on the command line
To get started, make a new directory anywhere you’d like for this project:
mkdir distinct-events && cd distinct-events
Next, create the following docker-compose.yml
file to configure an instance of the Confluent Platform (on macOS you can paste directly to a file from the copy buffer with pbpaste > docker-compose.yml
):
version: '2'
services:
broker:
image: confluentinc/cp-kafka:7.4.1
hostname: broker
container_name: broker
ports:
- 29092:29092
environment:
KAFKA_BROKER_ID: 1
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_NODE_ID: 1
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
schema-registry:
image: confluentinc/cp-schema-registry:7.3.0
hostname: schema-registry
container_name: schema-registry
depends_on:
- broker
ports:
- 8081:8081
environment:
SCHEMA_REGISTRY_HOST_NAME: schema-registry
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: broker:9092
SCHEMA_REGISTRY_LOG4J_ROOT_LOGLEVEL: WARN
And launch it by running:
docker compose up -d
We’ll use Gradle as our build system. Create a file named build.gradle
with the following contents (on macOS pbpaste > build.gradle
after copying the below):
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "gradle.plugin.com.github.jengelman.gradle.plugins:shadow:7.0.0"
}
}
plugins {
id "java"
id "com.github.davidmc24.gradle.plugin.avro" version "1.7.0"
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
version = "0.0.1"
repositories {
mavenCentral()
maven {
url "https://packages.confluent.io/maven"
}
}
apply plugin: "com.github.johnrengelman.shadow"
dependencies {
implementation "org.apache.avro:avro:1.11.1"
implementation "org.slf4j:slf4j-simple:2.0.7"
implementation "org.apache.kafka:kafka-streams:3.1.0"
implementation "io.confluent:kafka-streams-avro-serde:7.1.0"
testImplementation "org.apache.kafka:kafka-streams-test-utils:3.1.0"
testImplementation "junit:junit:4.13.2"
}
test {
testLogging {
outputs.upToDateWhen { false }
showStandardStreams = true
exceptionFormat = "full"
}
}
jar {
manifest {
attributes(
"Class-Path": configurations.compileClasspath.collect { it.getName() }.join(" "),
"Main-Class": "io.confluent.developer.FindDistinctEvents"
)
}
}
shadowJar {
archiveBaseName = "kstreams-find-distinct-standalone"
archiveClassifier = ''
}
And be sure to run the following command to obtain the Gradle wrapper:
gradle wrapper
Next, create a directory for configuration data:
mkdir configuration
Then create a configuration file for development at configuration/dev.properties
:
application.id=find-distinct-app
bootstrap.servers=127.0.0.1:29092
schema.registry.url=http://127.0.0.1:8081
input.topic.name=clicks
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=distinct-clicks
output.topic.partitions=1
output.topic.replication.factor=1
Create a directory for the schemas that represent the events in the stream:
mkdir -p src/main/avro
Then create the following Avro schema file at src/main/avro/click.avsc
for the click events (on macOS, copy the text then execute in the terminal: pbpaste > src/main/avro/click.avsc
):
{
"namespace": "io.confluent.developer.avro",
"type": "record",
"name": "Click",
"fields": [
{"name": "ip", "type": "string"},
{"name": "url", "type": "string"},
{"name": "timestamp", "type": "string"}
]
}
Because this Avro schema is used in the Java code, it needs to compile it. Run the following:
./gradlew build
Create a directory for the Java files in this project:
mkdir -p src/main/java/io/confluent/developer
Then create the following file at src/main/java/io/confluent/developer/FindDistinctEvents.java
Focusing on the buildTopology
method, note how the Kafka Streams topology relies on a ValueTransformerWithKey
and a Window Store
to filter out the duplicate IP addresses. Events are de-duped within a 2 minute window, and unique clicks are produced to a new topic named distinct-clicks
.
Note that we are using ValueTransformerWithKey
here instead of Transformer
since we need keys to transform data, but there is no need to re-key the stream.
Tranformer
usage will lead to redundant repartitioning when grouping operations are used afterwards.
package io.confluent.developer;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.KeyValueMapper;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.ValueTransformerWithKey;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowStore;
import org.apache.kafka.streams.state.WindowStoreIterator;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import io.confluent.common.utils.TestUtils;
import io.confluent.developer.avro.Click;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
public class FindDistinctEvents {
private static final String storeName = "eventId-store";
/**
* Discards duplicate click events from the input stream by ip address
* <p>
* Duplicate records are detected based on ip address
* The transformer remembers known ip addresses within an associated window state
* store, which automatically purges/expires IPs from the store after a certain amount of
* time has passed to prevent the store from growing indefinitely.
* <p>
* Note: This code is for demonstration purposes and was not tested for production usage.
*/
private static class DeduplicationTransformer<K, V, E> implements ValueTransformerWithKey<K, V, V> {
private ProcessorContext context;
/**
* Key: ip address
* Value: timestamp (event-time) of the corresponding event when the event ID was seen for the
* first time
*/
private WindowStore<E, Long> eventIdStore;
private final long leftDurationMs;
private final long rightDurationMs;
private final KeyValueMapper<K, V, E> idExtractor;
/**
* @param maintainDurationPerEventInMs how long to "remember" a known ip address
* during the time of which any incoming duplicates
* will be dropped, thereby de-duplicating the
* input.
* @param idExtractor extracts a unique identifier from a record by which we de-duplicate input
* records; if it returns null, the record will not be considered for
* de-duping but forwarded as-is.
*/
DeduplicationTransformer(final long maintainDurationPerEventInMs, final KeyValueMapper<K, V, E> idExtractor) {
if (maintainDurationPerEventInMs < 1) {
throw new IllegalArgumentException("maintain duration per event must be >= 1");
}
leftDurationMs = maintainDurationPerEventInMs / 2;
rightDurationMs = maintainDurationPerEventInMs - leftDurationMs;
this.idExtractor = idExtractor;
}
@Override
@SuppressWarnings("unchecked")
public void init(final ProcessorContext context) {
this.context = context;
eventIdStore = (WindowStore<E, Long>) context.getStateStore(storeName);
}
@Override
public V transform(final K key, final V value) {
final E eventId = idExtractor.apply(key, value);
if (eventId == null) {
return value;
} else {
final V output;
if (isDuplicate(eventId)) {
output = null;
updateTimestampOfExistingEventToPreventExpiry(eventId, context.timestamp());
} else {
output = value;
rememberNewEvent(eventId, context.timestamp());
}
return output;
}
}
private boolean isDuplicate(final E eventId) {
final long eventTime = context.timestamp();
final WindowStoreIterator<Long> timeIterator = eventIdStore.fetch(
eventId,
eventTime - leftDurationMs,
eventTime + rightDurationMs);
final boolean isDuplicate = timeIterator.hasNext();
timeIterator.close();
return isDuplicate;
}
private void updateTimestampOfExistingEventToPreventExpiry(final E eventId, final long newTimestamp) {
eventIdStore.put(eventId, newTimestamp, newTimestamp);
}
private void rememberNewEvent(final E eventId, final long timestamp) {
eventIdStore.put(eventId, timestamp, timestamp);
}
@Override
public void close() {
// Note: The store should NOT be closed manually here via `eventIdStore.close()`!
// The Kafka Streams API will automatically close stores when necessary.
}
}
private SpecificAvroSerde<Click> buildClicksSerde(final Properties allProps) {
final SpecificAvroSerde<Click> serde = new SpecificAvroSerde<>();
final Map<String, String> config = (Map)allProps;
serde.configure(config, false);
return serde;
}
public Topology buildTopology(Properties allProps,
final SpecificAvroSerde<Click> clicksSerde) {
final StreamsBuilder builder = new StreamsBuilder();
final String inputTopic = allProps.getProperty("input.topic.name");
final String outputTopic = allProps.getProperty("output.topic.name");
// How long we "remember" an event. During this time, any incoming duplicates of the event
// will be, well, dropped, thereby de-duplicating the input data.
//
// The actual value depends on your use case. To reduce memory and disk usage, you could
// decrease the size to purge old windows more frequently at the cost of potentially missing out
// on de-duplicating late-arriving records.
final Duration windowSize = Duration.ofMinutes(2);
// retention period must be at least window size -- for this use case, we don't need a longer retention period
// and thus just use the window size as retention time
final Duration retentionPeriod = windowSize;
final StoreBuilder<WindowStore<String, Long>> dedupStoreBuilder = Stores.windowStoreBuilder(
Stores.persistentWindowStore(storeName,
retentionPeriod,
windowSize,
false
),
Serdes.String(),
Serdes.Long());
builder.addStateStore(dedupStoreBuilder);
builder
.stream(inputTopic, Consumed.with(Serdes.String(), clicksSerde))
.transformValues(() -> new DeduplicationTransformer<>(windowSize.toMillis(), (key, value) -> value.getIp()), storeName)
.filter((k, v) -> v != null)
.to(outputTopic, Produced.with(Serdes.String(), clicksSerde));
return builder.build();
}
public void createTopics(Properties allProps) {
AdminClient client = AdminClient.create(allProps);
List<NewTopic> topics = new ArrayList<>();
topics.add(new NewTopic(
allProps.getProperty("input.topic.name"),
Integer.parseInt(allProps.getProperty("input.topic.partitions")),
Short.parseShort(allProps.getProperty("input.topic.replication.factor"))));
topics.add(new NewTopic(
allProps.getProperty("output.topic.name"),
Integer.parseInt(allProps.getProperty("output.topic.partitions")),
Short.parseShort(allProps.getProperty("output.topic.replication.factor"))));
client.createTopics(topics);
client.close();
}
public static Properties loadEnvProperties(String fileName) throws IOException {
Properties allProps = new Properties();
FileInputStream input = new FileInputStream(fileName);
allProps.load(input);
input.close();
return allProps;
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
throw new IllegalArgumentException(
"This program takes one argument: the path to an environment configuration file.");
}
new FindDistinctEvents().runRecipe(args[0]);
}
private void runRecipe(final String configPath) throws IOException {
final Properties allProps = new Properties();
try (InputStream inputStream = new FileInputStream(configPath)) {
allProps.load(inputStream);
}
allProps.put(StreamsConfig.APPLICATION_ID_CONFIG, allProps.getProperty("application.id"));
allProps.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());
final Topology topology = this.buildTopology(allProps, this.buildClicksSerde(allProps));
this.createTopics(allProps);
final KafkaStreams streams = new KafkaStreams(topology, allProps);
final CountDownLatch latch = new CountDownLatch(1);
// Attach shutdown handler to catch Control-C.
Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
@Override
public void run() {
streams.close(Duration.ofSeconds(5));
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
In your terminal, run:
./gradlew shadowJar
Now that an uberjar for the Kafka Streams application has been built, you can launch it locally. When you run the following, the prompt won’t return, because the application will run until you exit it (Ctrl-C
). Run the application in a separate terminal in order to see any output as well as continue with the remaining instructions in the current terminal. The Kafka Streams application should produce a log entry similar to this State transition from REBALANCING to RUNNING
to indicate it’s functioning correctly.
java -jar build/libs/kstreams-find-distinct-standalone-0.0.1.jar configuration/dev.properties
In a new terminal, run:
docker exec -i schema-registry /usr/bin/kafka-avro-console-producer --topic clicks --bootstrap-server broker:9092 --property value.schema="$(< src/main/avro/click.avsc)"
When the console producer starts it may log some informational messages, and then it will pause, waiting to read input from the terminal. Below are sample events you can paste into the terminal one at a time. Press enter to send each record after pasting. (Note: if the client encounters a SerializationException, that’s likely because a stray newline was included in the pasted content.)
In the next steps we will run a consumer to observe the distinct click events. You can experiment with various orderings of the records in order to observe what makes a click event distinct. By default the distinct event window store looks for distinct clicks over a 2-minute duration.
{"ip":"10.0.0.1","url":"https://docs.confluent.io/current/tutorials/examples/kubernetes/gke-base/docs/index.html","timestamp":"2019-09-16T14:53:43+00:00"}
{"ip":"10.0.0.2","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:01"}
{"ip":"10.0.0.3","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:03"}
{"ip":"10.0.0.1","url":"https://docs.confluent.io/current/tutorials/examples/kubernetes/gke-base/docs/index.html","timestamp":"2019-09-16T14:53:43+00:00"}
{"ip":"10.0.0.2","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:01"}
{"ip":"10.0.0.3","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:03"}
Leave your previous terminal running and open a new one that will run a consumer to view the distinct click events:
docker exec -it schema-registry /usr/bin/kafka-avro-console-consumer --topic distinct-clicks --bootstrap-server broker:9092 --from-beginning
Depending on the cadence and values you produce in the steps above, you should see messages similar to the following:
{"ip":"10.0.0.1","url":"https://docs.confluent.io/current/tutorials/examples/kubernetes/gke-base/docs/index.html","timestamp":"2019-09-16T14:53:43+00:00"}
{"ip":"10.0.0.2","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:01"}
{"ip":"10.0.0.3","url":"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen","timestamp":"2019-09-16T14:53:43+00:03"}
First, create a test file at configuration/test.properties
:
application.id=find-distinct-app
bootstrap.servers=127.0.0.1:29092
schema.registry.url=mock://SR_CLOUD_DUMMY_URL:8081
input.topic.name=clicks
input.topic.partitions=1
input.topic.replication.factor=1
output.topic.name=distinct-clicks
output.topic.partitions=1
output.topic.replication.factor=1
Then, create a directory for the tests to live in:
mkdir -p src/test/java/io/confluent/developer
Create the following test file at src/test/java/io/confluent/developer/FindDistinctEventsTest.java
. Testing a Kafka Streams application requires a bit of test harness code, but happily the org.apache.kafka.streams.TopologyTestDriver
class makes this much more pleasant than it would otherwise be.
There is a test method in FindDistinctEventsTest
annotated with @Test
: shouldFilterDistinctEvents()
which follows the common Arrange Act Assert (AAA) pattern. This is a simple method that runs our Streams topology using the TopologyTestDriver
and some mocked data that is set up inside the test method.
package io.confluent.developer;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;
import io.confluent.developer.avro.Click;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import static java.util.Arrays.asList;
public class FindDistinctEventsTest {
private final static String TEST_CONFIG_FILE = "configuration/test.properties";
private final static Path STATE_DIR =
Paths.get(System.getProperty("user.dir"), "build");
private final Properties allProps;
public FindDistinctEventsTest() throws IOException {
allProps = FindDistinctEvents.loadEnvProperties(TEST_CONFIG_FILE);
allProps.put(StreamsConfig.STATE_DIR_CONFIG, STATE_DIR.toString());
}
private static SpecificAvroSerde<Click> makeSerializer(Properties allProps) {
SpecificAvroSerde<Click> serde = new SpecificAvroSerde<>();
Map<String, String> config = new HashMap<>();
config.put("schema.registry.url", allProps.getProperty("schema.registry.url"));
serde.configure(config, false);
return serde;
}
@Test
public void shouldFilterDistinctEvents() {
final FindDistinctEvents distinctifier = new FindDistinctEvents();
String inputTopic = allProps.getProperty("input.topic.name");
String outputTopic = allProps.getProperty("output.topic.name");
final SpecificAvroSerde<Click> clickSerde = makeSerializer(allProps);
Topology topology = distinctifier.buildTopology(allProps, clickSerde);
final List<Click> expectedOutput;
List<Click> actualOutput;
try (TopologyTestDriver testDriver = new TopologyTestDriver(topology, allProps)) {
Serializer<String> keySerializer = Serdes.String().serializer();
final List<Click> clicks = asList(
new Click("10.0.0.1",
"https://docs.confluent.io/current/tutorials/examples/kubernetes/gke-base/docs/index.html",
"2019-09-16T14:53:43+00:00"),
new Click("10.0.0.2",
"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen",
"2019-09-16T14:53:43+00:01"),
new Click("10.0.0.3",
"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen",
"2019-09-16T14:53:43+00:03"),
new Click("10.0.0.1",
"https://docs.confluent.io/current/tutorials/examples/kubernetes/gke-base/docs/index.html",
"2019-09-16T14:53:43+00:00"),
new Click("10.0.0.2",
"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen",
"2019-09-16T14:53:43+00:01"),
new Click("10.0.0.3",
"https://www.confluent.io/hub/confluentinc/kafka-connect-datagen",
"2019-09-16T14:53:43+00:03"));
final TestInputTopic<String, Click>
testDriverInputTopic =
testDriver.createInputTopic(inputTopic, keySerializer, clickSerde.serializer());
clicks.forEach(clk -> testDriverInputTopic.pipeInput(clk.getIp(), clk));
expectedOutput = asList(clicks.get(0), clicks.get(1), clicks.get(2));
Deserializer<String> keyDeserializer = Serdes.String().deserializer();
actualOutput =
testDriver.createOutputTopic(outputTopic, keyDeserializer, clickSerde.deserializer()).readValuesToList()
.stream().filter(
Objects::nonNull).collect(Collectors.toList());
}
Assert.assertEquals(expectedOutput, actualOutput);
}
}
Now run the test, which is as simple as:
./gradlew test
Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.
Sign up for Confluent Cloud, a fully managed Apache Kafka service.
After you log in to Confluent Cloud Console, click Environments
in the lefthand navigation, click on Add cloud environment
, and name the environment learn-kafka
. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.
From the Billing & payment
section in the menu, apply the promo code CC100KTS
to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1
. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.
Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.
Next, from the Confluent Cloud Console, click on Clients
to get the cluster-specific configurations, e.g., Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.
In the case of this tutorial, add the following properties to the client application’s input properties file, substituting all curly braces with your Confluent Cloud values.
# Required connection configs for Kafka producer, consumer, and admin
bootstrap.servers={{ BROKER_ENDPOINT }}
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username='{{ CLUSTER_API_KEY }}' password='{{ CLUSTER_API_SECRET }}';
sasl.mechanism=PLAIN
# Required for correctness in Apache Kafka clients prior to 2.6
client.dns.lookup=use_all_dns_ips
# Best practice for Kafka producer to prevent data loss
acks=all
# Required connection configs for Confluent Cloud Schema Registry
schema.registry.url=https://{{ SR_ENDPOINT }}
basic.auth.credentials.source=USER_INFO
schema.registry.basic.auth.user.info={{ SR_API_KEY }}:{{ SR_API_SECRET }}
Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.