I have a chat application that is built using websockets, NodeJS and postgreSQL. On the client side the user sends the message and socket io server on nodejs receives the event, saves the result in postgreql database using pg npm package and notifies all the connected sockets with new message.
It all works fine until the nodejs socket server starts to receive very large number of messages in small time. For example, 1000 new messages sent from different client browsers to web socket server that needs to insert that into database and then send the newly sent message to recipients.
I want to know how to speed this up? I am already using connecting pooling on postgresql database server but still insert statements take lot of time when executed in very small amount of time.
Do I need to use some queuing system on server? If so what are options?
Here is may current code snippet:
Client Side:
socket.emit('message', {message: 'Hi', user_id: 125, room_id: 100});
Here is my server side code (node.js+socket.io library)
socket.on('message', function(data){
var query = connection.query(new pg.Query("INSERT INTO message(room_id, user_id,message,sent_datetime) values($1, $2,$3,$4
) RETURNING conversation_message_id", [data.room_id, data.user_id, data.message, new Date()));
query.on('end', function (result) {
io.sockets.in(data.room_id).emit('new_message', result);
});
});
On client side again:
socket.on('new_message', function(newMessage){
//Render logic in message window
});