Reputation: 243
I am working on a chat application using Node js, socket.io, React js where I am emitting socket event to node server and it calls another API(node js) to save data(message) on DB. when I trying to send messages very quickly, After that the node server hangs and socket disconnects and connects frequently. After sometimes(approx 5 mins) node server works perfectly. Please tell me what I am doing wrong.
Currently, I am testing for only 2 users.
Here is a code snippet.
io.on('RequestSendNewMessage', (message)=>{
// console.log('message', message);
headers['wh-user-id'] = message.user_id;
makeRequest({data: message, method: 'POST', url: `${workstream}/v1/workstream/send-message`, headers})
.then( async (response) => {
const message_count = await makeRequest({params: {}, method: 'GET', url: `${workstream}/v1/workstream/message-count`, headers})
socket.emit('RespondNewMessageCount', message_count.data.data);
socket.emit('RespondSendNewMessage', response.data);
})
.catch(error => {
console.log('errror', error.response.data);
socket.emit('newMessageError', error.response.data)
})
})
Upvotes: 0
Views: 1141
Reputation: 144
It is highly recommended to use message queuing in these scenarios...As long as you are calling another api's to perform some DB operation, It keeps your node thread busy...
To avoid this, you can store the message in message queuing tool(RabbitMQ)received through socket, and close the connection, by doing this, node thread can be ideally utilized
Later the messages published into RabbitMQ, can be consumed by your worker(separate node server) and it will take care of storing messages into your DB and sending chat messages....As the worker is being influenced by the message QUEUE, it would work one by one (FIFO) message and no mess will take place
Please refer : https://medium.com/better-programming/implementing-rabbitmq-with-node-js-93e15a44a9cc
(Note: It is good to keep the worker as a separate server)
Upvotes: 2