SlideShare une entreprise Scribd logo
1  sur  46
Join the Confluent
Community Slack
Channel
Subscribe to the
Confluent blog
cnfl.io/community-slack cnfl.io/read
Welcome to the Boston Apache Kafka® Meetup!
5:30pm-6:00pm:
Doors Open, Networking, Pizza and
Drinks
6:00pm - 6:45pm:
Bill Bejeck, Confluent
6:45pm-7:00 pm:
Break/Networking
7:00pm - 7:45pm:
Bill Scott, Jacob Zweifel & Srinivas
of Tribal Scale, Cupcakes, Kafka,
and .NET CoreApache, Apache Kafka, Kafka and the Kafka logo are trademarks of the Apache Software Foundation. The Apache Software Foundation has no affiliation
with and does not endorse the materials provided at this event.
2
Kick Your Database to the Curb
Using Kafka Streams Interactive Queries to Enable
Powerful MicroServices
3
Brief Introduction
• Worked at Confluent (Streams Team) 2 years
• Apache Kafka Committer
• Author Kafka Streams in Action
Special thanks to @gamussa!
4
Agenda
• What is State
• Kafka Streams Overview
• Describe Interactive Queries
• Live Demo!
5
Stateful Stream Processing
What is State?
6
Stateful Stream Processing
What is State?
Information your application needs to remember
beyond the scope of a single record
GroupBy Example
public static void main(String[] args) {
int counter = 0;
int sendInterval = 15;
Map<String, Integer> groupByCounts = new HashMap<>();
try(..consumer = new KafkaConsumer<>(consumerProperties());
..producer = new KafkaProducer<>(producerProperties())){
consumer.subscribe(Arrays.asList(”A”,”B”));
GroupBy Example
while (true) {
ConsumerRecords<String, String> records =
consumer.poll(Duration.ofSeconds(5));
for (ConsumerRecord<String, String> record : records) {
String key = record.key();
Integer count = groupByCounts.get(key);
if (count == null) {
count = 0;
}
count += 1;
groupByCounts.put(key, count);
}
GroupBy Example
while (true) {
ConsumerRecords<String, String> records =
consumer.poll(Duration.ofSeconds(5));
for (ConsumerRecord<String, String> record : records) {
String key = record.key();
Integer count = groupByCounts.get(key);
if (count == null) {
count = 0;
}
count += 1;
groupByCounts.put(key, count);
}
GroupBy Example
if(counter++ % sendInterval == 0) {
for(Entry<String, Integer> groupedEntry:groupByCounts.entrySet()){
ProducerRecord<String, Integer> producerRecord =
new ProducerRecord<>("group-by-counts",
groupedEntry.getKey(),
groupedEntry.getValue());
producer.send(producerRecord);
}
consumer.commitSync();
}
GroupBy Example
if(counter++ % sendInterval == 0) {
for(Entry<String, Integer> groupedEntry:groupByCounts.entrySet()){
ProducerRecord<String, Integer> producerRecord =
new ProducerRecord<>("group-by-counts",
groupedEntry.getKey(),
groupedEntry.getValue());
producer.send(producerRecord);
}
consumer.commitSync();
}
12
Streams GroupBy
...
stream = streamBuilder.stream(Arrays.asList(“A”, “B”))
stream.groupByKey()
.count()
.toStream()
.to(“output-topic”,
Produced.with(Serdes.String(), Serdes.Long()))
13
Streams GroupBy
...
stream = streamBuilder.stream(Arrays.asList(“A”, “B”))
stream.groupByKey()
.count()
.toStream()
.to(“output-topic”,
Produced.with(Serdes.String(), Serdes.Long()))
14
Streams GroupBy
...
stream = streamBuilder.stream(Arrays.asList(“A”, “B”))
stream.groupByKey()
.count()
.toStream()
.to(“output-topic”,
Produced.with(Serdes.String(), Serdes.Long()))
15
Stateful Stream Processing
Streams Stateful Operations
• Joins
• Windowing operations
• Aggregation/Reduce
Using any of these operations, Streams creates a state
store
16
Making Streams Results Queryable
Kafka Streams Application
KAFKA
External Application /
REST Service
17
Making Streams Results Queryable
Kafka Streams Application
KAFKA
External Application /
REST Service
Database
18
Making Streams Results Queryable
Kafka Streams Application
KAFKA
External Application /
REST Service
Database
19
Making Streams Queryable
stream.groupByKey()
.count()
.toStream()
.to(“output-topic”,
Produced.with(Serdes.String(), Serdes.Long()))
..
consumer.poll(Duration.ofSeconds(5));
for (ConsumerRecord<String, String> record : records) {
someService.save(record.key(), record.value())
..
}
..
20
Making Streams State Directly Queryable
...
stream = streamBuilder.stream(Arrays.asList(“A”, “B”))
stream.groupByKey()
.count(Materialized.as(“count-store”))
.toStream()
.to(“output-topic”,
Produced.with(Serdes.String(), Serdes.Long()))
21
Making Streams State Directly Queryable
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG,
"ks-interactive-stock-analysis-appid");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:9092");
properties.put(StreamsConfig.APPLICATION_SERVER_CONFIG,
host+":"+port);
...
22
Making Streams State Directly Queryable
Kafka Streams Application
KAFKA
Embedded RPC
23
What’s with the APPLICATION_SERVER_ID
• A single Streams instance doesn’t contain all keys
• Streams will query other instances for store misses
• A single Streams instance can be proxy for all instances
25
Making Streams Results Queryable
Streams app “A”
Host = hostA:4567
KAFKA
Streams app “B”
Host = hostB:4568
26
Making Streams Results Queryable
Streams app “A”
Host = hostA:4567
Metadata -> hostB:4568
KAFKA
Streams app “B”
Host = hostB:4568
Metadata -> hostA:4567
27
Topic Partitions and Streams Tasks
Streams app “A”
Host = hostA:4567
Streams app “B”
Host = hostB:4568
State Store State Store
Topic with four partitions
Four partitions are converted to 4 tasks so
each streams application is assigned 2
partitions/tasks
28
Making Streams Results Queryable
Streams app “A”
Host = hostA:4567
Streams app “B”
Host = hostB:4568
State Store State Store
{“ENERGY”:”10000”} written to
partition 0 assigned to App A
{“FINANCE”:”11000”} written to
partition 1 assigned to App B
29
Making Streams Results Queryable
Streams app “A”
Host = hostA:4567
Streams app “B”
Host = hostB:4568
State Store State Store
{“ENERGY”:”10000”} written to
partition 0 assigned to App A
{“FINANCE”:”11000”} written to
partition 1 assigned to App B
http://hostA:4567?key=FINANCE
30
Example of a Streams RPC
Kafka Streams Application
KAFKA
{ JS }
Demo Time!
31
Embedding the Web Server
KafkaStreams kafkaStreams =
new KafkaStreams(builder.build(), streamsConfig);
InteractiveQueryServer queryServer =
new InteractiveQueryServer(kafkaStreams, hostInfo);
32
Embedding the Web Server
.
kafkaStreams.setStateListener(((newState, oldState) -> {
if (newState == KafkaStreams.State.RUNNING
&& oldState == KafkaStreams.State.REBALANCING) {
queryServer.setReady(true);
} else if (newState != KafkaStreams.State.RUNNING) {
queryServer.setReady(false);
}
}))
33
Embedding the Web Server
.
kafkaStreams.setStateListener(((newState, oldState) -> {
if (newState == KafkaStreams.State.RUNNING
&& oldState == KafkaStreams.State.REBALANCING) {
queryServer.setReady(true);
} else if (newState != KafkaStreams.State.RUNNING) {
queryServer.setReady(false);
}
}))
34
Embedding the Web Server
public void init() {
get("/window/:store/:key/:from/:to", (req, res) -> ready ?
fetchFromWindowStore(req.params()) : STORES_NOT_ACCESSIBLE);
get("/window/:store/:key", (req, res) -> ready ?
fetchFromWindowStore(req.params()) : STORES_NOT_ACCESSIBLE);
get("/kv/:store", (req, res) -> ready ? fetchAllFromKeyValueStore(req.params()) :
STORES_NOT_ACCESSIBLE);
get("/kv/:store/:local", (req, res) -> ready ?
fetchAllFromLocalKeyValueStore(req.params()) : STORES_NOT_ACCESSIBLE);
get("/session/:store/:key",
(req, res) -> ready ?
fetchFromSessionStore(req.params()) : STORES_NOT_ACCESSIBLE);
get("/iq",
(req, res) -> {
res.redirect("interactiveQueriesApplication.html");
return "";
});
35
Embedding the Web Server
fetchFromSessionStore(Map<String, String> params) {
String store = params.get(STORE_PARAM);
String key = params.get(KEY_PARAM);
HostInfo storeHostInfo = getHostInfo(store, key);
if (storeHostInfo.host().equals("unknown")) {
return STORES_NOT_ACCESSIBLE;
}
if (dataNotLocal(storeHostInfo)) {
return fetchRemote(storeHostInfo, "session", params);
}
ReadOnlySessionStore<String, CustomerTransactions> readOnlySessionStore = kafkaStreams.store(store,
QueryableStoreTypes.sessionStore());
36
Embedding the Web Server
getHostInfo(String storeName, String key) {
StreamsMetadata metadata =
kafkaStreams.metadataForKey(storeName, key, stringSerializer);
return metadata.hostInfo();
}
37
Embedding the Web Server
fetchFromSessionStore(Map<String, String> params) {
String store = params.get(STORE_PARAM);
String key = params.get(KEY_PARAM);
HostInfo storeHostInfo = getHostInfo(store, key);
if (storeHostInfo.host().equals("unknown")) {
return STORES_NOT_ACCESSIBLE;
}
if (dataNotLocal(storeHostInfo)) {
return fetchRemote(storeHostInfo, "session", params);
}
ReadOnlySessionStore<String, CustomerTransactions> readOnlySessionStore = kafkaStreams.store(store,
QueryableStoreTypes.sessionStore());
38
Embedding the Web Server
fetchFromSessionStore(Map<String, String> params) {
String store = params.get(STORE_PARAM);
String key = params.get(KEY_PARAM);
HostInfo storeHostInfo = getHostInfo(store, key);
if (storeHostInfo.host().equals("unknown")) {
return STORES_NOT_ACCESSIBLE;
}
if (dataNotLocal(storeHostInfo)) {
return fetchRemote(storeHostInfo, "session", params);
}
ReadOnlySessionStore<String, CustomerTransactions>
readOnlySessionStore = kafkaStreams.store(
store,
QueryableStoreTypes.sessionStore());
39
Embedding the Web Server
fetchFromSessionStore(Map<String, String> params) {
String store = params.get(STORE_PARAM);
String key = params.get(KEY_PARAM);
HostInfo storeHostInfo = getHostInfo(store, key);
if (storeHostInfo.host().equals("unknown")) {
return STORES_NOT_ACCESSIBLE;
}
if (dataNotLocal(storeHostInfo)) {
return fetchRemote(storeHostInfo, "session", params);
}
// Iterate over readOnlySessionStore and
// store results in a list sessionResults
return gson.toJson(sessionResults);
40
Client View Development
<body>
<h2>Kafka Streams Equities Dashboard Application</h2>
<!–- Other div elements left out for clarity -->
<div id="sessionDiv">
<h3 id="sessionHeader">Customer Session Equity Activity Table</h3>
<table id="sessionTable">
<tr>
<th>Customer Id</th>
<th>Average Equity Transaction Spent Per Session</th>
</tr>
</table>
</div>
</body>
41
Client View Development
<script>
function loadIqTables() {
$.getJSON("/kv/TransactionsBySector", function (response) {
updateTable(response, $('#txnsTable'))
$('#txnsHeader').animate({color:'red'},500).animate({color:'#CCCCCC'}, 500)
})
updateTableWithList("/window/NumberSharesPerPeriod/", symbols,
$('#stockTable'), $('#stockHeader'));
updateTableWithList("/session/CustomerPurchaseSessions/", customers,
$('#sessionTable'), $('#sessionHeader'))
}
setInterval(loadIqTables, 7000);
</script>
42
Client View Development
<script>
function loadIqTables() {
$.getJSON("/kv/TransactionsBySector", function (response) {
updateTable(response, $('#txnsTable'))
$('#txnsHeader').animate({color:'red'},500).animate({color:'#CCCCCC'}, 500)
})
updateTableWithList("/window/NumberSharesPerPeriod/", symbols,
$('#stockTable'), $('#stockHeader'));
updateTableWithList("/session/CustomerPurchaseSessions/", customers,
$('#sessionTable'), $('#sessionHeader'))
}
setInterval(loadIqTables, 7000);
</script>
43
Summary
Interactive Queries is a powerful abstraction that
simplifies stateful stream processing
There are still cases for which external database/storage
might be a better
44
Summary
Kafka Streams in Action Examples: https://github.com/bbejeck/kafka-streams-in-
action/blob/master/src/main/java/bbejeck/webserver/InteractiveQueryServer.java
Music example: https://github.com/confluentinc/examples/blob/master/kafka-
streams/src/main/java/io/confluent/examples/streams/interactivequeries/kafkamusic/
KafkaMusicExample.java
Streaming Movie Ratings: https://github.com/confluentinc/demo-
scene/tree/master/streams-movie-demo
45
Thanks!
Stay in Touch!
• https://slackpass.io/confluentcommunity
• https://www.confluent.io/blog/
• Twitter @bbejeck
• We are hiring! https://www.confluent.io/careers/
NOMINATE YOURSELF OR A PEER AT
CONFLUENT.IO/NOMINATE
KS19Meetup.
CONFLUENT COMMUNITY DISCOUNT CODE
25% OFF*
*Standard Priced Conference pass

Contenu connexe

Tendances

Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams Johan Andrén
 
Safely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAMSafely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAMJonathan Katz
 
Kafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processingKafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processingYaroslav Tkachenko
 
Ireland OUG Meetup May 2017
Ireland OUG Meetup May 2017Ireland OUG Meetup May 2017
Ireland OUG Meetup May 2017Brendan Tierney
 
Building a near real time search engine & analytics for logs using solr
Building a near real time search engine & analytics for logs using solrBuilding a near real time search engine & analytics for logs using solr
Building a near real time search engine & analytics for logs using solrlucenerevolution
 
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...Guozhang Wang
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackJakub Hajek
 
Event stream processing using Kafka streams
Event stream processing using Kafka streamsEvent stream processing using Kafka streams
Event stream processing using Kafka streamsFredrik Vraalsen
 
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...confluent
 
If you give a mouse a clickhouse, by Alex Hofsteede, Sentry
If you give a mouse a clickhouse, by Alex Hofsteede, SentryIf you give a mouse a clickhouse, by Alex Hofsteede, Sentry
If you give a mouse a clickhouse, by Alex Hofsteede, SentryAltinity Ltd
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...HostedbyConfluent
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streamsconfluent
 
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...StampedeCon
 
Taming HBase with Apache Phoenix and SQL
Taming HBase with Apache Phoenix and SQLTaming HBase with Apache Phoenix and SQL
Taming HBase with Apache Phoenix and SQLHBaseCon
 
Integrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applicationsIntegrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applicationslucenerevolution
 
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and StreamingUsing Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and StreamingDatabricks
 
Get Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAMGet Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAMJonathan Katz
 
Spark Programming
Spark ProgrammingSpark Programming
Spark ProgrammingTaewook Eom
 
"How about no grep and zabbix?". ELK based alerts and metrics.
"How about no grep and zabbix?". ELK based alerts and metrics."How about no grep and zabbix?". ELK based alerts and metrics.
"How about no grep and zabbix?". ELK based alerts and metrics.Vladimir Pavkin
 
Apache Big Data EU 2015 - Phoenix
Apache Big Data EU 2015 - PhoenixApache Big Data EU 2015 - Phoenix
Apache Big Data EU 2015 - PhoenixNick Dimiduk
 

Tendances (20)

Streaming all the things with akka streams
Streaming all the things with akka streams   Streaming all the things with akka streams
Streaming all the things with akka streams
 
Safely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAMSafely Protect PostgreSQL Passwords - Tell Others to SCRAM
Safely Protect PostgreSQL Passwords - Tell Others to SCRAM
 
Kafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processingKafka Streams: the easiest way to start with stream processing
Kafka Streams: the easiest way to start with stream processing
 
Ireland OUG Meetup May 2017
Ireland OUG Meetup May 2017Ireland OUG Meetup May 2017
Ireland OUG Meetup May 2017
 
Building a near real time search engine & analytics for logs using solr
Building a near real time search engine & analytics for logs using solrBuilding a near real time search engine & analytics for logs using solr
Building a near real time search engine & analytics for logs using solr
 
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...
Consistency and Completeness: Rethinking Distributed Stream Processing in Apa...
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
 
Event stream processing using Kafka streams
Event stream processing using Kafka streamsEvent stream processing using Kafka streams
Event stream processing using Kafka streams
 
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...
Kafka Summit NYC 2017 - Singe Message Transforms are not the Transformations ...
 
If you give a mouse a clickhouse, by Alex Hofsteede, Sentry
If you give a mouse a clickhouse, by Alex Hofsteede, SentryIf you give a mouse a clickhouse, by Alex Hofsteede, Sentry
If you give a mouse a clickhouse, by Alex Hofsteede, Sentry
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
 
Robust Operations of Kafka Streams
Robust Operations of Kafka StreamsRobust Operations of Kafka Streams
Robust Operations of Kafka Streams
 
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
Beyond the Query – Bringing Complex Access Patterns to NoSQL with DataStax - ...
 
Taming HBase with Apache Phoenix and SQL
Taming HBase with Apache Phoenix and SQLTaming HBase with Apache Phoenix and SQL
Taming HBase with Apache Phoenix and SQL
 
Integrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applicationsIntegrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applications
 
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and StreamingUsing Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
 
Get Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAMGet Your Insecure PostgreSQL Passwords to SCRAM
Get Your Insecure PostgreSQL Passwords to SCRAM
 
Spark Programming
Spark ProgrammingSpark Programming
Spark Programming
 
"How about no grep and zabbix?". ELK based alerts and metrics.
"How about no grep and zabbix?". ELK based alerts and metrics."How about no grep and zabbix?". ELK based alerts and metrics.
"How about no grep and zabbix?". ELK based alerts and metrics.
 
Apache Big Data EU 2015 - Phoenix
Apache Big Data EU 2015 - PhoenixApache Big Data EU 2015 - Phoenix
Apache Big Data EU 2015 - Phoenix
 

Similaire à Kick Your Database to the Curb

From Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata SingaporeFrom Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata SingaporeOfir Sharony
 
What is Apache Kafka and What is an Event Streaming Platform?
What is Apache Kafka and What is an Event Streaming Platform?What is Apache Kafka and What is an Event Streaming Platform?
What is Apache Kafka and What is an Event Streaming Platform?confluent
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Bartosz Konieczny
 
NDC London 2017 - The Data Dichotomy- Rethinking Data and Services with Streams
NDC London 2017  - The Data Dichotomy- Rethinking Data and Services with StreamsNDC London 2017  - The Data Dichotomy- Rethinking Data and Services with Streams
NDC London 2017 - The Data Dichotomy- Rethinking Data and Services with StreamsBen Stopford
 
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...HostedbyConfluent
 
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...confluent
 
Apache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingApache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingGuozhang Wang
 
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka StreamsKafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streamsconfluent
 
Real-Time Stream Processing with KSQL and Apache Kafka
Real-Time Stream Processing with KSQL and Apache KafkaReal-Time Stream Processing with KSQL and Apache Kafka
Real-Time Stream Processing with KSQL and Apache Kafkaconfluent
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!Guido Schmutz
 
Richmond kafka streams intro
Richmond kafka streams introRichmond kafka streams intro
Richmond kafka streams introconfluent
 
Exactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsExactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsGuozhang Wang
 
APAC ksqlDB Workshop
APAC ksqlDB WorkshopAPAC ksqlDB Workshop
APAC ksqlDB Workshopconfluent
 
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...Matt Stubbs
 
Riviera Jug - 20/03/2018 - KSQL
Riviera Jug - 20/03/2018 - KSQLRiviera Jug - 20/03/2018 - KSQL
Riviera Jug - 20/03/2018 - KSQLFlorent Ramiere
 
Genji: Framework for building resilient near-realtime data pipelines
Genji: Framework for building resilient near-realtime data pipelinesGenji: Framework for building resilient near-realtime data pipelines
Genji: Framework for building resilient near-realtime data pipelinesSwami Sundaramurthy
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with ScarletZhixuan Lai
 
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...HostedbyConfluent
 
KSQL: Open Source Streaming for Apache Kafka
KSQL: Open Source Streaming for Apache KafkaKSQL: Open Source Streaming for Apache Kafka
KSQL: Open Source Streaming for Apache Kafkaconfluent
 
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!confluent
 

Similaire à Kick Your Database to the Curb (20)

From Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata SingaporeFrom Kafka to BigQuery - Strata Singapore
From Kafka to BigQuery - Strata Singapore
 
What is Apache Kafka and What is an Event Streaming Platform?
What is Apache Kafka and What is an Event Streaming Platform?What is Apache Kafka and What is an Event Streaming Platform?
What is Apache Kafka and What is an Event Streaming Platform?
 
Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡Apache Spark Structured Streaming + Apache Kafka = ♡
Apache Spark Structured Streaming + Apache Kafka = ♡
 
NDC London 2017 - The Data Dichotomy- Rethinking Data and Services with Streams
NDC London 2017  - The Data Dichotomy- Rethinking Data and Services with StreamsNDC London 2017  - The Data Dichotomy- Rethinking Data and Services with Streams
NDC London 2017 - The Data Dichotomy- Rethinking Data and Services with Streams
 
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...
Building an Interactive Query Service in Kafka Streams With Bill Bejeck | Cur...
 
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...
Using Location Data to Showcase Keys, Windows, and Joins in Kafka Streams DSL...
 
Apache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingApache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream Processing
 
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka StreamsKafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
Kafka Summit SF 2017 - Exactly-once Stream Processing with Kafka Streams
 
Real-Time Stream Processing with KSQL and Apache Kafka
Real-Time Stream Processing with KSQL and Apache KafkaReal-Time Stream Processing with KSQL and Apache Kafka
Real-Time Stream Processing with KSQL and Apache Kafka
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!
 
Richmond kafka streams intro
Richmond kafka streams introRichmond kafka streams intro
Richmond kafka streams intro
 
Exactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka StreamsExactly-once Stream Processing with Kafka Streams
Exactly-once Stream Processing with Kafka Streams
 
APAC ksqlDB Workshop
APAC ksqlDB WorkshopAPAC ksqlDB Workshop
APAC ksqlDB Workshop
 
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...
Big Data LDN 2017: Look Ma, No Code! Building Streaming Data Pipelines With A...
 
Riviera Jug - 20/03/2018 - KSQL
Riviera Jug - 20/03/2018 - KSQLRiviera Jug - 20/03/2018 - KSQL
Riviera Jug - 20/03/2018 - KSQL
 
Genji: Framework for building resilient near-realtime data pipelines
Genji: Framework for building resilient near-realtime data pipelinesGenji: Framework for building resilient near-realtime data pipelines
Genji: Framework for building resilient near-realtime data pipelines
 
Taming WebSocket with Scarlet
Taming WebSocket with ScarletTaming WebSocket with Scarlet
Taming WebSocket with Scarlet
 
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...
Interactive Query in Kafka Streams: The Next Generation with Vasiliki Papavas...
 
KSQL: Open Source Streaming for Apache Kafka
KSQL: Open Source Streaming for Apache KafkaKSQL: Open Source Streaming for Apache Kafka
KSQL: Open Source Streaming for Apache Kafka
 
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!
Apache Kafka and KSQL in Action: Let's Build a Streaming Data Pipeline!
 

Dernier

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Dernier (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Kick Your Database to the Curb

  • 1. Join the Confluent Community Slack Channel Subscribe to the Confluent blog cnfl.io/community-slack cnfl.io/read Welcome to the Boston Apache Kafka® Meetup! 5:30pm-6:00pm: Doors Open, Networking, Pizza and Drinks 6:00pm - 6:45pm: Bill Bejeck, Confluent 6:45pm-7:00 pm: Break/Networking 7:00pm - 7:45pm: Bill Scott, Jacob Zweifel & Srinivas of Tribal Scale, Cupcakes, Kafka, and .NET CoreApache, Apache Kafka, Kafka and the Kafka logo are trademarks of the Apache Software Foundation. The Apache Software Foundation has no affiliation with and does not endorse the materials provided at this event.
  • 2. 2 Kick Your Database to the Curb Using Kafka Streams Interactive Queries to Enable Powerful MicroServices
  • 3. 3 Brief Introduction • Worked at Confluent (Streams Team) 2 years • Apache Kafka Committer • Author Kafka Streams in Action Special thanks to @gamussa!
  • 4. 4 Agenda • What is State • Kafka Streams Overview • Describe Interactive Queries • Live Demo!
  • 6. 6 Stateful Stream Processing What is State? Information your application needs to remember beyond the scope of a single record
  • 7. GroupBy Example public static void main(String[] args) { int counter = 0; int sendInterval = 15; Map<String, Integer> groupByCounts = new HashMap<>(); try(..consumer = new KafkaConsumer<>(consumerProperties()); ..producer = new KafkaProducer<>(producerProperties())){ consumer.subscribe(Arrays.asList(”A”,”B”));
  • 8. GroupBy Example while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5)); for (ConsumerRecord<String, String> record : records) { String key = record.key(); Integer count = groupByCounts.get(key); if (count == null) { count = 0; } count += 1; groupByCounts.put(key, count); }
  • 9. GroupBy Example while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5)); for (ConsumerRecord<String, String> record : records) { String key = record.key(); Integer count = groupByCounts.get(key); if (count == null) { count = 0; } count += 1; groupByCounts.put(key, count); }
  • 10. GroupBy Example if(counter++ % sendInterval == 0) { for(Entry<String, Integer> groupedEntry:groupByCounts.entrySet()){ ProducerRecord<String, Integer> producerRecord = new ProducerRecord<>("group-by-counts", groupedEntry.getKey(), groupedEntry.getValue()); producer.send(producerRecord); } consumer.commitSync(); }
  • 11. GroupBy Example if(counter++ % sendInterval == 0) { for(Entry<String, Integer> groupedEntry:groupByCounts.entrySet()){ ProducerRecord<String, Integer> producerRecord = new ProducerRecord<>("group-by-counts", groupedEntry.getKey(), groupedEntry.getValue()); producer.send(producerRecord); } consumer.commitSync(); }
  • 12. 12 Streams GroupBy ... stream = streamBuilder.stream(Arrays.asList(“A”, “B”)) stream.groupByKey() .count() .toStream() .to(“output-topic”, Produced.with(Serdes.String(), Serdes.Long()))
  • 13. 13 Streams GroupBy ... stream = streamBuilder.stream(Arrays.asList(“A”, “B”)) stream.groupByKey() .count() .toStream() .to(“output-topic”, Produced.with(Serdes.String(), Serdes.Long()))
  • 14. 14 Streams GroupBy ... stream = streamBuilder.stream(Arrays.asList(“A”, “B”)) stream.groupByKey() .count() .toStream() .to(“output-topic”, Produced.with(Serdes.String(), Serdes.Long()))
  • 15. 15 Stateful Stream Processing Streams Stateful Operations • Joins • Windowing operations • Aggregation/Reduce Using any of these operations, Streams creates a state store
  • 16. 16 Making Streams Results Queryable Kafka Streams Application KAFKA External Application / REST Service
  • 17. 17 Making Streams Results Queryable Kafka Streams Application KAFKA External Application / REST Service Database
  • 18. 18 Making Streams Results Queryable Kafka Streams Application KAFKA External Application / REST Service Database
  • 19. 19 Making Streams Queryable stream.groupByKey() .count() .toStream() .to(“output-topic”, Produced.with(Serdes.String(), Serdes.Long())) .. consumer.poll(Duration.ofSeconds(5)); for (ConsumerRecord<String, String> record : records) { someService.save(record.key(), record.value()) .. } ..
  • 20. 20 Making Streams State Directly Queryable ... stream = streamBuilder.stream(Arrays.asList(“A”, “B”)) stream.groupByKey() .count(Materialized.as(“count-store”)) .toStream() .to(“output-topic”, Produced.with(Serdes.String(), Serdes.Long()))
  • 21. 21 Making Streams State Directly Queryable Properties props = new Properties(); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "ks-interactive-stock-analysis-appid"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); properties.put(StreamsConfig.APPLICATION_SERVER_CONFIG, host+":"+port); ...
  • 22. 22 Making Streams State Directly Queryable Kafka Streams Application KAFKA Embedded RPC
  • 23. 23 What’s with the APPLICATION_SERVER_ID • A single Streams instance doesn’t contain all keys • Streams will query other instances for store misses • A single Streams instance can be proxy for all instances
  • 24. 25 Making Streams Results Queryable Streams app “A” Host = hostA:4567 KAFKA Streams app “B” Host = hostB:4568
  • 25. 26 Making Streams Results Queryable Streams app “A” Host = hostA:4567 Metadata -> hostB:4568 KAFKA Streams app “B” Host = hostB:4568 Metadata -> hostA:4567
  • 26. 27 Topic Partitions and Streams Tasks Streams app “A” Host = hostA:4567 Streams app “B” Host = hostB:4568 State Store State Store Topic with four partitions Four partitions are converted to 4 tasks so each streams application is assigned 2 partitions/tasks
  • 27. 28 Making Streams Results Queryable Streams app “A” Host = hostA:4567 Streams app “B” Host = hostB:4568 State Store State Store {“ENERGY”:”10000”} written to partition 0 assigned to App A {“FINANCE”:”11000”} written to partition 1 assigned to App B
  • 28. 29 Making Streams Results Queryable Streams app “A” Host = hostA:4567 Streams app “B” Host = hostB:4568 State Store State Store {“ENERGY”:”10000”} written to partition 0 assigned to App A {“FINANCE”:”11000”} written to partition 1 assigned to App B http://hostA:4567?key=FINANCE
  • 29. 30 Example of a Streams RPC Kafka Streams Application KAFKA { JS } Demo Time!
  • 30. 31 Embedding the Web Server KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), streamsConfig); InteractiveQueryServer queryServer = new InteractiveQueryServer(kafkaStreams, hostInfo);
  • 31. 32 Embedding the Web Server . kafkaStreams.setStateListener(((newState, oldState) -> { if (newState == KafkaStreams.State.RUNNING && oldState == KafkaStreams.State.REBALANCING) { queryServer.setReady(true); } else if (newState != KafkaStreams.State.RUNNING) { queryServer.setReady(false); } }))
  • 32. 33 Embedding the Web Server . kafkaStreams.setStateListener(((newState, oldState) -> { if (newState == KafkaStreams.State.RUNNING && oldState == KafkaStreams.State.REBALANCING) { queryServer.setReady(true); } else if (newState != KafkaStreams.State.RUNNING) { queryServer.setReady(false); } }))
  • 33. 34 Embedding the Web Server public void init() { get("/window/:store/:key/:from/:to", (req, res) -> ready ? fetchFromWindowStore(req.params()) : STORES_NOT_ACCESSIBLE); get("/window/:store/:key", (req, res) -> ready ? fetchFromWindowStore(req.params()) : STORES_NOT_ACCESSIBLE); get("/kv/:store", (req, res) -> ready ? fetchAllFromKeyValueStore(req.params()) : STORES_NOT_ACCESSIBLE); get("/kv/:store/:local", (req, res) -> ready ? fetchAllFromLocalKeyValueStore(req.params()) : STORES_NOT_ACCESSIBLE); get("/session/:store/:key", (req, res) -> ready ? fetchFromSessionStore(req.params()) : STORES_NOT_ACCESSIBLE); get("/iq", (req, res) -> { res.redirect("interactiveQueriesApplication.html"); return ""; });
  • 34. 35 Embedding the Web Server fetchFromSessionStore(Map<String, String> params) { String store = params.get(STORE_PARAM); String key = params.get(KEY_PARAM); HostInfo storeHostInfo = getHostInfo(store, key); if (storeHostInfo.host().equals("unknown")) { return STORES_NOT_ACCESSIBLE; } if (dataNotLocal(storeHostInfo)) { return fetchRemote(storeHostInfo, "session", params); } ReadOnlySessionStore<String, CustomerTransactions> readOnlySessionStore = kafkaStreams.store(store, QueryableStoreTypes.sessionStore());
  • 35. 36 Embedding the Web Server getHostInfo(String storeName, String key) { StreamsMetadata metadata = kafkaStreams.metadataForKey(storeName, key, stringSerializer); return metadata.hostInfo(); }
  • 36. 37 Embedding the Web Server fetchFromSessionStore(Map<String, String> params) { String store = params.get(STORE_PARAM); String key = params.get(KEY_PARAM); HostInfo storeHostInfo = getHostInfo(store, key); if (storeHostInfo.host().equals("unknown")) { return STORES_NOT_ACCESSIBLE; } if (dataNotLocal(storeHostInfo)) { return fetchRemote(storeHostInfo, "session", params); } ReadOnlySessionStore<String, CustomerTransactions> readOnlySessionStore = kafkaStreams.store(store, QueryableStoreTypes.sessionStore());
  • 37. 38 Embedding the Web Server fetchFromSessionStore(Map<String, String> params) { String store = params.get(STORE_PARAM); String key = params.get(KEY_PARAM); HostInfo storeHostInfo = getHostInfo(store, key); if (storeHostInfo.host().equals("unknown")) { return STORES_NOT_ACCESSIBLE; } if (dataNotLocal(storeHostInfo)) { return fetchRemote(storeHostInfo, "session", params); } ReadOnlySessionStore<String, CustomerTransactions> readOnlySessionStore = kafkaStreams.store( store, QueryableStoreTypes.sessionStore());
  • 38. 39 Embedding the Web Server fetchFromSessionStore(Map<String, String> params) { String store = params.get(STORE_PARAM); String key = params.get(KEY_PARAM); HostInfo storeHostInfo = getHostInfo(store, key); if (storeHostInfo.host().equals("unknown")) { return STORES_NOT_ACCESSIBLE; } if (dataNotLocal(storeHostInfo)) { return fetchRemote(storeHostInfo, "session", params); } // Iterate over readOnlySessionStore and // store results in a list sessionResults return gson.toJson(sessionResults);
  • 39. 40 Client View Development <body> <h2>Kafka Streams Equities Dashboard Application</h2> <!–- Other div elements left out for clarity --> <div id="sessionDiv"> <h3 id="sessionHeader">Customer Session Equity Activity Table</h3> <table id="sessionTable"> <tr> <th>Customer Id</th> <th>Average Equity Transaction Spent Per Session</th> </tr> </table> </div> </body>
  • 40. 41 Client View Development <script> function loadIqTables() { $.getJSON("/kv/TransactionsBySector", function (response) { updateTable(response, $('#txnsTable')) $('#txnsHeader').animate({color:'red'},500).animate({color:'#CCCCCC'}, 500) }) updateTableWithList("/window/NumberSharesPerPeriod/", symbols, $('#stockTable'), $('#stockHeader')); updateTableWithList("/session/CustomerPurchaseSessions/", customers, $('#sessionTable'), $('#sessionHeader')) } setInterval(loadIqTables, 7000); </script>
  • 41. 42 Client View Development <script> function loadIqTables() { $.getJSON("/kv/TransactionsBySector", function (response) { updateTable(response, $('#txnsTable')) $('#txnsHeader').animate({color:'red'},500).animate({color:'#CCCCCC'}, 500) }) updateTableWithList("/window/NumberSharesPerPeriod/", symbols, $('#stockTable'), $('#stockHeader')); updateTableWithList("/session/CustomerPurchaseSessions/", customers, $('#sessionTable'), $('#sessionHeader')) } setInterval(loadIqTables, 7000); </script>
  • 42. 43 Summary Interactive Queries is a powerful abstraction that simplifies stateful stream processing There are still cases for which external database/storage might be a better
  • 43. 44 Summary Kafka Streams in Action Examples: https://github.com/bbejeck/kafka-streams-in- action/blob/master/src/main/java/bbejeck/webserver/InteractiveQueryServer.java Music example: https://github.com/confluentinc/examples/blob/master/kafka- streams/src/main/java/io/confluent/examples/streams/interactivequeries/kafkamusic/ KafkaMusicExample.java Streaming Movie Ratings: https://github.com/confluentinc/demo- scene/tree/master/streams-movie-demo
  • 44. 45 Thanks! Stay in Touch! • https://slackpass.io/confluentcommunity • https://www.confluent.io/blog/ • Twitter @bbejeck • We are hiring! https://www.confluent.io/careers/
  • 45. NOMINATE YOURSELF OR A PEER AT CONFLUENT.IO/NOMINATE
  • 46. KS19Meetup. CONFLUENT COMMUNITY DISCOUNT CODE 25% OFF* *Standard Priced Conference pass