NodeJs throttle data

I would like to know, how to use javascript to achieve my use case,

My app receives a post request, then it incr memcache key, then it publish the increased value straightaway to users(mobile app) using third party API.

Eg. first requst value become 1, publish 1. second request value become 2, publish 2 ...

It works fine with requests less than 2k within 30 secs. If the requests number goes up to 10k, users(mobile app) may receive too many messages from publisher(battery consuming)

So I have to the throttle publishing calls, instead of publishing per request, I want to publish the value every second. In 1 second, the value can be 1, then publish 1. In 2 second then value can be 100, then publish 100. So that I saved 99 publish calls.

When requests are not coming anymore, I don't want a worker keep running every second.

Each time it increments, cache the new value to a global variable and post it to clients using setInterval. Here is a simple example:

var key = 0;

// Update the cache to the present
// value on application start
memcache.get('key', updateKey);

// Handle increment request and
// save the new value
app.post('/post', function(req, res){
  memcache.incr('key', updateKey);
});

// Update the cached key
function updateKey(err, val){
  key = val;
}

// Publish to clients once
// a second
function publish(){
  clients.emit(key);
}

setInterval(publish, 1000);

Starting and stopping this routine is a little more involved and may depend on how you're serving requests / incrementing the value.

Take a look at node-rate-limiter

You can implement it in a number of ways to solve your problem...