Server Sent Events with Kotlin + Redis

Jose Figueredo
4 min readNov 16, 2020

--

In this article I will show you one simple approach to understand SSE using the programming language Kotlin and Redis channels

Some foundation first:

SSE is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.

The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C

Polling is when you want some specific data or state from the server and it isn’t available yet so you have to request over and over until it is available.

Cons of polling

– Overcharges the server load

– Overload networks with useless data because the polling will send data even if they didn’t change

– Consumes 75% to 95% more of the end-user battery than pushing

– Requires 3 round-trips (TCP SYN, SSL and Data)

Use cases

  • Server/product availability
  • Prices
  • Social
  • Chat
  • Game scores
  • Trading
  • Dashboards

How about Web Sockets?

Web Sockets has many advantages but in some use cases the use of SSE is advised.

When not to use Web Sockets

  • When you don’t need bi direction
  • When you need to automatically recover from disconnections: SSE has built-in support for re connection and event-id
  • When you need error handling at protocol level: SSE are mono directional from server to client with http protocol with error handling standards, Web Sockets use https protocol
  • When performance is an issue: SSE provides better performance
  • When you are behind a corporate firewall: SSE has no trouble with corporate firewalls doing packet inspection

How does SSE works ?

A client subscribes to a stream from a server and the server will send messages (“event-stream”) to the client until the server or the client closes the stream. It is up to the server to decide when and what to send the client.

The event-stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event-stream are separated by a pair of newline characters (“\n”).

The following field names are defined in the specification:

Event: The event’s type. It will allow you to use the same stream for different content. A client can decide to “listen” only to one type of event or to interpret differently each event type.

Data: The data field for the message. You can put consecutive “data” lines.

ID: ID for each event-stream. Useful to track lost messages.

Retry: The time to use before the browser attempts a new connection after all connections are lost (in milliseconds).

Browser Support

  • Internet Explorer: No
  • Mozilla Firefox: Yes (Starting with Firefox 6)
  • Google Chrome: Yes (Starting with Chrome 6)
  • Opera: Yes (Starting with Opera 11.5)
  • Safari: Yes (Starting with Safari 5.0)
  • Microsoft Edge: Yes (Starting with Edge 79)

The PoC

Let’s imagine that we want to subscribe to a tweet channel and we want to publish tweets in this channel so every subscriber can see it in real time.

Our model will be a tweet data class with a unique identification and creating date auto generated in construction time

The available endpoints will be one to subscribe to a channel called /stream and one to publish called /tweet

In our repository when someone subscribes we will listen to the desired channel and every time a tweet is published we will fire up the message to every subscriber

Also in the repository lives the code that send messages to the channel as follows

The code in the handler is similar to any other response adding the the sse() that is a shortcut for setting MediaType.TEXT_EVENT_STREAM as Content-Type header.

Testing

Case #1

In a terminal the first tests will be publish without subscribers:

The response will be 0 because zero subscribers had received the tweet

Case #2

In the terminal #1 we will subscribe to the tweets channel

In the terminal #2 we publish a new tweet

The response in the terminal #2 will be 1 because one subscriber have received the message, and the response in the terminal #1 will be the content of the tweet

Conclusion

In this article I show you how to easily test server sent events and gave you some technical background, use cases and pros & cons of it. You can now decide whenever go with Web Sockets or SSE, but you can not keep long polling those poor backend servers. You may ask but what about RSockets? Well this will be a matter of another post.

Full source code

You can test all the routers cloning this repo https://github.com/josefigueredo/kotlin-sse-example and calling the shell scripts in the test section in the same way as I do in the demo.

--

--

Jose Figueredo
Jose Figueredo

Written by Jose Figueredo

Solutions/Cloud Architect. Software developer since forever

No responses yet