I am playing with Kafka Streams and faced a situation which seems a little odd to me. I did search on this but could not find a proper answer. While processing the elements in the stream, if any unhandled exception occurs, following error happens and Kafka Streams can not recover, stops processing further messages then I need to restart my application.
2018-05-17 11:00:51.304 INFO 43810 --- [-StreamThread-3] o.a.k.s.p.internals.StreamThread : stream-thread [snapshot-stream-application-a1dbc5d4-1742-4af2-9919-d4f5f861bb36-StreamThread-3] Stream thread shutdown complete
2018-05-17 11:00:51.304 WARN 43810 --- [-StreamThread-3] o.a.k.s.p.internals.StreamThread : stream-thread [snapshot-stream-application-a1dbc5d4-1742-4af2-9919-d4f5f861bb36-StreamThread-3] Unexpected state transition from RUNNING to DEAD.
2018-05-17 11:00:51.305 ERROR 43810 --- [-StreamThread-3] c.u.kafkastreams.config.SnapshotStream : Error while processing:
org.apache.kafka.streams.errors.ProcessorStateException: task [0_4] Failed to flush state store KTABLE-SOURCE-STATE-STORE-0000000000
For sure catching all the exceptions will solve the problem, but I am looking for a proper exception handling mechanism for Kafka Streams. Here is my sample code:
private KafkaStreams streams;
@PostConstruct
public void runStreams() {
KStreamBuilder builder = new KStreamBuilder();
KTable<String, String> snapshotTable = builder.table(kafkaProperties.getInputTopic());
snapshotTable.toStream().foreach((key, value) -> {
process(value);
});
streams = new KafkaStreams(builder, consumerProps());
streams.cleanUp();
streams.start();
streams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
LOGGER.error("Error while processing:", e);
}
});
}
private void process(String message) {
simulateException(message);
LOGGER.info("Key: {} Value: {}", key, value);
}
private void simulateException(String message) {
if (message.contains("abc")) {
throw new RuntimeException();
}
}
@PreDestroy
private void closeStream() {
streams.close();
}
private Properties consumerProps() {
Properties config = new Properties();
config.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-application");
config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrap());
config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
config.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 10000);
config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
config.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 3);
return config;
}
(I did try with kafka-streams 0.11.0.0
and 1.1.0
)