Go Real-Time with Ballerina WebSockets

Bhashinee Nirmali
Ballerina Swan Lake Tech Blog
5 min readJul 28, 2021

Nowadays, seamless communication between applications is a critical necessity. Real-time applications ensure that clients (and also servers) get updates from server-side applications as they happen with minimum delay. The sooner you get data, the quicker you can react and make decisions.

To retrieve new data, methods such as short polling were used initially, where the client pings the server repeatedly. One major drawback with this method is that it consumes server resources with a lot of requests, where most of the responses would turn out to be empty. Then came long-polling, which had the downside of requests being timed out and the need to be issued periodically. Then came HTTP streaming, WebSockets, and Server-Sent Events(SSE) to address the problem of real-time communication between applications. But it was only WebSockets that proved to be reliable and efficient when it came to fully duplex, real-time communication.

Let’s discuss WebSockets!

Why WebSockets?

The WebSocket protocol gained its fame as it opened up a world of possibilities with real-time data. The protocol is famous for its long-held TCP connection established between the client and the server. Its full-duplex and low-latency data transfer capabilities allow developers to easily connect complex cloud services. And the event-driven architecture of the WebSocket protocol makes it easier to write real-time APIs.

The Ballerina WebSocket Package

Ballerina WebSocket is an all-in-one package where you get all the features you need to work with WebSockets using the Ballerina programming language. It provides a tested WebSocket client and server implementation that is compliant with the RFC 6455.

Additionally, it provides a whole bunch of security features starting from transport layer security SSL/TLS to application layer security, such as Basic Auth, JWT, and OAuth2.

Use Case: A Real-time Taxi Service Management Application

Let’s see how a taxi service management application can be implemented using the Ballerina WebSocket library. This is certainly a simplified representation of a real-life implementation created for demonstration purposes.

There are three parties involved:

  1. Taxi Management Service — The WebSocket server
  2. Drivers — Use the driver application
  3. Riders — Use the rider application

Drivers can register for the Taxi Management Service. Assume that the drivers are given an application. Starting that application will register the drivers and then the drivers’ locations will be shared with riders. The WebSocket server acts as the intermediary between the riders and the drivers. All the data will be transferred through the server.

Users are capable of registering as riders via the rider application. Once they register, they’ll be updated about the availability of drivers and their locations. Driver locations will be updated as they move. All the connections are WebSocket connections.

Figure1 — Design diagram of the flow

Let’s see how easy it is to implement this simple scenario using Ballerina Swan Lake Beta 2.

  1. The WebSocket Server
    The WebSocket server behaves as the intermediate server between the users and drivers. So, drivers can send their location details to the server, and once a user gets registered, he/she will be notified of the real-time locations of those drivers.
    You can run the following code using the command below:
bal run ws-server.bal

2. Rider Application

After registering, riders will get updates about the live locations of taxis. Taxi location details will get printed on the console once you start the driver code sample.

You can run the following code using the command below:

bal run rider.bal

3. Driver Application
Drivers send their locations to the WebSocket server, and users will be updated via the server.

You can run the following code using the command below:

bal run driver.bal

Securing the WebSocket Connections

Ballerina provides inbuilt support for SSL/TLS and configurations to enforce authentication and authorization such as Basic Auth, JWT auth, and OAuth2.

Use SSL/TLS over WebSockets
You can configure a secure socket for your WebSocket listener and client to upgrade to a TCP connection with TLS. Following is an example where you can secure the taxiMgtListener with TLS.

The TLS-enabled Listener

In order to connect to the secured taxiMgtListener, drivers and riders should enable TLS as follows.

The TLS-enabled Client

Authentication and Authorization

Listener
The Ballerina WebSocket library provides built-in support for the following listener authentication mechanisms that are validated in the initial upgrade request.

  • Basic authentication
  • JWT authentication
  • OAuth2 authentication

To enable one of the above, you should configure the auth field in websocket:ServiceConfig annotation which consists of the following records:

  • FileUserStoreConfigWithScopes
  • LdapUserStoreConfigWithScopes
  • JwtValidatorConfigWithScopes
  • OAuth2IntrospectionConfigWithScopes

Each of the above records consists of configurations specific to each type as FileUserStoreConfig , LdapUserStoreConfig ,JwtValidatorConfig and OAuth2IntrospectionConfig respectively. You just have to configure them and there will be no need for any extensions or handlers. Ballerina will perform the required validation for you.

In the code snippet below, the taxi service has been enabled for OAuth2 validation.

Client

The Ballerina WebSocket client can be configured to send authentication information to the endpoint being invoked. The Ballerina WebSocket library also has built-in support for the following client authentication mechanisms.

  • Basic authentication
  • JWT authentication
  • OAuth2 authentication

The following code snippet shows how a WebSocket client can be configured to call a secured endpoint. The auth field of the client configurations (websocket:ClientConfiguration) should have either one of the CredentialsConfig, BearerTokenConfig, JwtIssuerConfig, OAuth2ClientCredentialsGrantConfig, OAuth2PasswordGrantConfig, and OAuth2RefreshTokenGrantConfig records. Once this is configured, Ballerina will take care of the rest of the validation process.

To connect to the OAuth2-secured taxi service, drivers and riders should configure OAuth2 as follows.

You can refer “WebSocket Security” section in Ballerina by Examples for complete code samples for both the listener-side and the client-side security.

WebSockets are a great choice for many use cases, such as multiplayer games, stock tickers, chat apps, or location-based apps, to name just a few. If you want to learn more about the Ballerina WebSocket library or if you’d like to find out more about Ballerina Language here are some useful links, for further exploration:

Hope you found this useful!

--

--