How to Create a Server-Sent Events API with Spring Webflux and Kafka

Nil Seri
2 min readNov 13, 2021

Create an API with text/event-stream Response Type

Photo by kazuend on Unsplash

You should first add these dependencies to your Spring Boot project:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor.kafka</groupId>
<artifactId>reactor-kafka</artifactId>
</dependency>

Create your Kafka Receiver configuration class:

This is my custom deserializer class (with my custom “EventBaseModel”):

Create your Kafka Service:

This is the RestController class:

If you want to filter events (like by comparing a value in the event class with a parameter, etc.), you can add your method in “filter”. Here, I checked if the event belongs to my account by comparing the accountId in my event object to my accountId parameter. There is a heartbeat stream every 10 seconds to keep the connection alive. You will be receiving those when there are no events to receive from Kafka.

Postman does not support API calls with text/event-stream response type (it freezes if you try) so you can use cURL to test your API.

If you are using Windows, you can read how to install cURL here:

Logging in SSE is in my another post if you would like to have a look.

Happy Coding!

--

--

Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏻‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨