I have a bullCollections where I save some information about some messages example
try {
let bullPayload = {
type: 'message',
payload: {
messsages: messagesForPreProcessingData,
sessionID: this.data['sessionID'],
socketID: parseInt(this.data['socketID']),
},
await bullConnections[accumulatorQueue].add(bullPayload, {
removeOnComplete: true,
});
};
The code works fine but I was asked to change the logic here, according to some statistics the messages are taking too much time to be shown to some users ( from bad wifi) and I come up with a solution that the front end will calculate the time taken from server to client and if that took longer than 400ms a new request will be sent so that the backend will know that the messages took a long time to load.
I made a timeout like this
saveBullPayloadWithTimeout(key, timeDuration, bullPayLoad, messages, events) {
let redis = this.data.dbRedisConfigur.dataRedis;
return new Promise((resolve, reject) => {
setTimeout(() => {
redisConnections[redis].get(key, (err, result) => {
if (err) {
reject(err);
} else {
if (result) {
redisConnections[redis].del(key, (err, result) => {
if (result == 1) {
} else {
logErrors({ message: 'CANNOT DELETE KEY' });
}
});
} else {
bullConnections[accumulator].add(bullPayLoad, {
removeOnComplete: true,
});
console.log('AFTER');
this.updateCurrentMessages(messages, events);
}
}
});
}, timeDuration);
});
}
So this piece of code should wait for 5 seconds so that it can know whether to insert the message or not. During these 5 seconds, the backend waits for a second request if a second request has been made it saves data to Redis and after 5 seconds it will check that data if it exists then it won't save the message otherwise it will save it.
Does timeout affect the performance, because the backend will handle millions of users?
Is there any better way to separate this as a background process?
Does timeout affect the performance, because the backend will handle millions of users?
Timeouts, themselves, probably won't affect performance much. But your specific use of them will, because all it does is delay the process by timeDuration and then run it on the main thread, and you don't have anything in there (as far as I can tell) to cancel a previous one if a subsequent request is made that supercedes it.
Is there any better way to separate this as a background process?
setTimeout doesn't do its work as a background process. It doesn't even do it on a background thread. It's done on the same main thread that scheduled the timer. Using setTimeout just delays starting the work, it doesn't make the work happen on a different thread.
If you want something done in a different process, you'll need to spawn a child process.
If you want something done on a different thread, you'll need to spawn a worker thread.