Skip to content

Instantly share code, notes, and snippets.

@Paul-Reed
Created March 29, 2014 20:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paul-Reed/9410e4cebcc4b68fae73 to your computer and use it in GitHub Desktop.
Save Paul-Reed/9410e4cebcc4b68fae73 to your computer and use it in GitHub Desktop.
Rate Limiter

Whilst the delay module has a function to limit rates, it buffers the unsent msg's and dispatches them in sequence according to the limit rate set.
This code (courtesy of Nick O'Leary) limits the msg flow similar to above, except it 'throws away' all of the intermediate msg's, instead of queuing them. A further advantage is that you can set the limit rate to any value (within reason!) instead of being constrained to 1 sec,1 min, 1 hr.

The limit rate is set in the first line of code (in milliseconds).

Paul

[{"id":"3a82b835.c57d48","type":"function","name":"Rate Limiter","func":"var interval = (1000*60*10); // minimum interval between messages (ms)\ncontext.lastTime = context.lastTime || 0;\n\nvar now = Date.now();\n\nif (now-context.lastTime > interval) {\n context.lastTime = now;\n return msg;\n} else {\n return null;\n}","outputs":1,"x":327,"y":756,"z":"3f1992f2.c0e66e","wires":[[]]}]
@shanness
Copy link

Thanks for this! Was the only throttling/rate limiting one that almost did what I needed :)

Here's an improved version that allows overriding the interval, and groups rate limiting by topic (perfect say for an alert system, where you only want to hear each particular alert once per 20 minutes).

[{"id":"5b24df49.412f6","type":"function","z":"136ed48.14e8c2c","name":"Rate Limiter","func":"// Defaults to 10 minutes, overridable with msg.ratelimitms\n// Will limit per topic (including by null ones)\nvar interval = msg.ratelimitms || (1000*60*10); // minimum interval between messages (ms)\nvar key = \"lastTime\" + (msg.topic || \"null_topic\");\nvar lastReleased = context.get(key) || 0;\n\nvar now = Date.now();\n\nif (now-lastReleased > interval) {\n context.set(key,now);\n return msg;\n} else {\n return null;\n}","outputs":1,"noerr":0,"x":849.0173358917236,"y":438.0104217529297,"wires":[[]]}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment