Search code examples
websocketchatsocial-networking

In a group chat, should the new message event (websocket) be sent by the client or the API?


I have a doubt, in a group chat system that has a database with a rest API, who should issue the event of a new message?

The client or the endpoint to create the new message?

For example: X user sends a message to group Y, then uses the api endpoint api.com/message-create and that endpoint emits the message-create event through websocket

Example 2: X user sends a message to group Y, then uses the api api.com/message-create endpoint and the endpoint does not emit the message-create event, but was emitted when the user pressed the send message button

I still don't quite understand if it would occupy more websocket channels to achieve that, if a global one is enough, etc.


Solution

  • The server should be responsible for communication logic. So your first example is better.

    But: why do you use two communication channels for sending an creating messages? If you use websocket, you don't need create a message from a client by using additional rest endpoint. This approach is prone to errors. For example if the client will loose network connection after sending message through websocket and before executing call to the REST endpoint? The message will not be stored in a database.

    Your flow should looks as follows:

    1. User clicks the send button.
    2. Message is send through the websocket.
    3. Message is stored in the database asynchronously (you can do it directly from communication server, or use rest endpoint)
    4. Emit "new message" event to the group.