Spring WebFlux + Server Sent Events (SSE)

Introduction

What options we have to gather long processing data from the backend to send out to the UI?
I can recall the followings:

  • open frequent connections – polling
  • keep an open connection – websocket

Server Sent Events

With Server Sent Events you’re able to send continous updates from the server.
As a client subscription from a client to a server for a stream.
Sometimes we don’t need a full bi-directional protocol (sending data back from client side), just a non-blocking flow data with the ability to process whole, but parts of the message of the connection.
Updates, time splitted data chunks from the server side to provide a fluent UI experience.

advantages:

disadvantages:

  • unidirectional protocol
  • simultaneous request limit (browser defaults: 6)

WebFlux

Reactive programming, the purpose of this type of data processing is the fluency and non-blocking nature.

There are more conceptual advantages, like: backpressure, split and delayed and limited processing of datas.

It supports asynchronous and event-driven concept in programing with a fluent stream-like API.

The reactive API is present in Spring since version 5

It can be used with the specific content types in between:

  • backend-backend server-client (SOA/microservice calls)
  • backend-ui server client (server-browser calls)

Example Project

I picked some sample data about a movie database.
Our sample application is very simple: We stream the file line-by-line. Convert the data into a data model and producing the result as a stream to the endpoint.
The client side subscribed to the backend endpoint and processing the data line-by-line.
This way we have a stream from a datasource till the client visualization streamlined.

Backend stream logs

UI streaming processing and visualization

Besides the standard Flux stream we only needed to use the EVENT_STREAM Mediatype. While on the UI client side EventSource interface is required to capture the stream.

For more details see the Webflux + SSE example project: https://github.com/PazsitZ/webflux_sse

Leave a Reply

Your email address will not be published. Required fields are marked *