What happens when your service is overwhelmed with traffic? Your server can do one of two things:
This library helps you do the latter.
toobusy polls the node.js event loop and keeps track of "lag",
which is long requests wait in node's event queue to be processed.
When lag crosses a threshold,
toobusy tells you that you're too busy.
At this point you can stop request processing early
(before you spend too much time on them and compound the problem),
and return a "Server Too Busy" response.
This allows your server to stay responsive under extreme load,
and continue serving as many requests as possible.
npm install toobusy
var toobusy =express = ;var app = ;// middleware which blocks requests when we're too busyapp;app;var server = app;process;
The one knob that the library exposes is "maximum lag". This number represents the maximum amount of time in milliseconds that the event queue is behind, before we consider the process too busy.
// set maximum lag to an aggressive value;
The default value is 70ms, which allows an "average" server to run at 90-100% CPU and keeps request latency at around 200ms. For comparison, a value of 10ms results in 60-70% CPU usage, while latency for "average" requests stays at about 40ms.
These numbers are only examples, and the specifics of your hardware and application can change them drastically, so experiment! The default of 70 should get you started.
There is nothing new under the sun. (Ecclesiastes 1:9)
Though applying "event loop latency" to node.js was not directly inspired by anyone else's work, this concept is not new. Here are references to others who apply the same technique: