vendredi 7 mai 2021

In what layer should I place websocket calls in a layered architecture?

I'm starting to work with NestJS, a Javascript framework for building RESTful api's.
The framework encourages you to work with multilayered architecture, separating controllers, services and repositories.

In this project of mine, I have a RESTful api that talks to my website, and I'm currently in the need of using websockets for several reasons.

The general behavior of a module that will use the websocket protocol (in my app) is:
client makes http request with a message -> backend validates -> backend broadcasts the message through websockets.
Much like a chat application.

The problem is that I'm having a hard time figuring out where is the best place to put these broadcast calls. It seems like every layer is the wrong place.
I won't even consider the repository layer. Talking strictly about whether should I choose the controller or the service, they both seem wrong.

I don't want to send websocket messages in the same place where I handle HTTP requests, and I sure don't want to send them in the same place were I deal with business rules.

I've come to an approach, but I'm not sure if it's necessary to do it. I'm using Redis as caching mechanism, and as a store to Socket.io, so that I can horizontally scale my app and consistently send broadcast messages through sockets. Redis also has a Pub/Sub feature within it, and an awesome notification system called "keyspace notifications" that will publish messages to channels depending on the action performed in the cache memory store. Long story short, HTTP requests changes resources in the backend, these changes are reflected in my Redis cache and, with a (to-be) well crafted key design system, I can listen to the modifications in the cache from another, separate, module and fire the necessary broadcasts.
An illustration of the structure:
                     enter image description here

Aucun commentaire:

Enregistrer un commentaire