Using Spring Beans in a Kafka Streams ExceptionHandler
There are many things to know before diving into Kafka Streams. If you haven’t already, check out these 5 things as a starting point. Bullet 2 mentions designing for exceptions. Ironically, this seems to be the most critical as well as most forgotten… until a SEV-1 (this is bad) issue rolls into your inbox and the frantic patch process is initiated.
Before the incident lands in your inbox, let’s look at an easy way to bridge your custom exception handler (deserialization or production) to Spring.
Why is this bridge needed? When Kafka Streams starts up, the configured exception handler(s) are instantiated via reflection deep inside the Stream’s internals. As a result, they have no awareness of Spring’s Application Context. The ‘configure’ method on the handler interface is passed the current stream’s configurations and nothing else. This likely won’t provide enough context to build robust error handling that can produce a record, dump something to the DB, call an ancillary service, fire off an alert, etc.
Bridge to Spring
To get around this design, we can create a simple bridge to our Application Context. The following Gist illustrates an approach that achieves this. Notice it implements ApplicationContextAware, which will hand off the current application context state that we can keep for later use. Two static methods are defined for bean lookup, one by Class and one by name and Class which can be used if you have multiple beans of the same Class.
Second, the new utility can now be tapped into during the configure method of your exception handler to pull out any beans that may be helpful in error handling. In this case, I’m showing an implementation of the ProductionExceptionHandler but the same pattern can be used for the deserialization exception handler.
That’s it! Have you found alternatives to this approach that work for your team? I’d love to hear about them in the comments.