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

I use express.js and socket.io together for a real-time notification system. which work fine, I share some lines of code that I use on the 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 server load? since I get data from the database every few seconds. if it is harmful, what is the best way to do the same.

+5
source share
1 answer

My question is, does this code increase server load? how do i get data from the database every few seconds. if it is harmful, then what is the best way to do the same.

Of course, this increases the load. For each socket.io connection that is created on your server, you start a separate timer with an interval of 5 seconds and each time the timer fires, you start one or more database queries and then send these results to this client.

If you had 50 connected clients, you will run these requests every 100 ms (5000/50). If you have 1000 connected clients, the average interval will be every 5 ms. Besides the fact that your database is very busy, your server will also be very busy. If you had thousands of connected clients, scaling quickly degrades.

If you get the same data for each client, you should change the way you do it. Make one query to the database every 5 seconds, and then send the same results to all clients. It is much bigger, much better.

If you don't have to try your database at all and rely on some kind of event triggers to detect changes, this usually works even better.

+2
source

Source: https://habr.com/ru/post/1246285/


All Articles