I would like the messenger bot to notify the user that their session ended if they did not write/give input to the bot for some time. In order to do so, I first thought about using setTimeout() for each user which will reset upon activity. But that means if there will be 100 active users, there will be 100 Timeouts at the same time.
I wanted to know, if having one Interval instead that checks through each user`s session end timestamp every 30-60 seconds a better approach? The active users are stored in memory.
setTimeout is more precise in your case: each session will be ended independently and closer to the time it was supposed to end. It will also spread the activity more evenly. Since JS is single-threaded, the timeouts will not fire in parallel, even though there will be hundreds of them at the same time.
setInterval will create spikes of activity every 30-60 seconds, and will sometimes let the sessions stay alive longer than they should.
As per the cost of multiple timeouts running at the same time, please see this answer.
Related
I am using the firebase Stripe API, and what is happening is my app doesn't have a lot of traffic yet, nor will it for a little while. Firebase decided, after 2-3 minutes of no invocations on the function, it goes into cold start mode. This is unfortunate because it means my wait time from when a new user hits register, and goes to the checkout page, it is like 8 seconds. How horrendous is that!
Anyways, does anyone know a way around this, maybe setting a script to run in the background at all times, or something I can do from inside firebase?
One way to help is to add a "cold-start" command to the Cloud Function (i.e. a "no-op" invocation/call), and invoke it when your user starts the checkout process (before collecting any information). If the User doesn't complete check-out, no-harm-no-foul; if they do, the cloud function has already been started.
Update 2020-01-01:
Firebase now allows you to designate for each function, in the console, a minimum (and/or maximum) number of invocations - i.e. keeping functions in memory. A single active function costs about $0.33 to $0.50 per month - a fairly low (but not zero) cost for keeping cold starts down...
I've been working on an idle/incremental game in my free time.
The main game loop function gets called many times a second using setInterval.
Since chrome (and probably other browsers) throttle function calls to 1 per second, my game loop doesn't properly update the right amount of times so now im looking into web workers.
After reading through the WebWorkers documentation on MDN, i still have a question on how to properly implement the web worker.
My current idea is to detect when the user swaps tabs (onblur):
Pause the setInterval for gameLoop
Post a message to my worker with the current game state
Within the worker, continue computing the game state
When tab gets refocused, send message back and update game state with message
unpause setInterval and terminate worker.
Would this be the right way to use the Web Worker?
Thanks!
-EDIT-
Some additional info, my game is an idle game similar to cookie clicker so there isnt any position tracking.
A very brief idea of something that is within my gameLoop is a function call to gainResources(resourcePerSecond/gameTickRate).
My solution to stopping background tabs from throttling is to calculate the difference in time between each loop, and use that value to calculate how much things should've changed, assuming your loop updates things like resource amounts.
Example -
function loop() {
let now = Date.now();
let diff = now - Game.lastUpdate;
Game.lastUpdate = now;
// diff is now the exact amount of ms since loop has been called.
}
This way you are also sure to give an accurate production rate as setInterval doesn't call functions at exactly the same interval every time.
Let's say I have 1000 concurrent socket.io connections.
On disconnect, I would like to give at least 30 seconds for the user to re-connect and maintain its session, so I thought of adding a timer to do that.
Would that be cpu intensive considering the timers would run for 30 seconds and only execute simple database queries? This is backend btw, so no browser.
Thanks
Would that be cpu intensive considering the timers would run for 30 seconds and only execute simple database queries?
You don't want a timer to run every 30 seconds and run database queries when there's no disconnected sockets. That's kind of like "polling" which is rarely the most efficient way of doing things.
What would make more sense is to set a 30 second timer each time you get a socket disconnect. Put the timerID in the session object. If the user reconnects, upon that reconnect, you will find the session and find a timerID in there. Cancel that timer. If the user does not reconnect within 30 seconds, then the timer will fire and you can clear the session.
Timers themselves don't consume CPU so it's no big deal to have a bunch of them. The node.js timer system is very efficient. It keeps track of when the next timer should fire and that is the only one that is technically active and set for a system timer. When that timer fires, it sets a system timer for the next timer that should fire. Timers are kept in a sorted data structure to make this easy for node.js.
So, the only CPU to be consumed here is a very tiny amount of housekeeping to organize a new timer and then whatever code you're going to run when the timer fires. If you were going to run that code anyway and it's just a matter of whether you run it now or 30 seconds from now, then it doesn't make any difference to your CPU usage when you run it. It will consume the same amount of total CPU either way.
So, if you want to set a 30 second timer when each socket disconnects, that's a perfectly fine thing to do and it should not be a noticeable impact on your CPU usage at all.
Here's a reference article that will help explain: How does Node.js manage timers internally and also this other answer: How many concurrent setTimeouts before performance issues?
Just to be clear my understanding of long polling is that you make request to a server on a time interval.
I am trying to implement a bitcoin purchasing system that checks the blockchain for change in my wallets balance. I know there are websockets that do this but I have to wait for 1 confirmation to receive an update and the REST API offers more flexibility, so I would just prefer to make a request to the server every 5 seconds or so and check each response for a change in my balance then go from there.
The issue is I can't seem to figure out how to do this in NodeJS. Functionially this is how I imagine my code.
Get current balance (make request)
Get current balance again (make request)
Check if there is a difference
**If not**
wait 5 seconds
Get current balance
Check for difference
repeat till different (or till timeout or something)
If different
do some functions and stop checking balance.
I've been trying to do each step but I've gotten stuck at figuring out how to create a loop of checking the balance, and stopping the loop if it changes.
My original thought was to use promises and some for loops but that doesn't materialize.
So now I am asking for your help, how should I go about this?
One way to do this would be to setup a setInterval timer to kickoff a request every x seconds. By setting some logic after the response you can then choose to de-reference the timer and trigger another function. Here's a snippet. You'll notice I set a variable to reference the timer, and then de-reference it by setting it to null, where then the GC is smart enough to release. You may also use the 'clearTimeout' function, which is perhaps the better way to go.
My app's framework is built around collapsing backbone models sending the data via websockets and updating models on other clients with the data. My question is how should I batch these updates for times when an action triggers 5 changes in a row.
The syncing method is set up to update on any change but if I set 5 items at the same time I don't want it to fire 5 times in a row.
I was thinking I could do a setTimeout on any sync that gets cleared if something else tries to sync within a second of it. Does this seem like the best route or is there a better way to do this?
Thanks!
i haven't done this with backbone specifically, but i've done this kind of batching of commands in other distributed (client / server) apps in the past.
the gist of it is that you should start with a timeout and add a batch size for further optimization, if you see the need.
say you have a batch size of 10. what happens when you get 9 items stuffed into the batch and then the user just sits there and doesn't do anything else? the server would never get notified of the things the user wanted to do.
timeout generally works well to get small batches. but if you have an action that generates a large number of related commands you may want to batch all of the commands and send them all across as soon as they are ready instead of waiting for a timer. the time may fire in the middle of creating the commands and split things apart in a manner that causes problems, etc.
hope that helps.
Underscore.js, the utility library that Backbone.js uses, has several functions for throttling callbacks:
throttle makes a version of a function that will execute at most once every X milliseconds.
debounce makes a version of a function that will only execute if X milliseconds elapse since the last time it was called
after makes a version of a function that will execute only after it has been called X times.
So if you know there are 5 items that will be changed, you could register a callback like this:
// only call callback after 5 change events
collection.on("change", _.after(5, callback));
But more likely you don't, and you'll want to go with a timeout approach:
// only call callback 30 milliseconds after the last change event
collection.on("change", _.debounce(30, callback));