Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to build push notification system using express.js and socket.io

i am using express.js and socket.io together for realtime push notification system. which are working fine, i share some line of code which i am using on server side

 var app = express();
 var server = require('http').Server(app);
 var io = require('socket.io')(server);
 server.listen(appconfig.webPort, function() {
  console.log('server runing at ' + appconfig.webPort);
 });

 io.on('connection', function(socket) {
   var id = setInterval(function() {
    some database logic here to get data from database  
       socket.emit(data);
  }, 5000);
 });

my question is does this code increase load on server ? as i get the data from database on every few seconds. if it is harmful , what is the best way of doing the same.

like image 231
Meesam Avatar asked Oct 31 '22 06:10

Meesam


1 Answers

my question is does this code increase load on server ? as i get the data from database on every few seconds. if it is harmful , what is the best way of doing the same.

Of course it does increase the load. For every socket.io connection that is made to your server, you are starting a separate 5 second interval timer and on every time that timer fires, you are running one or more database queries and then sending those results to that client.

If you had 50 connected clients, you'd be running these queries every 100ms (5000 / 50). If you had 1000 connected clients, the average interval would be every 5ms. Besides keeping your database pretty busy, your server would be pretty busy too. If you had thousands of connected clients, the scaling gets rapidly worse.

If you're getting the same data for every client, then you should change the way you're doing this. Make one query to the database every 5 seconds and then send the same results to all the clients. That scales much, much better.

If you can avoid polling your database at all and rely on some sort of event triggers to detect changes, that usually works even better.

like image 69
jfriend00 Avatar answered Nov 09 '22 06:11

jfriend00