kafEEne #1: Websocket & Kafka

Say hello  to kafEEne ! A blog series which will show Kafka and Java EE examples

This one is about Kafka + (Java EE) Websocket API. Code is on Github and you can refer to the README on how to get this up and running using Docker. Although the focus is on Websocket, here is a list of other Java EE specs which have been used – EJB, CDI & a bit of JSON-B (part of Java EE 8)


Websocket based dashboard


  • Kafka Consumer is a @Stateless EJB
  • Initialized in the @PostConstruct callback
  • The consumer logic is executed within a while loop controlled by a (atomic) boolean flag which can potentially be mutated by the container. It sends the event data in form of a custom Payload object using CDI Events
  • Consumer shutdown is exposed within a @PreDestroy method where it invokes the wakeup method to interrupt the consumer while loop
  • A simple (one time) EJB timer job triggers the Consumer process – this is just for simplicity. No harm in exposing the consumer startup through, say, a REST endpoint

See Consumer for more details

Websocket endpoint

A server side Websocket endpoint which is actually does very little to be honest. Client can call it with the interested topic in the URL itself

  • The @OnOpen callback makes sure that the Websocket Session is added and tracked and the topic is added to the Session properties (Map)
  • @OnClose callback removes the Session from the memory


  • It is enabled by a CDI observer (@Observe) for the Payload object
  • Simply loops over all the Sessions and broadcasts the key-value pair (received from the Kafka topic) if it registered for that topic to begin with
  • It uses the JSON-B API to convert the Payload POJO to a JSON format

See KafkaWebsocketEndpoint for more details

Connected clients

  • A @Singleton EJB maintains a list of connected clients
  • Its provides a synchronized wrapper over the collection of Websocket Session objects

See Peers for more details

Websocket Client

A simple Javascript based front end. See index.html for more details. I am not a front end guy – please pardon me!

Producer application

It’s a bare bones Java based producer application which pushes random data to couple of Kafka topics

Further reading



About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java EE and tagged , , , , , , , . Bookmark the permalink.

1 Response to kafEEne #1: Websocket & Kafka

  1. Pingback: Kafka & Websocket | Simply Distributed

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s