Issue
I have a question regarding how to build a Java Spring API that can continuously update the frontend with a status. How I want this to go about is that I can via a POST-request "update" the status of our application, and this to then be information that is obtainable from the frontend with a GET-request. The POST-request is to be used from within a VM.
Just to try and make myself clear:
- Frontend "subscribes" to some sort of connection, identified by a user-id.
- A POST-request to the backend is fired from within a VM.
- This new status is broadcast to the correct connection (based on user-id) in out frontend application.
How would I go about to build this?
Our backend is a Java Spring Boot REST API and out frontend is a React webapplication.
Solution
If you need to continuosly update the front end with data coming from the back end a good idea is to use a WebSocket:
WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection.
Once a websocket has been established the server can send periodically update of status to the front end.
On the back end side you need to mantain a reference between each websocket and the user id so that when an update is detected for a particular user you can send that information to the correct web socket.
This is often used in realtime applications like chats, but you can use it for any kind of application where the back end need to push updates frequently to the front end.
Other options that you can use are:
- polling
- long polling
In the polling is the front end that periodically ask the back end to get new data. So you need to define a scheduling policy to request new data. If the scheduling is not too frequent the risk is that you don't see enough updates. If the scheduling is too much frequent the problem is that you are busying resources on when not needed.
A long polling is an enhanced form of polling where the back end doesn't answer immediately if no data are available but holds the connection for a period of time until when data are available or a timeout is reached. This solution uses better the resources, but the websocket still remains the best solution to adopt.
Answered By - Davide Lorenzo MARINO